AudioRecord play PCM audio recording

AudioRecord and MediaRecorder difference
AudioRecord byte-recording pcm data is output, compression is not performed, directly pcm file can not be saved in the player recognize the player.
Can real-time processing of audio file, variable-class live sound editing for sound recording.
MediaRecorder is based on AudioRecord, the package, easy to use, because of their compressed audio recorded, coded and can not be real-time processing of audio editing. Suitable for general audio recording.
With the MediaPlayer to play.
public AudioRecord(int audioSource, int sampleRateInHz, int channelConfig, int audioFormat,
int bufferSizeInBytes)
AudioRecord Constructor
AudioSource audio source, commonly MediaRecorder.AudioSource.MIC (microphone audio source)
SampleRateInHz sampling rate (sampling rate in Hertz .44100Hz * is the only guarantee of the rates applicable to all devices)
ChannelConfig audio channels
AudioFormat return to the audio data format
BufferSizeInBytes buffer size
Recording process:
  • AudioRecord construction objects
  • startRecording () to start collecting
  • Collected data is written in the thread pcm file
  • stop () Stops collection
    public void record(){
        mAudioRecord.startRecording();
    new Thread(new Runnable() {
        @Override
        public void run() {
                FileOutputStream fileOutputStream=new FileOutputStream(recordFile);
                byte[] buffer=new byte[mBufferSizeInBytes];
                while(isRecording){
                    int read=mAudioRecord.read(buffer,0,mBufferSizeInBytes);
                    if(AudioRecord.ERROR_INVALID_OPERATION!=read){
                        fileOutputStream.write(buffer);
                    }
                }
                fileOutputStream.close();
            }
        }).start();
    
    }
    public void stopRecord(){
        isRecording=false;
        if(mAudioRecord.getState()==AudioRecord.RECORDSTATE_RECORDING){
            mAudioRecord.stop();
         }
         mAudioRecord.release();
    }
    Use AudioTrack Play
    • Construction AudioTrack
    • play() 
    • write in the thread () writes the file stream pcm
    • release () resource recovery
    The difference with MediaPlayer
    MediaPlayer can play a variety of audio file formats, such as MP3, AAC, WAV, OGG, MIDI and so on. MediaPlayer creates a corresponding audio decoder framework layer. And AudioTrack only play that has been decoded PCM stream, if you compare the words of supported file formats is AudioTrack only supports audio file format wav, wav format audio files because most of them are PCM streams. AudioTrack not create a decoder can only play does not need to decode wav file
    Constructor
    public AudioTrack(AudioAttributes attributes, AudioFormat format, int bufferSizeInBytes,
    int mode, int sessionId)
    mAudioTrack.play();
    new Thread(new Runnable(){
        @Override
        public void run() {
            
    try {
    FileInputStream fileInputStream=new FileInputStream(filePath);
    byte[] tempBuffer=new byte[mWriteMinBufferSize];
    while (fileInputStream.available()>0){
    int readCount= fileInputStream.read(tempBuffer);
    if (readCount== AudioTrack.ERROR_INVALID_OPERATION||readCount==AudioTrack.ERROR_BAD_VALUE){
    continue;
    }
    if (readCount!=0&&readCount!=-1){
    mAudioTrack.write(tempBuffer,0,readCount);
    }
    }
    Log.e("TAG","end");
    } catch (Exception e) {
    e.printStackTrace();
    }
    
        }
    }).start();

    Example: Use AudioRecord acquisition PCM, AudioTrack play

    package com.rexkell.mediaapplication;
    
    import android.media.AudioAttributes;
    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.support.annotation.Nullable;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    
    import com.rexkell.mediaapplication.media.MediaConfig;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.concurrent.Executors;
    
    /**
    * author: rexkell
    * date: 2019/7/22
    * explain:
    */
    public class AudioRecordActivity extends AppCompatActivity {
        boolean isRecording=false;
        //音频源 MIC指的是麦克风
        private final int mAudioSource= MediaRecorder.AudioSource.MIC;
        //(MediaRecoder sampling rate is often 8000Hz AAC 44100Hz disposed generally sampling rate 44100, currently the commonly used sampling rate, the official document that the value can be compatible with all settings.) 
        Private  Final  int SampleRateInHz = 44100; // sample rate
         / / input channels 
        Private  Final  int channelInMono = AudioFormat.CHANNEL_CONFIGURATION_MONO;
         Private  Final  int channelOutMono = AudioFormat.CHANNEL_OUT_MONO;
         // specified audio quantization bit number, specifies the following constants in the various possible AudioFormaat class. Usually we choose ENCODING_PCM_16BIT and ENCODING_PCM_8BIT PCM stands for pulse code modulation, it is actually the original audio samples.
        // so you can set the resolution of each sample is 16-bit or 8-bit, 16-bit will take up more space and processing power, but also denoted the audio closer to the true 
        Private  Final  int mAudioFormat =AudioFormat.ENCODING_PCM_16BIT;
        //指定缓冲区大小
        private int mBufferSizeInBytes;
        private String filePath;
    
        private int mWriteMinBufferSize;
        private AudioAttributes mAudioAttributes;
        AudioRecord mAudioRecord;
        AudioTrack mAudioTrack;
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.ac_audio_record);
            filePath=getExternalFilesDir("Music").getPath()+"/test.pcm";
            initAudioRecord();
        }
        private void initAudioRecord(){
          mBufferSizeInBytes=AudioRecord.getMinBufferSize(SampleRateInHz,channelInMono,mAudioFormat);
          mWriteMinBufferSize=AudioTrack.getMinBufferSize(SampleRateInHz,channelInMono,mAudioFormat);
          mAudioRecord=new AudioRecord(mAudioSource,SampleRateInHz,channelInMono,mAudioFormat,mBufferSizeInBytes);
    
          AudioFormat audioFormat=new AudioFormat.Builder().setSampleRate(SampleRateInHz).setEncoding(mAudioFormat).setChannelMask(channelOutMono).build();
          mAudioAttributes=new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
          mAudioTrack=new AudioTrack(mAudioAttributes,audioFormat,mWriteMinBufferSize, AudioTrack.MODE_STREAM, AudioManager.AUDIO_SESSION_ID_GENERATE);
          File recordFile=new File(filePath);
         if (!recordFile.exists()){
             try {
                 recordFile.createNewFile();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
    
        }
        public void record(View view){
            isRecording=!isRecording;
            String text=isRecording?"结束":"录制";
            ((Button)view).setText(text);
            if (isRecording){
                final File recordFile=new File(filePath);
                if (recordFile.exists()){
                    recordFile.delete();
                    try {
                        recordFile.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                mAudioRecord.startRecording();
                Executors.newSingleThreadExecutor().execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            FileOutputStream fileOutputStream=new FileOutputStream(recordFile);
                            byte[] buffer=new byte[mBufferSizeInBytes];
                            while (isRecording){
                                int read=mAudioRecord.read(buffer,0,mBufferSizeInBytes);
                                if (AudioRecord.ERROR_INVALID_OPERATION!=read){
                                    fileOutputStream.write(buffer);
                                }
                            }
                            fileOutputStream.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }else {
                if (mAudioRecord!=null&&isRecording){
                    if (mAudioRecord.getState()==AudioRecord.RECORDSTATE_RECORDING){
                        mAudioRecord.stop();
                    }
                    mAudioRecord.release();
                    isRecording=false;
                }
    
            }
    
        }
        public void play(View view){
            mAudioTrack.play();
            Executors.newSingleThreadExecutor().execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        FileInputStream fileInputStream=new FileInputStream(filePath);
                        byte[] tempBuffer=new byte[mWriteMinBufferSize];
                        while (fileInputStream.available()>0){
                           int readCount= fileInputStream.read(tempBuffer);
                           if (readCount== AudioTrack.ERROR_INVALID_OPERATION||readCount==AudioTrack.ERROR_BAD_VALUE){
                               continue;
                           }
                           if (readCount!=0&&readCount!=-1){
                               mAudioTrack.write(tempBuffer,0,readCount);
                           }
                        }
                        Log.e("TAG","end");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    
        @Override
        protected void onDestroy() {
           if (mAudioRecord!=null){
               mAudioRecord.release();
               mAudioRecord=null;
           }
           if (mAudioTrack!=null){
               mAudioTrack.release();
               mAudioTrack=null;
           }
           super.onDestroy();
        }
    }

     

Guess you like

Origin www.cnblogs.com/changeMsBlog/p/11256453.html