Skip to content

Instantly share code, notes, and snippets.

@haydenjameslee
Created January 29, 2016 06:22
Show Gist options
  • Save haydenjameslee/30e176bd9964ae2e4e4c to your computer and use it in GitHub Desktop.
Save haydenjameslee/30e176bd9964ae2e4e4c to your computer and use it in GitHub Desktop.
public override bool GetAudioBytes(int streamId, int bufferSize, out byte[] bytes, out int receivedBytes)
{
//Debug.Log("Get coherent audio data. Bytes = " + bufferSize);
IntPtr audioBuffer = Marshal.AllocHGlobal(bufferSize);
// When you need more data to play for stream #streamID
//int timeout = 0; // A zero timeout means block until data is received
receivedBytes = m_View.GetAudioData(streamId, audioBuffer, bufferSize, 0);
if (receivedBytes <= 0)
{
// Negative values indicate an error; Zero is a valid return value if no data is present
Marshal.FreeHGlobal(audioBuffer);
bytes = new byte[0];
return false;
}
// Get a byte pointer from the unmanaged memory block.
byte* audioBufferBytePtr = (byte*)audioBuffer.ToPointer();
UnmanagedMemoryStream readStream = new UnmanagedMemoryStream(audioBufferBytePtr, receivedBytes, bufferSize, FileAccess.Read);
// Create a byte array to hold data from unmanaged memory.
bytes = new byte[receivedBytes];
// Read from unmanaged memory to the byte array.
readStream.Read(bytes, 0, receivedBytes);
readStream.Close();
Marshal.FreeHGlobal(audioBuffer);
// You now have your data in *managedData*
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment