简体   繁体   中英

Can't Encode and Decode WaveIn data with OpusDotNet

I'm trying to figure out Encoding and Decoding an NAudio input. For testing purposes, I'm doing both in the same scope, which means it doesn't go trough network or file compression etc.

Here's how I start recording with NAudio:

private static WaveIn input;
private static BufferedWaveProvider waveProvider;
private static WaveOut output;

public static void StartRecording(ComboBox inputs, ComboBox outputs) {
    input = new WaveIn {
        DeviceNumber = ((AudioDevice)inputs.SelectedItem).id,
        BufferMilliseconds = 25
    };
    input.WaveFormat = new WaveFormat(48000, 1);
    input.RecordingStopped += RecordingStopped;
    input.DataAvailable += DataAvailable;

    waveProvider = new BufferedWaveProvider(input.WaveFormat);

    output = new WaveOut {
        DeviceNumber = ((AudioDevice)outputs.SelectedItem).id,
        DesiredLatency = 100
    };
    output.Init(waveProvider);
    output.PlaybackStopped += PlaybackStopped;

    input.StartRecording();
    output.Play();
}

And inside the DataAvailable method I try and make the Encoding and Decoding work but with so far no success.

private static void DataAvailable(object sender, WaveInEventArgs e) {
    using OpusEncoder encoder = new OpusEncoder(OpusDotNet.Application.Audio, 48000, 1);
    byte[] opusBytes = encoder.Encode(e.Buffer, e.BytesRecorded, out int encodedLength);

    using OpusDecoder decoder = new OpusDecoder(48000, 1);
    byte[] output = decoder.Decode(opusBytes, encodedLength, out int decodedLength);

    waveProvider.AddSamples(output, 0, decodedLength);
}

The error I'm getting is "The frame size must be one of the following: 2.5, 5, 10, 20, 40 or 60."

If I remove the encoding and decoding part and just send e.Buffer into my WaveProvider, it works fine and the quality is good too.

I'm using the OpusDotNet Nuget package ( https://github.com/mrphil2105/OpusDotNet ) and I also tried using the Concentus package ( https://github.com/lostromb/concentus ) but no success on both.

There's something I fundamentally don't understand here but I can't figure out what.

Edit: I've figured out that I need to set my Buffer size to 20, as that's the Frame Size, or it affects it. Now it compiles, but the audio is very choppy/spiky.

I've solved my problem by putting the OpusEncoder and OpusDecoder outside of DataReceived's scope, making them global.

Which makes sense, initializing and disposing of both an Encoder and Decoder every time you received data doesn't sound that good.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM