将音频字节传输到MediaPlayer



有没有办法将字节直接流到 Android.Media.MediaPlayer?因此,当我收到一堆字节时,我可以将它们扔进此课程并播放并重复吗?我找不到任何用字节喂食MediaPlayer的示例,这似乎是最合理的方法。

目前,我正在玩耍将每个数据包作为一个临时文件,因此我可以播放一小部分音乐并立即将其放置,但是我还没有工作,感觉就像是一种可怕的方法。

这是我到目前为止尝试的。我会收到一小部分声音(bArray(,然后将.wav标题附加到它上,以便我可以播放它。我会用我收到的每个数据包这样做。此标头匹配我收到的数据(我使用NAudio库录制声音(:

public void PlayAudio(byte[] bArray)
{
    var player = new MediaPlayer();
    player.Prepared += (sender, args) =>
    {
        player.Start();
    };
    var header = new byte[]
    {
        0x52, 0x49, 0x46, 0x46, // b Chunk ID (RIFF)
        //0x24, 0xDC, 0x05, 0x00, // l Chunk size
        0x32, 0x4B, 0x00, 0x00,
        0x57, 0x41, 0x56, 0x45, // b Format WAVE
        0x66, 0x6d, 0x74, 0x20, // b Subchunk 1 id
        0x12, 0x00, 0x00, 0x00, // l Subchunk 1 size (size of the rest of the header) = 16
        0x03, 0x00,             // l Audio format, 1 = Linear Quantization, others = compression
        0x02, 0x00,             // l Number of channels, 1 = mono, 2 = stereo
        0x80, 0xBB, 0x00, 0x00, // l Sample rate
        0x00, 0xDC, 0x05, 0x00, // l Byte rate (SampleRate * NumChannels * BitsPerSample / 8)
        0x08, 0x00,             // l Block align (NumChannels * BitsPerSample / 8)
        0x20, 0x00,             // l Bits per sample 
        0x00, 0x00, 0x66, 0x61, // compression data
        0x63, 0x74, 0x04, 0x00, // compression data
        0x00, 0x00, 0x60, 0x09, // compression data
        0x00, 0x00,             // compression data
        0x64, 0x61, 0x74, 0x61, // b Subchunk 2 id (Contains the letters "data")
        0x00, 0x4B, 0x00, 0x00, // l Subchunk 2 Size
    };
        var file = File.CreateTempFile("example", ".wav");
        var fos = new FileOutputStream(file);
        fos.Write(header);
        fos.Write(bArray);
        fos.Close();
        player.Reset();
        var fis = new FileInputStream(file);
        player.SetDataSource(fis.FD);
        player.Prepare();
}

显然,此代码没有优化,但我什至无法使其工作,并且我花了很多时间在上面,因此希望对此问题有不同的解决方案。

据我所知,

MediaPlayer不能播放连续的流(不是为此设计的(。但是,还有更多的低级类AudioTrack,可以做到这一点。

这是我项目之一的小样本:

private int _bufferSize;
private AudioTrack _output;
// in constructor
_bufferSize = AudioTrack.GetMinBufferSize(8000, ChannelOut.Mono, Encoding.Pcm16bit);
// when starting to play audio
_output = new AudioTrack(Stream.Music, 8000, ChannelOut.Mono, Encoding.Pcm16bit, _bufferSize, AudioTrackMode.Stream);
_output.Play();
// when data arrives via UDP socket
byte[] decoded = _codec.Decode(decrypted, 0, decrypted.Length);                
// just write to AudioTrack
_output.Write(decoded, 0, decoded.Length);

当然,您需要了解所有这些参数的含义(例如Pcm16bit或采样率(才能正确实现。

最新更新