在Android中,使用MediaRecorder類來錄制音頻需要遵循以下步驟:
獲取必要的權限: 在AndroidManifest.xml文件中添加錄音權限:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
檢查并請求權限(針對Android 6.0及以上版本): 在運行時檢查并請求錄音權限。
private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
private void requestRecordAudioPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_RECORD_AUDIO_PERMISSION);
} else {
startRecording();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_RECORD_AUDIO_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startRecording();
} else {
Toast.makeText(this, "Permission denied to record audio", Toast.LENGTH_SHORT).show();
}
}
}
配置MediaRecorder:
private MediaRecorder mediaRecorder;
private String filePath;
private void startRecording() {
filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setOutputFile(filePath);
try {
mediaRecorder.prepare();
mediaRecorder.start();
Toast.makeText(this, "Recording started", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
停止錄制:
private void stopRecording() {
if (mediaRecorder != null) {
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
Toast.makeText(this, "Recording stopped", Toast.LENGTH_SHORT).show();
}
}
處理權限請求結果:
在Activity中重寫onRequestPermissionsResult
方法來處理權限請求結果。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startButton = findViewById(R.id.start_button);
Button stopButton = findViewById(R.id.stop_button);
startButton.setOnClickListener(v -> requestRecordAudioPermission());
stopButton.setOnClickListener(v -> stopRecording());
}
處理權限請求結果:
在Activity中重寫onRequestPermissionsResult
方法來處理權限請求結果。
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_RECORD_AUDIO_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startRecording();
} else {
Toast.makeText(this, "Permission denied to record audio", Toast.LENGTH_SHORT).show();
}
}
}
通過以上步驟,你可以在Android應用中使用MediaRecorder類錄制音頻。請確保在實際應用中處理所有可能的錯誤情況,并提供用戶友好的反饋。