我有一种尝试创建AudioRecord
的方法。不同的手机支持不同的采样率,通道配置和音频格式。因此,该方法尝试为每个方法创建AudioRecord
并返回第一个有效的方法。
private AudioRecord getAudioRecord() {
for (int rate: sampleRates) {
for (int audioFormat: audioFormats) {
for (int channelConfig: channelConfigs) {
String description = rate + "Hz, bits: " + audioFormat
+ ", channel: " + channelConfig;
Log.d(TAG, "Trying: " + description);
int bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);
if (bufferSize == AudioRecord.ERROR
|| bufferSize == AudioRecord.ERROR_BAD_VALUE) {
Log.d(TAG, "Failed: This rate/channel config/format is not supported");
continue;
}
AudioRecord recorder = new AudioRecord(AudioSource.MIC, rate, channelConfig, audioFormat, bufferSize);
if (recorder.getState() == AudioRecord.STATE_UNINITIALIZED) {
Log.d(TAG, "Failed: Recorder is uninitialized");
continue;
}
Log.d(TAG, "Success: " + description);
return recorder;
}
}
}
Log.e(TAG, "Failed all rates. Does the device have a microphone?");
return null;
}
问题是return recorder
永远不会发生!
这是我的logcat输出:
在突出显示的行(8000/3/12)上没有错误,但也没有成功。
如果我在下面的评论中没有使用continue
,它仍然不会返回!
private AudioRecord getAudioRecord() {
for (int rate: sampleRates) {
for (int audioFormat: audioFormats) {
for (int channelConfig: channelConfigs) {
String description = rate + "Hz, bits: " + audioFormat
+ ", channel: " + channelConfig;
Log.d(TAG, "Trying (2): " + description);
int bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);
if (bufferSize != AudioRecord.ERROR && bufferSize != AudioRecord.ERROR_BAD_VALUE) {
AudioRecord recorder = new AudioRecord(AudioSource.MIC, rate, channelConfig, audioFormat, bufferSize);
if (recorder.getState() == AudioRecord.STATE_INITIALIZED) {
Log.d(TAG, "Success: " + description);
return recorder;
} else {
Log.d(TAG, "Failed: Recorder is uninitialized");
}
} else {
Log.d(TAG, "Failed: This rate/channel config/format is not supported");
}
}
}
}
Log.e(TAG, "Failed all rates. Does the device have a microphone?");
return null;
}
答案 0 :(得分:1)
return语句没有问题,你根本就没到达它,因为你的AudioRecord永远不会初始化(大多数例子没有检查它,即使它们可能应该检查)
作为简短的完整性检查,您可能需要检查您的清单文件到verify you have the proper permissions以便首先录制音频,因为对麦克风的访问权限可能是/可能不存在。
答案 1 :(得分:0)
将您的函数包装在try
/ catch
块中,您可能会发现某些事情导致异常被抛出。