Android多媒体功能开发(11)——使用AudioRecord类录制音频

AudioRecord类优点是能录制到缓冲区,能够实现边录边播(AudioRecord + AudioTrack)以及对音频的实时处理(如QQ电话)。缺点是输出是PCM格式的原始采集数据,如果直接保存成音频文件,不能够被播放器播放,所以必须用代码实现数据编码以及压缩。

使用AudioRecord录音的基本步骤是:确定录音参数、申请缓冲区、创建AudioRecord对象、开始录制、循环读取数据到缓冲区并处理数据、停止录制、释放资源。

需要确定的录音参数包括:采样率、声道、格式。申请缓冲区时需要根据录音参数计算最小缓冲区大小。有了缓冲区以后才能创建AudioRecord对象。录制过程中,需要不停地读取采样到的音频数据,并进行处理。流程和对应的代码如下图:

下面编写一个例子,用AudioRecord采集音频数据,并以原始PCM格式存入文件。读取数据和处理数据是需要循环进行的操作,所以放入单独线程执行。例子运行在Android8.0以上。

例子界面和主要代码如下:

因为要录音,所以在配置文件里需要声明录音权限。同时,Android将文件写入应用在外部存储上的私有目录不需要再申请读写存储的权限。

<uses-permission android:name="android.permission.RECORD_AUDIO" />


同时,使用AudioRecord录音需要动态申请权限,即在实际录音时需要检查用户是否允许应用使用录音权限。如果没有允许,就弹出一个对话框询问用户。代码如下:

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
      ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
      return;
}

这里用到的AudioRecord类的主要方法有:

1)构造函数:AudioRecord(int audioSource, int sampleRateInHz, int channelConfig, int audioFormat, int bufferSizeInBytes) 

  • audioSource:音频来源,一般取麦克风MediaRecorder.AudioSource.MIC
  • sampleRateInHz:采样率
  • channelConfig:声道配置,一般取AudioFormat.CHANNEL_IN_MONO 、CHANNEL_IN_DEFAULT、CHANNEL_IN_STEREO等
  • audioFormat:音频格式,取AudioFormat.ENCODING_PCM_16BIT、AudioFormat.ENCODING_PCM_8BIT
  • bufferSizeInBytes:缓冲区字节数,不得小于getMinBufferSize计算出的最小缓冲区大小

2)static int getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat):计算最小缓冲区大小,参数同构造函数中三个参数。

3)从硬件读取音频数据保存到缓冲区有三个方法,都返回读取的数据个数

  • int read(byte[] audioData, int offsetInBytes, int sizeInBytes) 
  • int read(ByteBuffer audioBuffer, int sizeInBytes) 
  • int read(short[] audioData, int offsetInShorts, int sizeInShorts)

4)void startRecording():开始录制

5)void stop():停止录制

6)void release():释放资源

从AudioRecord读取的数据是PCM格式,可以用AudioTrack类播放。用AudioTrack类播放音频的基本流程是:创建AudioTrack对象、开始播放、循环写入数据到缓冲区、停止播放、释放资源。创建AudioTrack对象时需给出参数:采样率、声道、格式。流程和对应的代码如下图:

下面就为前面的例子加上播放音频的功能。用AudioTrack播放AudioRecord录制的PCM音频文件时需要注意:写入数据后不能马上release,因为播放是异步的,此时还刚开始播放,一旦release就不播放了。用AudioTrack还可以实现变音效果:以采样率a录制,以采样率b播放。主要代码如下:

AudioTrack类的主要方法有:

1)构造函数:AudioTrack(int streamType, int sampleRateInHz, int channelConfig, int audioFormat, int bufferSizeInBytes, int mode) 

  • streamType: 流类型,取值为AudioManager.STREAM_VOICE_CALL, AudioManager.STREAM_SYSTEM, AudioManager.STREAM_RING, AudioManager.STREAM_MUSIC, AudioManager.STREAM_ALARM
  • sampleRateInHz:采样率
  • channelConfig:声道配置,一般取AudioFormat.CHANNEL_OUT_DEFAULT、CHANNEL_OUT_STEREO等
  • audioFormat:音频格式,取AudioFormat.ENCODING_PCM_16BIT、AudioFormat.ENCODING_PCM_8BIT
  • bufferSizeInBytes:缓冲区字节数,不得小于getMinBufferSize计算出的最小缓冲区大小
  • mode:缓冲区类型,MODE_STATIC、MODE_STREAM 

2)void play() :开始播放

