android AudioTrack:不推荐使用流类型

ppcbkaq5  于 2022-12-16  发布在  Android
关注(0)|答案(1)|浏览(179)

我正在尝试使用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_MUSICAudioManager.MODE_STREAM还是两者都有?它应该修改为什么?
Android开发人员文档中没有关于如何回放示例数据的示例。

68bkxrlz

68bkxrlz1#

对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);

相关问题