- Android 基礎
- Android - 首頁
- Android - 概述
- Android - 環境搭建
- Android - 架構
- Android - 應用元件
- Android - Hello World 示例
- Android - 資源
- Android - 活動 (Activities)
- Android - 服務 (Services)
- Android - 廣播接收器 (Broadcast Receivers)
- Android - 內容提供器 (Content Providers)
- Android - 碎片 (Fragments)
- Android - 意圖/過濾器 (Intents/Filters)
- Android - 使用者介面
- Android - UI 佈局
- Android - UI 控制元件
- Android - 事件處理
- Android - 風格和主題
- Android - 自定義元件
- Android 高階概念
- Android - 拖放
- Android - 通知
- 基於位置的服務
- Android - 傳送郵件
- Android - 傳送簡訊
- Android - 電話撥打
- 釋出 Android 應用
- Android 實用示例
- Android - 警報對話方塊
- Android - 動畫
- Android - 音訊錄製
- Android - AudioManager
- Android - 自動完成
- Android - 最佳實踐
- Android - 藍牙
- Android - 相機
- Android - 剪貼簿
- Android - 自定義字型
- Android - 資料備份
- Android - 開發者工具
- Android - 模擬器
- Android - Facebook 整合
- Android - 手勢
- Android - 谷歌地圖
- Android - 圖片特效
- Android - ImageSwitcher
- Android - 內部儲存
- Android - JetPlayer
- Android - JSON 解析器
- Android - Linkedin 整合
- Android - 載入動畫
- Android - 本地化
- Android - 登入介面
- Android - MediaPlayer
- Android - 多點觸控
- Android - 導航
- Android - 網路連線
- Android - NFC 指南
- Android - PHP/MySQL
- Android - 進度圓圈
- Android - 進度條
- Android - 推送通知
- Android - RenderScript
- Android - RSS 閱讀器
- Android - 螢幕錄製
- Android - SDK 管理器
- Android - 感測器
- Android - 會話管理
- Android - 共享首選項
- Android - SIP 協議
- Android - 拼寫檢查器
- Android - SQLite 資料庫
- Android - 支援庫
- Android - 測試
- Android - 文字轉語音
- Android - TextureView
- Android - Twitter 整合
- Android - UI 設計
- Android - UI 模式
- Android - UI 測試
- Android - WebView 佈局
- Android - Wi-Fi
- Android - 小工具 (Widgets)
- Android - XML 解析器
- Android 實用資源
- Android - 問答
- Android - 實用資源
- Android - 討論
Android - 音訊錄製
Android 透過內建麥克風可以錄製音訊並將其儲存或播放。有多種方法可以實現,最常見的方法是使用 MediaRecorder 類。
Android 提供 MediaRecorder 類來錄製音訊或影片。要使用 MediaRecorder 類,首先需要建立一個 MediaRecorder 類的例項。語法如下所示。
MediaRecorder myAudioRecorder = new MediaRecorder();
現在,您將設定音訊源、輸出和編碼格式以及輸出檔案。語法如下所示。
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB); myAudioRecorder.setOutputFile(outputFile);
指定音訊源、格式和輸出檔案後,我們可以呼叫 prepare 和 start 兩個基本方法來開始錄音。
myAudioRecorder.prepare(); myAudioRecorder.start();
除了這些方法外,MediaRecorder 類中還有其他方法,允許您更精細地控制音訊和影片錄製。
| 序號 | 方法和描述 |
|---|---|
| 1 | setAudioSource() 此方法指定要錄製的音訊源。 |
| 2 | setVideoSource() 此方法指定要錄製的影片源。 |
| 3 | setOutputFormat() 此方法指定要儲存音訊的音訊格式。 |
| 4 |
setAudioEncoder() 此方法指定要使用的音訊編碼器。 |
| 5 |
setOutputFile() 此方法配置要將錄製的音訊儲存到的檔案的路徑。 |
| 6 | stop() 此方法停止錄製過程。 |
| 7 | release() 當不需要錄製器例項時,應該呼叫此方法。 |
示例
此示例演示瞭如何使用 MediaRecorder 類錄製音訊,然後使用 MediaPlayer 類播放錄製的音訊。
要試用此示例,您需要在實際裝置上執行。
| 步驟 | 描述 |
|---|---|
| 1 | 您將使用 Android Studio IDE 建立一個 Android 應用程式,並將其命名為 AudioCapture,包名為 com.example.sairamkrishna.myapplication。 |
| 2 | 修改 src/MainActivity.java 檔案以新增 AudioCapture 程式碼。 |
| 3 | 修改佈局 XML 檔案 res/layout/activity_main.xml,根據需要新增任何 GUI 元件。 |
| 4 | 修改 AndroidManifest.xml 以新增必要的許可權。 |
| 5 | 執行應用程式,選擇一個正在執行的 Android 裝置,將應用程式安裝到裝置上並驗證結果。 |
以下是 **src/MainActivity.java** 的內容。
package com.example.sairamkrishna.myapplication;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import java.util.Random;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import android.support.v4.app.ActivityCompat;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
public class MainActivity extends AppCompatActivity {
Button buttonStart, buttonStop, buttonPlayLastRecordAudio,
buttonStopPlayingRecording ;
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder ;
Random random ;
String RandomAudioFileName = "ABCDEFGHIJKLMNOP";
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStart = (Button) findViewById(R.id.button);
buttonStop = (Button) findViewById(R.id.button2);
buttonPlayLastRecordAudio = (Button) findViewById(R.id.button3);
buttonStopPlayingRecording = (Button)findViewById(R.id.button4);
buttonStop.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(false);
buttonStopPlayingRecording.setEnabled(false);
random = new Random();
buttonStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
CreateRandomAudioFileName(5) + "AudioRecording.3gp";
MediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buttonStart.setEnabled(false);
buttonStop.setEnabled(true);
Toast.makeText(MainActivity.this, "Recording started",
Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
});
buttonStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mediaRecorder.stop();
buttonStop.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
buttonStart.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
Toast.makeText(MainActivity.this, "Recording Completed",
Toast.LENGTH_LONG).show();
}
});
buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) throws IllegalArgumentException,
SecurityException, IllegalStateException {
buttonStop.setEnabled(false);
buttonStart.setEnabled(false);
buttonStopPlayingRecording.setEnabled(true);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(AudioSavePathInDevice);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
Toast.makeText(MainActivity.this, "Recording Playing",
Toast.LENGTH_LONG).show();
}
});
buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
buttonStop.setEnabled(false);
buttonStart.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
if(mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
MediaRecorderReady();
}
}
});
}
public void MediaRecorderReady(){
mediaRecorder=new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
public String CreateRandomAudioFileName(int string){
StringBuilder stringBuilder = new StringBuilder( string );
int i = 0 ;
while(i < string ) {
stringBuilder.append(RandomAudioFileName.
charAt(random.nextInt(RandomAudioFileName.length())));
i++ ;
}
return stringBuilder.toString();
}
private void requestPermission() {
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length> 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
if (StoragePermission && RecordPermission) {
Toast.makeText(MainActivity.this, "Permission Granted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"Permission
Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
}
以下是 **activity_main.xml** 的內容。
在以下程式碼中,**abc** 表示 tutorialspoint 的徽標。
<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="@drawable/abc"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Record"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_marginTop="37dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_centerHorizontal="true"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play"
android:id="@+id/button3"
android:layout_alignTop="@+id/button2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP PLAYING RECORDING "
android:id="@+id/button4"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
/>
</RelativeLayout>
以下是 **strings.xml** 的內容。
<resources> <string name="app_name">My Application</string> </resources>
以下是 **AndroidManifest.xml** 的內容。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sairamkrishna.myapplication.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
讓我們嘗試執行您的應用程式。我假設您已將實際的 Android 移動裝置連線到您的計算機。要在 Android Studio 中執行應用程式,請開啟專案的活動檔案之一,然後單擊工具欄中的執行
圖示。在啟動應用程式之前,Android Studio 將顯示以下影像。
預設情況下,您將看到停止和播放按鈕處於停用狀態。只需按下“錄製”按鈕,您的應用程式將開始錄製音訊。它將顯示以下螢幕。
現在只需按下停止按鈕,它就會將錄製的音訊儲存到外部 SD 卡。單擊停止按鈕時,將出現以下螢幕。
現在只需按下播放按鈕,錄製的音訊就會在裝置上開始播放。單擊播放按鈕時,將出現以下訊息。
