Kiran Kumar
Kiran Kumar

Reputation: 71

How to convert NAudio data to OGG Opus format?

I am using NAudio to capture data from the audio device, I need to convert the data to OGG Opus format. I am using OpusDotNet nuget package https://github.com/mrphil2105/OpusDotNet

Below is the code for getting audio data from NAudio

OpusEncoder opusEncoder = new OpusEncoder(Application.Audio, 16000, 1);

WaveInEvent waveInStream = new WaveInEvent();
waveInStream.DeviceNumber = 0;
waveInStream.WaveFormat = new WaveFormat(16000, 16, 1);
waveInStream.DataAvailable += new EventHandler<WaveInEventArgs>(OnDataAvailable);
waveInStream.StartRecording();

private void OnDataAvailable(object sender, WaveInEventArgs e)
{
    int encodedLength;
    byte[] encodedData = opusEncoder.Encode(e.Buffer,e.Buffer.Length,out encodedLength);
}

I am getting error saying invalid framesize. I looked into Converting WAV Stream to Opus using NAudio and Sending NAudio / Opus-encoded audio from device as RTP, but could not figure out the solution.

Upvotes: 2

Views: 762

Answers (1)

XTankKiller
XTankKiller

Reputation: 41

The input data for opus encoder MUST BE in PCM format. Try this:

WaveInEvent waveInStream = new WaveInEvent();
waveInStream.DeviceNumber = 0;
waveInStream.BufferMilliseconds = 60;
waveInStream.WaveFormat = new WaveFormat(16000, 16, 1);
waveInStream.DataAvailable += new EventHandler<WaveInEventArgs>(OnDataAvailable);
waveInStream.StartRecording();

private void OnDataAvailable(object sender, WaveInEventArgs e)
{
    using (var reader = new RawSourceWaveStream(new MemoryStream(e.Buffer, 0, e.BytesRecorded), new WaveFormat(16000, 16, 1)))
    using (var encoder = new OpusEncoder(OpusDotNet.Application.Audio, 16000, 1)
    {
        Bitrate = 128000, // 128 kbps
        VBR = true, // Variable bitrate
    })
    {
    var pcmStream = WaveFormatConversionStream.CreatePcmStream(reader);
    byte[] m4 = new byte[60 * 16000 / 1000 * 2];
    pcmStream.Read(m4, 0, (int)pcmStream.Length);
    byte[] encodedData = opusEncoder.Encode(m4,m4.Length,out encodedLength);
    }
}

Upvotes: 0

Related Questions