[英]How to get an Audio Stream from Media Recorder in android
我想在android中制作流媒體錄音機。 我不確定如何獲取音頻流以及如何設置音頻流的緩沖區大小。
下面是我的媒體記錄器類
public class MyMediaRecorder {
final MediaRecorder recorder = new MediaRecorder();
final File path;
/**
* Creates a new audio recording at the given path (relative to root of SD
* card).
*/
public MyMediaRecorder(File path) {
this.path = path;
}
/**
* Starts a new recording.
*/
public void start() throws IOException {
String state = android.os.Environment.getExternalStorageState();
if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
throw new IOException("SD Card is not mounted. It is " + state
+ ".");
}
// make sure the directory we plan to store the recording in exists
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(path.getAbsolutePath());
recorder.prepare();
recorder.start();
}
/**
* Stops a recording that has been previously started.
*/
public void stop() throws IOException {
recorder.stop();
recorder.release();
}
}
在錄制開始時,我需要獲取緩沖區大小並將其發送到服務器並行錄制音頻。 我應該使用 Media Recorder 的 Audio Record 和 Audio track instaed 嗎? 請建議我該怎么做
您應該使用AudioRecord 。 這是一個簡單的代碼,展示了如何使用AudioRecord
類。
final int sampleRate = 48000;
final int channelConfig = AudioFormat.CHANNEL_IN_MONO;
final int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
int minBufferSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);
AudioRecord microphone = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate, channelConfig, audioFormat, minBufferSize * 10);
microphone.startRecording();
//Since audioformat is 16 bit, we need to create a 16 bit (short data type) buffer
short[] buffer = new short[1024];
while(!stopped) {
int readSize = microphone.read(buffer, 0, buffer.length);
sendDataToServer(buffer, readSize);
}
microphone.stop();
microphone.release();
如果您需要實時錄音機和流媒體,您應該注意性能並盡快讀取所有數據並管理它們以發送到服務器。 Github 中有很多項目,你可以重用它們並從他們的想法中學習。 我在這里分享了其中的一些(特別是錄音機類),但您可以搜索並找到更多。
1. 錄音機
2. FullDuplexNetworkAudioCallService
3. 麥克風錄音機
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.