使用NAudio BufferedWaveProvider发送Icecast实时音频流

时间:2019-06-05 12:35:03

标签: c# naudio live-streaming icecast lame

我想将读取的字节从NAudio BufferedWaveProvider发送到Icecast服务器。我已经做过,但是我面临音频块和静音的问题。声音没有连续发送。

我尝试了以下操作:

void init_broadcast(){

    //Connect to the icecast server
    Libshout icecast = new Libshout();
    icecast.connect();

    //Audio format
    WaveFormat format = new WaveFormat(44100, 2);

    //Audio input and buffer
    WaveIn wavein = new WaveIn(format);
    BufferedWaveProvider bwp = new BufferedWaveProvider(format);

    //Save audio to buffer
    wavein.DataAvailable += delegate(object sender, WaveInEventArgs args){
        bwp.AddSamples(args.Buffer, 0, args.BytesRecorded);
    }

    //Start recording
    wavein.StartRecording();

    //Thread to send continuously audio to icecast server
    new Thread(() => {
        while(true){
            if(!icecast.isConnected)
                break;

            var buffer = new byte[bwp.BufferLength];
            bwp.Read(buffer, 0, buffer.Length);

            byte[] mp3 = to_mp3_encoder(buffer);

            icecast.send(mp3);
        }
    }).Start();

}

这是我的to_mp3_encoder方法:

public byte[] to_mp3_encoder(byte[] buffer) {

    byte[] buffer_mp3;

    using(MemoryStream ms = new MemoryStream()) {

        LameMP3FileWriter writer = new LameMP3FileWriter(ms, new WaveFormat(44100, 2), LAMEPreset.ABR_128);

        writer.Write(buffer, 0, buffer.Length);
        writer.Flush();

        buffer_mp3 = ms.GetBuffer();

    }

    return buffer_mp3;

}

它可以正常工作,服务器可以正确连接并发送音频,但是当我在icecast客户端上播放音频时,它在音频中间有一个静音块。音频不连续。看起来它发送了一半的音频,一半了。

有人可以帮我吗?我在线程中使用缓冲区错误吗?

0 个答案:

没有答案