天天看点

Android AudioRecord录制wav格式的音频

Android AudioRecord录制wav格式的音频

package com.example.chezi008.recorderdemo;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Environment;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 描述:
 * 作者:chezi008 on 2016/11/4 17:11
 * 邮箱:[email protected]
 */
public class AudioUtil {

    private static AudioUtil mInstance;
    private AudioRecord recorder;
    //录音源
    private static int audioSource = MediaRecorder.AudioSource.MIC;
    //录音的采样频率
    private static int audioRate = ;
    //录音的声道,单声道
    private static int audioChannel = AudioFormat.CHANNEL_IN_MONO;
    //量化的深度
    private static int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
    //缓存的大小
    private static int bufferSize = AudioRecord.getMinBufferSize(audioRate,audioChannel,audioFormat);
    //记录播放状态
    private boolean isRecording = false;
    //数字信号数组
    private byte [] noteArray;
    //PCM文件
    private File pcmFile;
    //WAV文件
    private File wavFile;
    //文件输出流
    private OutputStream os;
    //文件根目录
    private String basePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/yinfu/";
    //wav文件目录
    private String outFileName = basePath+"/yinfu.wav";
    //pcm文件目录
    private String inFileName = basePath+"/yinfu.pcm";

    private AudioUtil(){
        createFile();//创建文件
        recorder = new AudioRecord(audioSource,audioRate,audioChannel,audioFormat,bufferSize);
    }

    public synchronized static AudioUtil getInstance(){
        if(mInstance == null){
            mInstance = new AudioUtil();
        }
        return mInstance;
    }

    //读取录音数字数据线程
    class WriteThread implements Runnable{
        public void run(){
            writeData();
        }
    }

    //开始录音
    public void startRecord(){
        isRecording = true;
        recorder.startRecording();
    }

    //停止录音
    public void stopRecord(){
        isRecording = false;
        recorder.stop();
    }

    //将数据写入文件夹,文件的写入没有做优化
    public void writeData(){
        noteArray = new byte[bufferSize];
        //建立文件输出流
        try {
            os = new BufferedOutputStream(new FileOutputStream(pcmFile));
        }catch (IOException e){

        }
        while(isRecording == true){
            int recordSize = recorder.read(noteArray,,bufferSize);
            if(recordSize>){
                try{
                    os.write(noteArray);
                }catch(IOException e){

                }
            }
        }
        if (os != null) {
            try {
                os.close();
            }catch (IOException e){

            }
        }
    }

    // 这里得到可播放的音频文件
    public void convertWaveFile() {
        FileInputStream in = null;
        FileOutputStream out = null;
        long totalAudioLen = ;
        long totalDataLen = totalAudioLen + ;
        long longSampleRate = AudioUtil.audioRate;
        int channels = ;
        long byteRate =  *AudioUtil.audioRate * channels / ;
        byte[] data = new byte[bufferSize];
        try {
            in = new FileInputStream(inFileName);
            out = new FileOutputStream(outFileName);
            totalAudioLen = in.getChannel().size();
            //由于不包括RIFF和WAV
            totalDataLen = totalAudioLen + ;
            WriteWaveFileHeader(out, totalAudioLen, totalDataLen, longSampleRate, channels, byteRate);
            while (in.read(data) != -) {
                out.write(data);
            }
            in.close();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /* 任何一种文件在头部添加相应的头文件才能够确定的表示这种文件的格式,wave是RIFF文件结构,每一部分为一个chunk,其中有RIFF WAVE chunk, FMT Chunk,Fact chunk,Data chunk,其中Fact chunk是可以选择的, */
    private void WriteWaveFileHeader(FileOutputStream out, long totalAudioLen, long totalDataLen, long longSampleRate,
                                     int channels, long byteRate) throws IOException {
        byte[] header = new byte[];
        header[] = 'R'; // RIFF
        header[] = 'I';
        header[] = 'F';
        header[] = 'F';
        header[] = (byte) (totalDataLen & );//数据大小
        header[] = (byte) ((totalDataLen >> ) & );
        header[] = (byte) ((totalDataLen >> ) & );
        header[] = (byte) ((totalDataLen >> ) & );
        header[] = 'W';//WAVE
        header[] = 'A';
        header[] = 'V';
        header[] = 'E';
        //FMT Chunk
        header[] = 'f'; // 'fmt '
        header[] = 'm';
        header[] = 't';
        header[] = ' ';//过渡字节
        //数据大小
        header[] = ; // 4 bytes: size of 'fmt ' chunk
        header[] = ;
        header[] = ;
        header[] = ;
        //编码方式 10H为PCM编码格式
        header[] = ; // format = 1
        header[] = ;
        //通道数
        header[] = (byte) channels;
        header[] = ;
        //采样率,每个通道的播放速度
        header[] = (byte) (longSampleRate & );
        header[] = (byte) ((longSampleRate >> ) & );
        header[] = (byte) ((longSampleRate >> ) & );
        header[] = (byte) ((longSampleRate >> ) & );
        //音频数据传送速率,采样率*通道数*采样深度/8
        header[] = (byte) (byteRate & );
        header[] = (byte) ((byteRate >> ) & );
        header[] = (byte) ((byteRate >> ) & );
        header[] = (byte) ((byteRate >> ) & );
        // 确定系统一次要处理多少个这样字节的数据,确定缓冲区,通道数*采样位数
        header[] = (byte) ( *  / );
        header[] = ;
        //每个样本的数据位数
        header[] = ;
        header[] = ;
        //Data chunk
        header[] = 'd';//data
        header[] = 'a';
        header[] = 't';
        header[] = 'a';
        header[] = (byte) (totalAudioLen & );
        header[] = (byte) ((totalAudioLen >> ) & );
        header[] = (byte) ((totalAudioLen >> ) & );
        header[] = (byte) ((totalAudioLen >> ) & );
        out.write(header, , );
    }

    //创建文件夹,首先创建目录,然后创建对应的文件
    public void createFile(){
        File baseFile = new File(basePath);
        if(!baseFile.exists())
            baseFile.mkdirs();
        pcmFile = new File(basePath+"/yinfu.pcm");
        wavFile = new File(basePath+"/yinfu.wav");
        if(pcmFile.exists()){
            pcmFile.delete();
        }
        if(wavFile.exists()){
            wavFile.delete();
        }
        try{
            pcmFile.createNewFile();
            wavFile.createNewFile();
        }catch(IOException e){

        }
    }

    //记录数据
    public void recordData(){
        new Thread(new WriteThread()).start();
    }
}