Android多媒體之音頻、視頻錄製MediaRecorder

概述:

MediaRecorder的狀態圖:
這裏寫圖片描述
Initial:初始狀態,當使用new()方法創建一個MediaRecorder對象或者調用了reset()方法時,該MediaRecorder對象處於Initial狀態。在設定視頻源或者音頻源之後將轉換爲Initialized狀態。另外,在除Released狀態外的其它狀態通過調用reset()方法都可以使MediaRecorder進入該狀態。

Initialized:已初始化狀態,可以通過在Initial狀態調用setAudioSource()或setVideoSource()方法進入該狀態。在這個狀態可以通過setOutputFormat()方法設置輸出格式,此時MediaRecorder轉換爲DataSourceConfigured狀態。另外,通過reset()方法進入Initial狀態。

DataSourceConfigured:數據源配置狀態,這期間可以設定編碼方式、輸出文件、屏幕旋轉、預覽顯示等等。可以在Initialized狀態通過setOutputFormat()方法進入該狀態。另外,可以通過reset()方法回到Initial狀態,或者通過prepare()方法到達Prepared狀態。

Prepared:就緒狀態,在DataSourceConfigured狀態通過prepare()方法進入該狀態。在這個狀態可以通過start()進入錄製狀態。另外,可以通過reset()方法回到Initialized狀態。

Recording:錄製狀態,可以在Prepared狀態通過調用start()方法進入該狀態。另外,它可以通過stop()方法或reset()方法回到Initial狀態。

Released:釋放狀態(官方文檔給出的詞叫做Idle state 空閒狀態),可以通過在Initial狀態調用release()方法來進入這個狀態,這時將會釋放所有和MediaRecorder對象綁定的資源。

Error:錯誤狀態,當錯誤發生的時候進入這個狀態,它可以通過reset()方法進入Initial狀態。

提示:與MediaPlayer相似使用MediaRecorder錄音錄像時需要嚴格遵守狀態圖說明中的函數調用先後順序,在不同的狀態調用不同的函數,否則會出現異常。

代碼:

開始錄製音頻:

mRecorder = new MediaRecorder();
                //Sets the audio source to be used for recording,設置音頻資源
                mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                //Sets the format of the output file produced during recording,設置輸出音頻的格式
                mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                //Sets the video encoder to be used for recording,設置音頻編碼格式
                mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                //Sets the path of the output file to be produced,設置音頻文件輸出路徑
                mRecorder.setOutputFile(Environment.getExternalStorageDirectory()  + "/my_recorder.3gp");
                try {
                    //Prepares the recorder to begin capturing and encoding data
                    mRecorder.prepare();
                    //Begins capturing and encoding data to the file specified with setOutputFile()
                    mRecorder.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }

停止錄製音頻

//Stops recording
                mRecorder.stop();
                //Restarts the MediaRecorder to its idle state
                mRecorder.reset();
                //Releases resources associated with this MediaRecorder object,釋放資源
                mRecorder.release();

需要在manifests中申請權限:

<uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

我們猿類工作壓力大,很需要有自己的樂趣,於是乎,我開通了音樂人賬號,以後的作品將會上傳到我的音樂人小站上。如果這篇博客幫助到您,希望您能多關注,支持,鼓勵我將創作進行下去,同時也祝你能在工作和生活樂趣兩發麪都能出彩!

網易雲音樂人,直接打開客戶端搜索音樂人 “星河河”

豆瓣音樂人地址:https://site.douban.com/chuxinghe/ 星河河

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章