android通过tcp socket播放wave流

时间:2011-11-23 11:36:57

标签: android sockets live wave

我不知道如何通过套接字播放直播音频流。现在我有了套接字音频流。流格式:

wav format header +pcm data
wav format header +pcm data 
wav format header +pcm data

那么我如何解析现场音频流以在android中的AudioTrack类中播放。谢谢。 这是我的代码:

private void PlayAudio(int mode)
{

   if(AudioTrack.MODE_STATIC != mode && AudioTrack.MODE_STREAM != mode)
        throw new InvalidParameterException();
    long bytesWritten = 0;
    int bytesRead = 0;
    int bufferSize = 0;
    byte[] buffer;
    AudioTrack track;

    Socket socket=null;
    DataInputStream dIn=null;


      bufferSize = 55584; // i donnt know how much the buffer size should be. 55584 is the size that i got first from the socket stream.  maybe the buffer size is setted wrong.


    //sample rate 16khz,channel: mono sample bits:16 bits channel:1
            bufferSize = AudioTrack.getMinBufferSize(16000,
        AudioFormat.CHANNEL_CONFIGURATION_MONO,
        AudioFormat.ENCODING_PCM_16BIT);

    buffer = new byte[bufferSize];

    track = new AudioTrack(AudioManager.STREAM_MUSIC, 16000, 
        AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, 
        bufferSize, mode);
    // in stream mode, 
    //   1. start track playback
    //   2. write data to track

    if(AudioTrack.MODE_STREAM == mode)
        track.play(); 

    try
    {
        socket = new Socket("192.168.11.123", 8081);
        dIn = new DataInputStream(socket.getInputStream());
    //          dIn.skipBytes(44);

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }


    try
    {
        do
        {
            long t0 = SystemClock.elapsedRealtime();
            try
            {
                bytesRead = dIn.read(buffer, 0, buffer.length);

            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (NullPointerException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            bytesWritten += track.write(buffer, 0, bytesRead);

            Log.e("debug", "WritesBytes "+bytesRead);

        } while (dIn.read() != -1);

    }


    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    }

当我运行一个活动时,我得到了静音,但我可以在调试模式下间歇性地听到一些音乐,但它很吵。请你帮助我好吗 ? 服务器发送流100ms间隔: 音频格式://采样率16khz,通道:单声道采样位:16位通道:1

0 个答案:

没有答案