3)写入音频数据到硬件有两个方法,返回成功写入的数据个数

  • int write(byte[] audioData, int offsetInBytes, int sizeInBytes) 
  • int write(short[] audioData, int offsetInShorts, int sizeInShorts) 

4)void stop() :停止播放

5)void pause():暂停播放

6)void release():释放资源

例子的完整代码如下:

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.pm.PackageManager;
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.view.MotionEvent;
import android.view.View;
import android.widget.*;

import java.io.*;

public class MainActivity extends AppCompatActivity {
    File soundFile;                // 存放录音的文件
    boolean isRecording;
    int frequency = 11025;
    int inChannelConfig = AudioFormat.CHANNEL_IN_MONO;
    int outChannelConfig = AudioFormat.CHANNEL_OUT_MONO;
    int audioFormat = AudioFormat.ENCODING_PCM_16BIT;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        setContentView(ll);

        //  录制到文件:Android/data/<package-name>/files/audioRecord.pcm
        soundFile = new File(getExternalFilesDir(null), "audioRecord.pcm");

        Button btnRecord = new Button(this);
        btnRecord.setText("Record");
        ll.addView(btnRecord);
        btnRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Thread t = new Thread() {
                    public void run() {
                        try {
                            record();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                };
                t.start();
            }
        });
        Button btnStop = new Button(this);
        btnStop.setText("Stop");
        ll.addView(btnStop);
        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                isRecording = false;
            }
        });

        Button btnPlay = new Button(this);
        btnPlay.setText("Play");
        ll.addView(btnPlay);
        btnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (soundFile.exists()) {
                    try {
                        play(frequency);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        Button btnPlayFast = new Button(this);
        btnPlayFast.setText("Play Fast");
        ll.addView(btnPlayFast);
        btnPlayFast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (soundFile.exists()) {
                    try {
                        play(frequency * 4 / 3);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        Button btnPlaySlow = new Button(this);
        btnPlaySlow.setText("Play Slow");
        ll.addView(btnPlaySlow);
        btnPlaySlow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (soundFile.exists()) {
                    try {
                        play(frequency * 3 / 4);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        Button btnSpeak = new Button(this);
        btnSpeak.setText("Press to Speak");
        ll.addView(btnSpeak);
        btnSpeak.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                switch (arg1.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        Thread t = new Thread() {
                            public void run() {
                                try {
                                    record();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        };
                        t.start();
                        break;
                    case MotionEvent.ACTION_UP:
                        isRecording = false;
                        break;
                }
                return false;
            }
        });
    }

    void record() throws IOException {
        // 动态权限申请
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
            return;
        }

        if (soundFile.exists()) soundFile.delete();
        soundFile.createNewFile();

        FileOutputStream fos = new FileOutputStream(soundFile);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        DataOutputStream dos = new DataOutputStream(bos);

        int bufferSize = AudioRecord.getMinBufferSize(frequency, inChannelConfig, audioFormat);
        short[] buffer = new short[bufferSize];
        AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, frequency, inChannelConfig, audioFormat, bufferSize);

        audioRecord.startRecording();
        isRecording = true;
        while(isRecording){
            int bufferRead = audioRecord.read(buffer, 0, bufferSize);
            for(int i=0; i<bufferRead; i++){
                dos.writeShort(buffer[i]);
            }
        }
        audioRecord.stop();
        audioRecord.release();

        dos.close();
        bos.close();
        fos.close();
    }

    void play(int frq) throws IOException{
        int length = (int)soundFile.length()/2;
        if(!soundFile.exists() || length==0) {
            Toast.makeText(getBaseContext(), "音频文件不存在或为空", Toast.LENGTH_SHORT).show();
            return;
        }
        short[] data = new short[length];
        FileInputStream fis = new FileInputStream(soundFile);
        BufferedInputStream bis = new BufferedInputStream(fis);
        DataInputStream dis = new DataInputStream(bis);
        int i=0;
        while(dis.available()>0) {
            data[i] = dis.readShort();
            i++;
        }
        dis.close();
        bis.close();
        fis.close();

        AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, frq, outChannelConfig, audioFormat, length*2, AudioTrack.MODE_STREAM);
        audioTrack.play();
        audioTrack.write(data, 0, length);
        audioTrack.stop();
        //audioTrack.release();		// 不能马上release,因为write后是异步播放,此时还刚开始播放,release就不播放了
    }
}

猜你喜欢

转载自blog.csdn.net/nanoage/article/details/127485313