Android-Entwicklungshandbuch
/ 使用MediaRecord錄音
使用MediaRecord錄音
本節(jié)引言
本節(jié)是Android多媒體基本API調(diào)用的最后一節(jié),帶來(lái)的是MediaRecord的簡(jiǎn)單使用, 用法非常簡(jiǎn)單,我們寫個(gè)例子來(lái)熟悉熟悉~
1.使用MediaRecord錄制音頻
運(yùn)行結(jié)果:
實(shí)現(xiàn)代碼:
布局代碼:activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/btn_control" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="開始錄音" /></RelativeLayout>
MainActivity.java:
public class MainActivity extends AppCompatActivity { private Button btn_control; private boolean isStart = false; private MediaRecorder mr = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn_control = (Button) findViewById(R.id.btn_control); btn_control.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!isStart){ startRecord(); btn_control.setText("停止錄制"); isStart = true; }else{ stopRecord(); btn_control.setText("開始錄制"); isStart = false; } } }); } //開始錄制 private void startRecord(){ if(mr == null){ File dir = new File(Environment.getExternalStorageDirectory(),"sounds"); if(!dir.exists()){ dir.mkdirs(); } File soundFile = new File(dir,System.currentTimeMillis()+".amr"); if(!soundFile.exists()){ try { soundFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } mr = new MediaRecorder(); mr.setAudioSource(MediaRecorder.AudioSource.MIC); //音頻輸入源 mr.setOutputFormat(MediaRecorder.OutputFormat.AMR_WB); //設(shè)置輸出格式 mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB); //設(shè)置編碼格式 mr.setOutputFile(soundFile.getAbsolutePath()); try { mr.prepare(); mr.start(); //開始錄制 } catch (IOException e) { e.printStackTrace(); } } } //停止錄制,資源釋放 private void stopRecord(){ if(mr != null){ mr.stop(); mr.release(); mr = null; } } }
最后別忘了在AndroidManifest.xml中添加下述權(quán)限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.RECORD_AUDIO"/>
好的,就是這么簡(jiǎn)單~
2.本節(jié)示例代碼下載
本節(jié)小結(jié):
好的,本節(jié)內(nèi)容非常簡(jiǎn)單,就是MediaRecorder的使用而已,大概是整套教程中最精簡(jiǎn)的一節(jié) 了吧~嘿嘿~