我正在尝试使用AudioTrack播放样本数据。我没有听到设备发出的声音,但我在logcat中看到了这一点:
AudioTrack: Use of stream types is deprecated for operations other than volume control
AudioTrack: See the documentation of AudioTrack() for what to use instead with android.media.AudioAttributes to qualify your playback use case
我试过很多我在网上找到的例子,它们似乎都有同样的问题。这些例子通常都有4年以上的历史,所以问题一定与最近Android API的变化有关。
我目前正在尝试让这个代码工作:github example
它的playSound()方法如下所示:
protected void playSound(int sampleRate, byte[] soundData) {
try {
int bufferSize = AudioTrack.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
//if buffer-size changing or no previous obj then allocate:
if (bufferSize != audTrackBufferSize || audioTrack == null) {
if (audioTrack != null) {
//release previous object
audioTrack.pause();
audioTrack.flush();
audioTrack.release();
}
//allocate new object:
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
sampleRate, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, bufferSize,
AudioTrack.MODE_STREAM);
audTrackBufferSize = bufferSize;
}
float gain = (float) (volume / 100.0);
//noinspection deprecation
audioTrack.setStereoVolume(gain, gain);
audioTrack.play();
audioTrack.write(soundData, 0, soundData.length);
} catch (Exception e) {
Log.e("tone player", e.toString(), e);
}
我已经看过这里的Android开发者文档,但我不知道需要修改什么。它是抱怨使用AudioManager.STREAM_MUSIC
,AudioManager.MODE_STREAM
还是两者都有?它应该修改为什么?
Android开发人员文档中没有关于如何回放示例数据的示例。
1条答案
按热度按时间68bkxrlz1#
对AudioTrack使用新的构造函数对我很有效。你可以这样做: