android sdk实时音频记录

时间:2012-12-22 23:25:37

标签: android audiotrack android-audiorecord

我使用此代码使用AudioTrackAudioRecord

实时录制和播放录制的音频
package com.example.audiotrack;

import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {
    private int freq = 8000;
    private AudioRecord audioRecord = null;
    private Thread Rthread = null;

    private AudioManager audioManager = null;
    private AudioTrack audioTrack = null;
    byte[] buffer = new byte[freq];
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
        final int bufferSize = AudioRecord.getMinBufferSize(freq,
                AudioFormat.CHANNEL_CONFIGURATION_MONO,
                AudioFormat.ENCODING_PCM_16BIT);


        audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, freq,
                AudioFormat.CHANNEL_CONFIGURATION_MONO,
                MediaRecorder.AudioEncoder.AMR_NB, bufferSize);

        audioTrack = new AudioTrack(AudioManager.ROUTE_HEADSET, freq,
                AudioFormat.CHANNEL_CONFIGURATION_MONO,
                MediaRecorder.AudioEncoder.AMR_NB, bufferSize,
                AudioTrack.MODE_STREAM);



        audioTrack.setPlaybackRate(freq);
         final byte[] buffer = new byte[bufferSize];
        audioRecord.startRecording();
        Log.i("info", "Audio Recording started");
        audioTrack.play();
        Log.i("info", "Audio Playing started");
        Rthread = new Thread(new Runnable() {
            public void run() {
                while (true) {
                    try {
                        audioRecord.read(buffer, 0, bufferSize);                                    
                        audioTrack.write(buffer, 0, buffer.length);

                    } catch (Throwable t) {
                        Log.e("Error", "Read write failed");
                        t.printStackTrace();
                    }
                }
            }
        });
        Rthread.start();
    }

}

我的问题:

1.音频质量不好

2.当我尝试不同的频率时,应用程序崩溃

1 个答案:

答案 0 :(得分:1)

音频质量可能很差,因为您使用AMR编解码器来压缩音频数据。 AMR使用基于声学模型的压缩,因此除了人类语音之外的任何其他声音都将质量很差

而不是

MediaRecorder.AudioEncoder.AMR_NB

尝试

AudioFormat.ENCODING_PCM_16BIT 

AudioRecord是低级工具,因此您必须自己处理参数兼容性。如文档中所述,许多频率都不能保证工作。

因此,在尝试录制或播放之前,最好先查看所有组合并检查它们是否可以访问。

在stackOverflow上几次提到了很好的解决方案,例如这里 Frequency detection on Android - AudioRecord

检查public AudioRecord findAudioRecord()方法