編輯:Android 開發實例
上一篇的入口程式裡,我們留了這麼一段:
case R.id.btn2:
// 透過 MediaRecorder 類來實現自己的音頻錄制程序
Intent intent2 = new Intent();
intent2.setClass(this, MyAudioRecord.class);
startActivityForResult(intent2, 1);
break;
點下這個按鈕,就會跳進我們自己寫的錄音 Activity。本文就來把 MyAudioRecord 這個類補完。
錄音需要 android.permission.RECORD_AUDIO;想把檔案落到外部儲存空間,還需要 android.permission.WRITE_EXTERNAL_STORAGE。少了任何一個,程式不會告訴你哪裡錯,只會安靜地錄出一個 0 位元組的檔案。
MediaRecorder 是個講究排場的傢伙,設定必須嚴格按照下面的次序呼叫,顛倒任何一步都會收到 IllegalStateException:
setAudioSource() — 音源,最常用的是 AudioSource.MIC。setOutputFormat() — 輸出容器格式。可選值有 THREE_GPP(3gp,音訊視訊皆可)、MPEG-4(可承載音訊與視訊)、RAW_AMR(僅支援純音訊,且編碼必須是 AMR_NB)。setAudioEncoder() — 音訊編碼,此處選 AudioEncoder.AMR_NB。setOutputFile() — 輸出路徑。設定完畢,依序呼叫 prepare() 與 start(),錄音就開始了。
檔案存在 SD 卡上不難,難的是讓其他播放器與相簿掃描得到。做法是組一個 ContentValues,填入標題、加入時間與絕對路徑,再透過 ContentResolver.insert() 插進 MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,傳回來的 Uri 就是要交給呼叫方的結果。
停止錄音時務必 stop() 之後緊接著 release(),把麥克風還給系統。接著就能建立 MediaPlayer,掛上 OnCompletionListener 監聽播放結束、同步復原按鈕狀態,最後 setDataSource() 加 prepare() 完成播放前的準備。
package demo.camera;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* 使用 MediaRecorder 實作自己的錄音程式。
* 需要 RECORD_AUDIO 與 WRITE_EXTERNAL_STORAGE 權限。
*/
public class MyAudioRecord extends Activity {
private TextView stateView;
private Button btnStart, btnStop, btnPlay, btnFinish;
private MediaRecorder recorder;
private MediaPlayer player;
private File audioFile;
private Uri fileUri;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.my_audio_record);
stateView = (TextView)this.findViewById(R.id.view_state);
stateView.setText("準備開始");
btnStart = (Button)this.findViewById(R.id.btn_start);
btnStop = (Button)this.findViewById(R.id.btn_stop);
btnPlay = (Button)this.findViewById(R.id.btn_play);
btnFinish = (Button)this.findViewById(R.id.btn_finish);
btnStop.setEnabled(false);
btnPlay.setEnabled(false);
}
public void onClick(View v){
int id = v.getId();
switch(id){
case R.id.btn_start:
recorder = new MediaRecorder();
// 1. 音源:麥克風
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
// 2. 輸出格式:3gp(音訊、視訊皆可)
// MPEG_4 可承載音訊與視訊;RAW_AMR 僅支援音訊且編碼須為 AMR_NB
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
// 3. 音訊編碼
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
// 4. 輸出檔案
File fpath = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/data/files/");
fpath.mkdirs();
try {
audioFile = File.createTempFile("recording", ".3gp", fpath);
} catch (IOException e) {
e.printStackTrace();
}
recorder.setOutputFile(audioFile.getAbsolutePath());
// 5. 準備並開始
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recorder.start();
stateView.setText("正在錄制");
btnStart.setEnabled(false);
btnPlay.setEnabled(false);
btnStop.setEnabled(true);
break;
case R.id.btn_stop:
recorder.stop();
recorder.release();
// 把錄音檔登記到 MediaStore,讓系統媒體庫能掃描到
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Media.TITLE, "this is my first record-audio");
values.put(MediaStore.Audio.Media.DATE_ADDED, System.currentTimeMillis());
values.put(MediaStore.Audio.Media.DATA, audioFile.getAbsolutePath());
fileUri = this.getContentResolver().insert(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
// 順手把播放器準備好
player = new MediaPlayer();
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer arg0) {
stateView.setText("準備錄制");
btnPlay.setEnabled(true);
btnStart.setEnabled(true);
btnStop.setEnabled(false);
}
});
try {
player.setDataSource(audioFile.getAbsolutePath());
player.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
stateView.setText("準備播放");
btnPlay.setEnabled(true);
btnStart.setEnabled(true);
btnStop.setEnabled(false);
break;
case R.id.btn_play:
// 停止錄音時已經 prepare 完畢,這裡直接 start 即可
player.start();
stateView.setText("正在播放");
btnStart.setEnabled(false);
btnStop.setEnabled(false);
btnPlay.setEnabled(false);
break;
case R.id.btn_finish:
// 帶著錄音檔的 Uri 回上一頁
Intent intent = new Intent();
intent.setData(fileUri);
this.setResult(RESULT_OK, intent);
this.finish();
break;
}
}
}
把 MediaPlayer 的 prepare() 提前到「停止錄音」時做完,是按壓播放鍵時能立刻出聲的關鍵;代價是這段 I/O 落在主執行緒上,錄音檔很長時畫面會短暫卡住,正式專案裡應該改用 prepareAsync() 搭配 OnPreparedListener。此外 btnFinish 在版面配置中的初始狀態也需要一併設為不可用,避免使用者跳過錄音直接回傳空 Uri。
Android JSON 解析器:用 JSONObject 讀取天氣資料
為什麼 JSON 在 Android 中很重要 JSON 是一種輕量、易讀的資料交換格式,常用於 API 回傳。相較 XML,它結構更簡潔,解析也相對直接。Android
Android 載入 Spinner:不確定進度列的顯示與隱藏
在 Android 中,ProgressBar 可分為有明確進度的進度列,以及不確定進度的加載 Spinner。當任務耗時未知,例如等待網路回應,Spinner 很適合提
Android 自定義軟鍵盤:打造中文與數字輸入鍵盤
軟鍵盤的核心類別 Android 自定義軟鍵盤主要使用 Keyboard 與 KeyboardView。Keyboard 描述按鍵排列,KeyboardView 負責繪製
Android MediaPlayer 完整教學:播放控制、進度同步與快轉邊界處理
Android 在媒體播放這件事上提供了不少API,而最常被拿來入門的就是 MediaPlayer。它是內建媒體播放服務的 Java 層入口,音訊、視訊、串流都能處理。本