java - 如何判断 AudioTrack 对象何时播放完毕?

标签 java android audiotrack

我正在尝试使用 AudioTrack 类在 Android 中播放 PCM 文件。我可以让文件播放得很好,但我无法可靠地判断播放何时结束。 AudioTrack.getPlayState 表示播放还没有结束就停止了。我在使用 AudioTrack.setNotificationMarkerPosition 时遇到了同样的问题,而且我很确定我的标记已设置到文件的末尾(尽管我不完全确定我做对了) .同样,当 getPlaybackHeadPosition 位于文件末尾并停止递增时,播放继续。谁能帮忙?

最佳答案

我发现使用 audioTrack.setNotificationMarkerPosition(audioLength) 和 audioTrack.setPlaybackPositionUpdateListener 对我有用。见以下代码:

    // Get the length of the audio stored in the file (16 bit so 2 bytes per short)
    // and create a short array to store the recorded audio.
    int audioLength = (int) (pcmFile.length() / 2);
    short[] audioData = new short[audioLength];
    DataInputStream dis = null;

    try {
        // Create a DataInputStream to read the audio data back from the saved file.
        InputStream is = new FileInputStream(pcmFile);
        BufferedInputStream bis = new BufferedInputStream(is);
        dis = new DataInputStream(bis);

        // Read the file into the music array.
        int i = 0;
        while (dis.available() > 0) {
            audioData[i] = dis.readShort();
            i++;
        }

        // Create a new AudioTrack using the same parameters as the AudioRecord.
        audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, RECORDER_SAMPLE_RATE, RECORDER_CHANNEL_OUT,
                                    RECORDER_AUDIO_ENCODING, audioLength, AudioTrack.MODE_STREAM);
        audioTrack.setNotificationMarkerPosition(audioLength);
        audioTrack.setPlaybackPositionUpdateListener(new OnPlaybackPositionUpdateListener() {
            @Override
            public void onPeriodicNotification(AudioTrack track) {
                // nothing to do
            }
            @Override
            public void onMarkerReached(AudioTrack track) {
                Log.d(LOG_TAG, "Audio track end of file reached...");
                messageHandler.sendMessage(messageHandler.obtainMessage(PLAYBACK_END_REACHED));
            }
        });

        // Start playback
        audioTrack.play();

        // Write the music buffer to the AudioTrack object
        audioTrack.write(audioData, 0, audioLength);

    } catch (Exception e) {
        Log.e(LOG_TAG, "Error playing audio.", e);
    } finally {
        if (dis != null) {
            try {
                dis.close();
            } catch (IOException e) {
                // don't care
            }
        }
    }

关于java - 如何判断 AudioTrack 对象何时播放完毕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3643338/

相关文章:

java - 如何通过AudioTrack播放大型PCM文件? (目前出现错误)

android - 是否可以生成小于 1 秒长的音调/音频?还是立即切断播放器?

android - 在 Android AudioTrack 中使用缓冲区

java - 如果缺少标签,如何单击元素

java - Android - 保持服务在锁屏状态下保持响应

java - CellRenderer - 使文本变粗

java - 使用ajax向服务器发送数据

android - TYPE_GAME_ROTATION_VECTOR 的替代方案

android - ViewPager PagerObserver 未注册

java - 安全标志 fstack-protector Realm library Android