/// <summary> /// Streams audio into a floating point sample buffer. /// </summary> /// <param name="unityBuffer"></param> /// <param name="intermediateBuffer">A PCM sample buffer to act as an intermediary between the raw audio stream and Unity.</param> /// <param name="audioStream"></param> /// <returns>Returns the number of samples that were read from the stream.</returns> public static int FillUnityStreamBuffer(float[] unityBuffer, PCMAudioBuffer intermediateBuffer, MP3StreamReader audioStream) { if (audioStream.isDoneStreaming) { // Fill the Unity sample buffer with zeros. Array.Clear(unityBuffer, 0, unityBuffer.Length); return(0); } int totalSampleFramesToRead = unityBuffer.Length / audioStream.channelCount; int sampleFramesRead = 0; while (sampleFramesRead < totalSampleFramesToRead) { // Read some sample frames. int sampleFramesLeftToRead = totalSampleFramesToRead - sampleFramesRead; int sampleFramesReturned = audioStream.ReadSampleFrames(intermediateBuffer.data, 0, Math.Min(sampleFramesLeftToRead, intermediateBuffer.sampleFrameCount)); if (sampleFramesReturned > 0) { // Convert the read samples to floats copy them to the output buffer. intermediateBuffer.ToFloatArray(unityBuffer, sampleFramesRead, sampleFramesReturned); sampleFramesRead += sampleFramesReturned; } else { // Fill the rest of the Unity sample buffer with zeros. int samplesRead = sampleFramesRead * audioStream.channelCount; Array.Clear(unityBuffer, samplesRead, unityBuffer.Length - samplesRead); break; } } return(sampleFramesRead * audioStream.channelCount); }
// TODO: Handle exceptions public static PCMAudioBuffer ReadMP3(string filePath) { using (MP3StreamReader audioStream = new MP3StreamReader(filePath)) { var audioData = new List <byte>(2 * (int)audioStream.compressedStreamLengthInBytes); // Allocate enough space for a 50% compression ratio. int streamBufferSizeInSampleFrames = 16384; var streamBuffer = new byte[SampleFramesToBytes(streamBufferSizeInSampleFrames, audioStream.channelCount, audioStream.bitDepth)]; do { int sampleFramesRead = audioStream.ReadSampleFrames(streamBuffer, 0, streamBufferSizeInSampleFrames); if (sampleFramesRead > 0) { int bytesRead = SampleFramesToBytes(sampleFramesRead, audioStream.channelCount, audioStream.bitDepth); audioData.AddRange(new ArrayRange <byte>(streamBuffer, 0, bytesRead)); } } while (!audioStream.isDoneStreaming); return(new PCMAudioBuffer(audioStream.channelCount, audioStream.bitDepth, audioStream.samplingRate, audioData.ToArray())); } }