在Android手机之间流式传输UDP播放问题

时间:2015-03-31 17:37:22

标签: android multithreading audiorecord audiotrack

我正在尝试实时传输2个Android手机之间的语音。我的想法是使用AudioRecord进行录制,使用AudioTrack进行播放。数据包似乎很好,但播放听起来非常尖锐,并且有很多噪音。我该如何解决?

这是我的发件人活动 -

private static int BUFFER_SIZE = AudioRecord.getMinBufferSize(
        44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);

AudioRecord recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
   44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, BUFFER_SIZE * 10);

    new Thread(new Runnable() {
        @Override
        public void run() {
            byte[] buffer = new byte[8000]; 
            DatagramPacket packet; 
            recorder.startRecording();
            while(!stopClicked){
                try {
                    Thread.sleep(90); //Recording 90ms duration packets
                    int out = recorder.read(buffer, 0, buffer.length);
                    packet = new DatagramPacket(buffer, out, inetAddress, 4444);
                    clientSocket.send(packet);
                } catch (IOException e1) {
                    e1.printStackTrace();
                } catch (InterruptedException e1) {
                    e1.printStackTrace();}
            }
        }
    }).start();

在接收方,我使用两个线程 - 一个用于收集数据包,另一个用于使用AudioTrack播放数据包 这是我的接收器活动 -

AudioTrack myAudioTrack = new AudioTrack(AudioManager.STREAM_VOICE_CALL, 44100, AudioFormat.CHANNEL_OUT_MONO,
            AudioFormat.ENCODING_PCM_16BIT, 16000,AudioTrack.MODE_STREAM);
    myAudioTrack.play();
    playerThread = new Thread(m_packetCollector);
    playerThread.start();
    new receiveUDPTask().execute();

线程是 -

Runnable m_packetCollector = new Runnable(){
    public void run(){
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
        byte[] noiseData = null;
        while(true){
            if (!packetQueue.isEmpty()) {
                noiseData = packetQueue.remove();
                myAudioTrack.write(noiseData, 0, noiseData.length);
 }}}};


private class receiveUDPTask extends AsyncTask<Void, Void, Void>{
    byte[] buf = new byte[8000];
    DatagramPacket dp = new DatagramPacket(buf, 8000);
    @Override
    protected Void doInBackground(Void... params) {
        while(true){
            System.out.println("Listening for packets");
            try {
                serverSocket.receive(dp);
                packetQueue.add(buf);
            } catch (IOException e) {
                e.printStackTrace();
}}}}

一切似乎都很好。我不明白错误在哪里。请帮我找到它。

0 个答案:

没有答案