public static int PlaySound(string fileName, float volume = 1.0f) { if (volume * seBalance <= 0f) { return(0); } //don't play more than X sound effects in one frame if (soundIndex == playedSounds.Length) { return(0); } //don't play more than one instance of the same sound in one frame for (int ii = 0; ii < soundIndex; ii++) { if (fileName == playedSounds[ii]) { return(0); } } playedSounds[soundIndex] = fileName; soundIndex++; IntPtr stbVorbisData = FAudio.stb_vorbis_open_filename(fileName, out int error, IntPtr.Zero); FAudio.stb_vorbis_info fileInfo = FAudio.stb_vorbis_get_info(stbVorbisData); long total_samples = FAudio.stb_vorbis_stream_length_in_samples(stbVorbisData); long total_frames = total_samples * 60 / fileInfo.sample_rate; float[] chunk = new float[fileInfo.channels * total_samples]; int framesRead = FAudio.stb_vorbis_get_samples_float_interleaved(stbVorbisData, fileInfo.channels, chunk, fileInfo.channels * (int)total_samples); FAudio.stb_vorbis_close(stbVorbisData); DynamicSoundEffectInstance soundStream = new DynamicSoundEffectInstance( (int)fileInfo.sample_rate, (fileInfo.channels == 1) ? AudioChannels.Mono : AudioChannels.Stereo ); soundStream.Volume = volume * seBalance; soundStream.SubmitFloatBufferEXT(chunk, 0, framesRead * fileInfo.channels); soundStream.Play(); return((int)total_frames); }
public LoopedSong(string fileName) { stbVorbisData = FAudio.stb_vorbis_open_filename(fileName, out int error, IntPtr.Zero); FAudio.stb_vorbis_info fileInfo = FAudio.stb_vorbis_get_info(stbVorbisData); Channels = fileInfo.channels; SampleRate = (int)fileInfo.sample_rate; Name = Path.GetFileNameWithoutExtension(fileName); long total_samples = FAudio.stb_vorbis_stream_length_in_samples(stbVorbisData); FAudio.stb_vorbis_comment comments = FAudio.stb_vorbis_get_comment(stbVorbisData); loopStart = 0; loopEnd = (int)total_samples; int loopLength = 0; Tags = new Dictionary <string, string>(); for (int ii = 0; ii < comments.comment_list_length; ii++) { IntPtr ptr = new IntPtr(comments.comment_list.ToInt64() + IntPtr.Size * ii); IntPtr strPtr = (IntPtr)Marshal.PtrToStructure(ptr, typeof(IntPtr)); string comment = Marshal.PtrToStringUTF8(strPtr); string[] split = comment.Split('=', 2); string label = split.Length > 0 ? split[0] : ""; string val = split.Length > 1 ? split[1] : ""; if (label != "") { Tags.Add(label, val); } if (label == "LOOPSTART") { loopStart = Convert.ToInt32(val); } else if (label == "LOOPLENGTH") { loopLength = Convert.ToInt32(val); } } if (loopStart > -1) { if (loopLength > 0) { loopEnd = loopStart + loopLength; } } pcmPosition = 0; soundStream = new DynamicSoundEffectInstance( SampleRate, (Channels == 1) ? AudioChannels.Mono : AudioChannels.Stereo ); chunk = new float[chunkSize]; }