[英]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.