3

我使用此代码使用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.当我尝试不同频率时,应用程序崩溃

4

1 回答 1

2

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

代替

MediaRecorder.AudioEncoder.AMR_NB

尝试

AudioFormat.ENCODING_PCM_16BIT 

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

因此,在尝试录制或播放之前,最好检查所有组合并检查其中哪些是可访问的。

在 stackOverflow 上多次提到了不错的解决方案,例如这里的 Frequency detection on Android - AudioRecord

检查public AudioRecord findAudioRecord()方法

于 2012-12-23T00:53:05.917 回答