我有一个在很多设备上都运行正常(Xoom,Xyboard等)的应用程序,但在Galaxy 10.1上却在这一行出现了故障。
mrec.setAudioSamplingRate(44100);
当我注释掉这一行的时候,一切都顺利了。(我不确定它使用了哪个默认速率)。
我猜设备不支持这个特定的采样率,但是在文档中我找不到可以查看支持采样率的方法或对象。
非常感谢您的帮助。
我有一个在很多设备上都运行正常(Xoom,Xyboard等)的应用程序,但在Galaxy 10.1上却在这一行出现了故障。
mrec.setAudioSamplingRate(44100);
是的,Android没有提供显式方法来检查它,但可以通过AudioRecord类的getMinBufferSize函数解决问题。
public void getValidSampleRates() {
for (int rate : new int[] {8000, 11025, 16000, 22050, 44100}) { // add the rates you wish to check against
int bufferSize = AudioRecord.getMinBufferSize(rate, AudioFormat.CHANNEL_CONFIGURATION_DEFAULT, AudioFormat.ENCODING_PCM_16BIT);
if (bufferSize > 0) {
// buffer size is valid, Sample rate supported
}
}
}
Android提供了AudioManager.getProperty()
函数,用于获取音频录制和播放的最小缓冲区大小和首选采样率。但是当然,AudioManager.getProperty()
在API级别<17上不可用。以下是如何使用此API的示例代码。
// To get preferred buffer size and sampling rate.
AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
String rate = audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE);
String size = audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER);
Log.d("Buffer Size and sample rate", "Size :" + size + " & Rate: " + rate);
getProperty
的调用返回空字符串。我可能漏掉了什么。 - John Crawfordboolean validSampleRate(int sample_rate) {
AudioRecord recorder = null;
try {
int bufferSize = AudioRecord.getMinBufferSize(sample_rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, sample_rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
} catch(IllegalArgumentException e) {
return false; // cannot sample at this rate
} finally {
if(recorder != null)
recorder.release(); // release resources to prevent a memory leak
}
return true; // if nothing has been returned yet, then we must be able to sample at this rate!
}
int maxValidSampleRate() {
int[] sample_rates = new int[]{44100, 16000}; // pad list with other samples rates you want to test for
for(int sample_rate : sample_rates) {
if(validSampleRate(sample_rate))
return sample_rate; // this rate is supported, so return it!
}
return -1; // no valid sample rate
}