android wav錄音,停止和播放
這幾天一直在做錄音方面的應用,下面一個wav的錄音,停止和播放。
public class AudioFileFunc {
//音訊輸入-麥克風public final static int AUDIO_INPUT = MediaRecorder.AudioSource.MIC;
//採用頻率
//44100是目前的標準,但是某些裝置仍然支援22050,16000,11025
public final static int AUDIO_SAMPLE_RATE = 44100; //44.1KHz,普遍使用的頻率
//錄音輸出檔案
private final static String AUDIO_RAW_FILENAME = "RawAudio.raw";
private final static String AUDIO_WAV_FILENAME = "FinalAudio.wav";
public final static String AUDIO_AMR_FILENAME = "FinalAudio.amr";
/**
* 判斷是否有外部儲存裝置sdcard
* @return true | false
*/
public static boolean isSdcardExit(){
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
return true;
else
return false;
}
/**
* 獲取麥克風輸入的原始音訊流檔案路徑
* @return
*/
public static String getRawFilePath(){
String mAudioRawPath = "";
if(isSdcardExit()){
String fileBasePath = Environment.getExternalStorageDirectory().getAbsolutePath();
mAudioRawPath = fileBasePath+"/"+AUDIO_RAW_FILENAME;
}
return mAudioRawPath;
}
/**
* 獲取編碼後的WAV格式音訊檔案路徑
* @return
*/
public static String getWavFilePath(){
String mAudioWavPath = "";
if(isSdcardExit()){
//String fileBasePath = Environment.getExternalStorageDirectory().getAbsolutePath();
mAudioWavPath = Environment.getExternalStorageDirectory()+"/"+AUDIO_WAV_FILENAME;
}
return mAudioWavPath;
}
/**
* 獲取檔案大小
* @param path,檔案的絕對路徑
* @return
*/
public static long getFileSize(String path){
File mFile = new File(path);
if(!mFile.exists())
return -1;
return mFile.length();
}
}
public class AudioRecordFunc {
// 緩衝區位元組大小
private int bufferSizeInBytes = 0;
//AudioName裸音訊資料檔案 ,麥克風
private String AudioName = "";
//NewAudioName可播放的音訊檔案
private String NewAudioName = "";
private AudioRecord audioRecord;
private boolean isRecord = false;// 設定正在錄製的狀態
private static AudioRecordFunc mInstance;
private AudioRecordFunc(){
}
public synchronized static AudioRecordFunc getInstance()
{
if(mInstance == null)
mInstance = new AudioRecordFunc();
return mInstance;
}
public int startRecordAndFile() {
//判斷是否有外部儲存裝置sdcard
if(AudioFileFunc.isSdcardExit())
{
if(isRecord)
{
return ErrorCode.E_STATE_RECODING;
}
else
{
if(audioRecord == null)
creatAudioRecord();
audioRecord.startRecording();
// 讓錄製狀態為true
isRecord = true;
// 開啟音訊檔案寫入執行緒
new Thread(new AudioRecordThread()).start();
return ErrorCode.SUCCESS;
}
}
else
{
return ErrorCode.E_NOSDCARD;
}
}
public void stopRecordAndFile() {
close();
}
public long getRecordFileSize(){
return AudioFileFunc.getFileSize(NewAudioName);
}
private void close() {
if (audioRecord != null) {
System.out.println("stopRecord");
isRecord = false;//停止檔案寫入
audioRecord.stop();
audioRecord.release();//釋放資源
audioRecord = null;
}
}
private void creatAudioRecord() {
// 獲取音訊檔案路徑
AudioName = AudioFileFunc.getRawFilePath();
NewAudioName = AudioFileFunc.getWavFilePath();
// 獲得緩衝區位元組大小
bufferSizeInBytes = AudioRecord.getMinBufferSize(AudioFileFunc.AUDIO_SAMPLE_RATE,
AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT);
// 建立AudioRecord物件
audioRecord = new AudioRecord(AudioFileFunc.AUDIO_INPUT, AudioFileFunc.AUDIO_SAMPLE_RATE,
AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT, bufferSizeInBytes);
}
class AudioRecordThread implements Runnable {
@Override
public void run() {
writeDateTOFile();//往檔案中寫入裸資料
copyWaveFile(AudioName, NewAudioName);//給裸資料加上標頭檔案
}
}
/**
* 這裡將資料寫入檔案,但是並不能播放,因為AudioRecord獲得的音訊是原始的裸音訊,
* 如果需要播放就必須加入一些格式或者編碼的頭資訊。但是這樣的好處就是你可以對音訊的 裸資料進行處理,比如你要做一個愛說話的TOM
* 貓在這裡就進行音訊的處理,然後重新封裝 所以說這樣得到的音訊比較容易做一些音訊的處理。
*/
private void writeDateTOFile() {
// new一個byte陣列用來存一些位元組資料,大小為緩衝區大小
byte[] audiodata = new byte[bufferSizeInBytes];
FileOutputStream fos = null;
int readsize = 0;
try {
File file = new File(AudioName);
if (file.exists()) {
file.delete();
}
fos = new FileOutputStream(file);// 建立一個可存取位元組的檔案
} catch (Exception e) {
e.printStackTrace();
}
while (isRecord == true) {
readsize = audioRecord.read(audiodata, 0, bufferSizeInBytes);
if (AudioRecord.ERROR_INVALID_OPERATION != readsize && fos!=null) {
try {
fos.write(audiodata);
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
if(fos != null)
fos.close();// 關閉寫入流
} catch (IOException e) {
e.printStackTrace();
}
}
// 這裡得到可播放的音訊檔案
private void copyWaveFile(String inFilename, String outFilename) {
FileInputStream in = null;
FileOutputStream out = null;
long totalAudioLen = 0;
long totalDataLen = totalAudioLen + 36;
long longSampleRate = AudioFileFunc.AUDIO_SAMPLE_RATE;
int channels = 2;
long byteRate = 16 * AudioFileFunc.AUDIO_SAMPLE_RATE * channels / 8;
byte[] data = new byte[bufferSizeInBytes];
try {
in = new FileInputStream(inFilename);
out = new FileOutputStream(outFilename);
totalAudioLen = in.getChannel().size();
totalDataLen = totalAudioLen + 36;
WriteWaveFileHeader(out, totalAudioLen, totalDataLen,
longSampleRate, channels, byteRate);
while (in.read(data) != -1) {
out.write(data);
}
in.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 這裡提供一個頭資訊。插入這些資訊就可以得到可以播放的檔案。
* 為我為啥插入這44個位元組,這個還真沒深入研究,不過你隨便開啟一個wav
* 音訊的檔案,可以發現前面的標頭檔案可以說基本一樣哦。每種格式的檔案都有
* 自己特有的標頭檔案。
*/
private void WriteWaveFileHeader(FileOutputStream out, long totalAudioLen,
long totalDataLen, long longSampleRate, int channels, long byteRate)
throws IOException {
byte[] header = new byte[44];
header[0] = 'R'; // RIFF/WAVE header
header[1] = 'I';
header[2] = 'F';
header[3] = 'F';
header[4] = (byte) (totalDataLen & 0xff);
header[5] = (byte) ((totalDataLen >> 8) & 0xff);
header[6] = (byte) ((totalDataLen >> 16) & 0xff);
header[7] = (byte) ((totalDataLen >> 24) & 0xff);
header[8] = 'W';
header[9] = 'A';
header[10] = 'V';
header[11] = 'E';
header[12] = 'f'; // 'fmt ' chunk
header[13] = 'm';
header[14] = 't';
header[15] = ' ';
header[16] = 16; // 4 bytes: size of 'fmt ' chunk
header[17] = 0;
header[18] = 0;
header[19] = 0;
header[20] = 1; // format = 1
header[21] = 0;
header[22] = (byte) channels;
header[23] = 0;
header[24] = (byte) (longSampleRate & 0xff);
header[25] = (byte) ((longSampleRate >> 8) & 0xff);
header[26] = (byte) ((longSampleRate >> 16) & 0xff);
header[27] = (byte) ((longSampleRate >> 24) & 0xff);
header[28] = (byte) (byteRate & 0xff);
header[29] = (byte) ((byteRate >> 8) & 0xff);
header[30] = (byte) ((byteRate >> 16) & 0xff);
header[31] = (byte) ((byteRate >> 24) & 0xff);
header[32] = (byte) (2 * 16 / 8); // block align
header[33] = 0;
header[34] = 16; // bits per sample
header[35] = 0;
header[36] = 'd';
header[37] = 'a';
header[38] = 't';
header[39] = 'a';
header[40] = (byte) (totalAudioLen & 0xff);
header[41] = (byte) ((totalAudioLen >> 8) & 0xff);
header[42] = (byte) ((totalAudioLen >> 16) & 0xff);
header[43] = (byte) ((totalAudioLen >> 24) & 0xff);
out.write(header, 0, 44);
}
}
public class ErrorCode {
public final static int SUCCESS = 1000;
public final static int E_NOSDCARD = 1001;
public final static int E_STATE_RECODING = 1002;
public final static int E_UNKOWN = 1003;
public static String getErrorInfo(Context vContext, int vType) throws NotFoundException
{
switch(vType)
{
case SUCCESS:
return "success";
case E_NOSDCARD:
return "沒有SD卡,無法儲存錄音資料";
case E_STATE_RECODING:
return "正在錄音中,請先停止錄音";
case E_UNKOWN:
default:
return "無法識別的錯誤";
}
}
}
public class SecondActivity extends Activity {
private final static int FLAG_WAV = 0;
private int mState = -1; //-1:沒再錄製,0:錄製wav
private Button btn_record_wav;
private Button btn_stop;
private Button btn_play;
private TextView txt;
private UIHandler uiHandler;
private UIThread uiThread;
MediaPlayer mMediaPlayer;//播放聲音
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.record);
setPlayer();
findViewByIds();
setListeners();
init();
}
//mediaPlayer的create必須在oncreate裡
private void setPlayer(){
Uri playUri = Uri.parse(AudioFileFunc.getWavFilePath());//獲取wav檔案路徑
mMediaPlayer = MediaPlayer.create(this, playUri);
}
private void findViewByIds(){
btn_record_wav = (Button)this.findViewById(R.id.start);
btn_stop = (Button)this.findViewById(R.id.stop);
txt = (TextView)this.findViewById(R.id.textView1);
btn_play=(Button) this.findViewById(R.id.play);
}
private void setListeners(){
btn_record_wav.setOnClickListener(btn_record_wav_clickListener);
btn_stop.setOnClickListener(btn_stop_clickListener);
btn_play.setOnClickListener(btn_play_clickListener);
}
private void init(){
uiHandler = new UIHandler();
}
private Button.OnClickListener btn_record_wav_clickListener = new Button.OnClickListener(){
@Override
public void onClick(View v){
record(FLAG_WAV);
}
};
private Button.OnClickListener btn_stop_clickListener = new Button.OnClickListener(){
@Override
public void onClick(View v){
stop();
}
};
private Button.OnClickListener btn_play_clickListener = new Button.OnClickListener(){
@Override
public void onClick(View v){
play();
}
};
/**
* 開始錄音
* @param mFlag,0:錄製wav格式,1:錄音amr格式
*/
private void record(int mFlag){
if(mState != -1){
Message msg = new Message();
Bundle b = new Bundle();// 存放資料
b.putInt("cmd",CMD_RECORDFAIL);
b.putInt("msg", ErrorCode.E_STATE_RECODING);
msg.setData(b);
uiHandler.sendMessage(msg); // 向Handler傳送訊息,更新UI
return;
}
int mResult = -1;
AudioRecordFunc mRecord_1 = AudioRecordFunc.getInstance();
mResult = mRecord_1.startRecordAndFile();
if(mResult == ErrorCode.SUCCESS){
uiThread = new UIThread();
new Thread(uiThread).start();
mState = mFlag;
}else{
Message msg = new Message();
Bundle b = new Bundle();// 存放資料
b.putInt("cmd",CMD_RECORDFAIL);
b.putInt("msg", mResult);
msg.setData(b);
uiHandler.sendMessage(msg); // 向Handler傳送訊息,更新UI
}
}
/**
* 停止錄音
*/
private void stop(){
if(mState != -1){
AudioRecordFunc mRecord_1 = AudioRecordFunc.getInstance();
mRecord_1.stopRecordAndFile();
if(uiThread != null){
uiThread.stopThread();
}
if(uiHandler != null)
uiHandler.removeCallbacks(uiThread);
Message msg = new Message();
Bundle b = new Bundle();// 存放資料
b.putInt("cmd",CMD_STOP);
b.putInt("msg", mState);
msg.setData(b);
uiHandler.sendMessageDelayed(msg,1000); // 向Handler傳送訊息,更新UI
mState = -1;
}
}
/**
* 播放錄音
*/
private void play(){
if(mState != -1){
Message msg = new Message();
Bundle b = new Bundle();// 存放資料
b.putInt("cmd",CMD_PLAYFAIL);
b.putInt("msg", mState);
msg.setData(b);
uiHandler.sendMessageDelayed(msg,1000); // 向Handler傳送訊息,更新UI
mState = -1;
}else{
if(AudioFileFunc.getWavFilePath()!=""){
if(mMediaPlayer!=null)
mMediaPlayer.stop();
try {
mMediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO 自動生成的 catch 塊
e.printStackTrace();
} catch (IOException e) {
// TODO 自動生成的 catch 塊
e.printStackTrace();
}
mMediaPlayer.start();
}else{
Log.d("play", "找不到錄音檔案!!!");
}
}
}
private final static int CMD_RECORDING_TIME = 2000;
private final static int CMD_RECORDFAIL = 2001;
private final static int CMD_STOP = 2002;
private final static int CMD_PLAYFAIL = 2003;
class UIHandler extends Handler{
public UIHandler() {
}
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
Log.d("MyHandler", "handleMessage......");
super.handleMessage(msg);
Bundle b = msg.getData();
int vCmd = b.getInt("cmd");
switch(vCmd)
{
case CMD_RECORDING_TIME:
int vTime = b.getInt("msg");
SecondActivity.this.txt.setText("正在錄音中,已錄製:"+vTime+" s");
break;
case CMD_RECORDFAIL:
int vErrorCode = b.getInt("msg");
String vMsg = ErrorCode.getErrorInfo(SecondActivity.this, vErrorCode);
SecondActivity.this.txt.setText("錄音失敗:"+vMsg);
break;
case CMD_STOP:
int vFileType = b.getInt("msg");
switch(vFileType){
case FLAG_WAV:
AudioRecordFunc mRecord_1 = AudioRecordFunc.getInstance();
long mSize = mRecord_1.getRecordFileSize();
SecondActivity.this.txt.setText("錄音已停止.錄音檔案:"+AudioFileFunc.getWavFilePath()+"\n檔案大小:"+mSize);
break;
}
break;
case CMD_PLAYFAIL:
SecondActivity.this.txt.setText("請先錄完音!");
break;
default:
break;
}
}
};
class UIThread implements Runnable {
int mTimeMill = 0;
boolean vRun = true;
public void stopThread(){
vRun = false;
}
@Override
public void run() {
while(vRun){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mTimeMill ++;
Log.d("thread", "mThread........"+mTimeMill);
Message msg = new Message();
Bundle b = new Bundle();// 存放資料
b.putInt("cmd",CMD_RECORDING_TIME);
b.putInt("msg", mTimeMill);
msg.setData(b);
SecondActivity.this.uiHandler.sendMessage(msg); // 向Handler傳送訊息,更新UI
}
}
}
}