using System; using System.IO; using System.Collections.Generic; using OpenTK.Audio; using OpenTK.Audio.OpenAL; using org.budnhead.core; using org.budnhead.tools; namespace org.budnhead.audio { public static class nhBuffers { //public static List buffers = new List(); //public static List buffersNames = new List(); public static Dictionary buffers = new Dictionary(); private static List _files = new List(); private static List _searchPaths = new List(); //private static string filepath; public static void init() { buffers.Clear(); _files.Clear(); //_searchPaths = new List(); _searchPaths.Add("."); } public static void addSearchPath(string sPath) { _searchPaths.Add(sPath); } public static void loadSound(params string[] sName) { foreach(string a in sName) { string fullName = FileHelper.findFile(String.Format("{0}.wav", a), _searchPaths.ToArray()); Console.WriteLine("TEST: " + fullName); if (fullName != null) { Console.WriteLine("Sound found: {0}", fullName); _createBuffer(fullName, a); }else throw new FileNotFoundException("File not found."); } } private static void _createBuffer(string path, string sName) { Stream stream = File.Open(path, FileMode.Open); string name = sName; if (stream == null) throw new ArgumentNullException(nameof(stream)); using (BinaryReader reader = new BinaryReader(stream)) { //RIFF HEADER string signature = new string(reader.ReadChars(4)); if (signature != "RIFF") throw new NotSupportedException("File is not RIFF."); reader.ReadInt32(); string format = new string(reader.ReadChars(4)); if (format != "WAVE") throw new NotSupportedException("File is not WAVE."); //WAVE HEADER string format_sig = new string(reader.ReadChars(4)); if (format_sig != "fmt ") throw new NotSupportedException("File is not supported."); //Format Chunk Size reader.ReadInt32(); //Format reader.ReadInt16(); int channels = reader.ReadInt16(); int sample_rate = reader.ReadInt32(); //Byterate reader.ReadInt32(); reader.ReadInt16(); //Block allign int bits = reader.ReadInt16(); string data_sig = new string(reader.ReadChars(4)); if (data_sig != "data") throw new NotSupportedException("File is not supported"); //Data chunk Size reader.ReadInt32(); byte[] soundData = reader.ReadBytes((int)reader.BaseStream.Length); ALFormat fileFormat; switch (channels) { case 1: fileFormat = bits == 8 ? ALFormat.Mono8 : ALFormat.Mono16; break; case 2: fileFormat = bits == 8 ? ALFormat.Stereo8 : ALFormat.Stereo16; break; default: throw new NotSupportedException("File is not supported."); } int buffer = AL.GenBuffer(); AL.BufferData(buffer, fileFormat, soundData, soundData.Length, sample_rate); buffers.Add(name, buffer); } } } }