Android麥克風錄音的實現(手動實現環信音訊傳送)
阿新 • • 發佈:2019-01-07
最近公司有一個業務,就是通過IM傳送音訊,我用的是環信的第三方,自定義傳送音訊,寫了一個錄音的demo,錄製完成之後傳送。
這個Demo測試之後感覺還不錯,分享一下。
一、新增許可權:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
二、XML檔案(三個按鈕)
三、Java程式碼<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:id="@+id/btnStart" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="錄音"/> <Button android:id="@+id/btnStop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="停止"/> <Button android:id="@+id/btnPlay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="播放"/> </LinearLayout>
註釋寫的很清楚,但是還是有幾點需要說明,我錄音完成之後將檔案儲存到臨時檔案中,你在手機中是沒辦法找到的,你可以將你的手機root之後,用RE檔案管理器開啟指定的目錄檢視,或者你也可以改變一下檔案的路徑。public class MainActivity extends Activity implements OnClickListener { private MediaPlayer mediaPlayer; private MediaRecorder mediaRecorder = new MediaRecorder(); private File audioFile; private String msg; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnStart = (Button) findViewById(R.id.btnStart); Button btnStop = (Button) findViewById(R.id.btnStop); Button btnPlay = (Button) findViewById(R.id.btnPlay); btnStart.setOnClickListener(this); btnStop.setOnClickListener(this); btnPlay.setOnClickListener(this); } @Override public void onClick(View view) { try { switch (view.getId()) { case R.id.btnStart: // 設定音訊來源(一般為麥克風) mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); // 設定音訊輸出格式(預設的輸出格式) mediaRecorder .setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); // 設定音訊編碼方式(預設的編碼方式) mediaRecorder .setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT); // 建立一個臨時的音訊輸出檔案 audioFile = File.createTempFile("record_", ".amr"); mediaRecorder.setOutputFile(audioFile.getAbsolutePath()); mediaRecorder.prepare(); mediaRecorder.start(); msg = "正在錄音..."; break; case R.id.btnStop: if (audioFile != null) { mediaRecorder.stop(); } msg = "已經停止錄音."; break; case R.id.btnPlay: if (audioFile != null) { mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(audioFile.getAbsolutePath()); mediaPlayer.prepare(); mediaPlayer.start(); mediaPlayer .setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { setTitle("錄音播放完畢."); } }); msg = "正在播放錄音..."; } break; } setTitle(msg); Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); } catch (Exception e) { setTitle(e.getMessage()); } } }