AudioTrack:不支持使用流类型



我正在尝试使用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示例

它的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开发者文档中没有关于如何回放样本数据的例子。

使用AudioTrack的新构造函数为我工作。你可以这样做:

// first, create the required objects for new constructor
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
rate = audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build();
AudioFormat audioFormat = new AudioFormat.Builder()
.setSampleRate(Integer.parseInt(rate))
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.setChannelMask(AudioFormat.CHANNEL_OUT_STEREO)
.build();
// then, initialize with new constructor
AudioTrack audioTrack = new AudioTrack(audioAttributes,
audioFormat,
minBufferSize*2,
AudioTrack.MODE_STREAM,
0);

相关内容

最新更新