Implement 「Play」function
PersonRecordActivity.java
public class PersonRecordActivity extends Activity implements OnCompletionListener, OnErrorListener{ static final int IDLE_STATE = 0; // 播放狀態以2來表示 static final int PLAYING_STATE = 2; // 此值紀錄record的起始時間 long recordingStart =0; MediaPlayer mPlayer = null; MediaRecorder mPlayer = null; public void onClick(View ImageButton) { switch (ImageButton.getId()) { // 當user按下play按鈕 case R.id.ib_play: startPlayback(); updateUi(); break; . . . } } public void startPlayback() { try { if(mPlayer == null) { mPlayer = new MediaPlayer(); } // 欲播放檔案之完整路徑 mPlayer.setDataSource(recordingFile.getAbsolutePath()); // 監聽"檔案播放完"的事件 mPlayer.setOnCompletionListener(this); // 監聽"檔案播放中產生錯誤"的事件 mPlayer.setOnErrorListener(this); // 緩衝 mPlayer.prepare(); // 開始播放 mPlayer.start(); } catch (NullPointerException e) { mPlayer = null; return; } catch (IllegalArgumentException e) { mPlayer = null; return; } catch (IOException e) { mPlayer = null; return; } recordingStart = System.currentTimeMillis(); setState(PLAYING_STATE); } private void setState(int state) { mState = state; } public void onCompletion(MediaPlayer mp) { // 把狀態設為IDLE mState = IDLE_STATE; stop(); } public boolean onError(MediaPlayer mp, int what, int extra) { stop(); return true; } // stop()的狀況有兩種, 1. 錄音狀態的stop 2.播放狀態的stop public void stop() { stopRecording(); stopPlayback(); } public void stopRecording() { if (mRecorder == null) return; mRecorder.stop(); mRecorder.release(); mRecorder = null; setState(IDLE_STATE); } public void stopPlayback() { if (mPlayer == null) return; mPlayer.stop(); mPlayer.release(); mPlayer = null; setState(IDLE_STATE); } }
沒有留言:
張貼留言