2010-09-04 134 views
12

我試圖在Android中使用AudioTrack類播放PCM文件。我可以讓文件播放得很好,但我無法可靠地判斷播放何時完成。 AudioTrack.getPlayState表示播放未完成播放時已停止播放。我與AudioTrack.setNotificationMarkerPosition有同樣的問題,並且我很確定我的標記被設置爲文件的末尾(雖然我不完全確定我是正確的)。同樣,當getPlaybackHeadPosition位於文件末尾並停止遞增時,將繼續播放。誰能幫忙?如何判斷AudioTrack對象何時完成播放?

回答

14

我發現使用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 
      } 
     } 
    } 
3

這個工作對我來說:

  do{              // Montior playback to find when done 
       x = audioTrack.getPlaybackHeadPosition(); 
     }while (x< pcmFile.length()/2); 
相關問題