暂停后无法恢复AudioTrack

时间:2017-05-15 22:48:08

标签: java android

我目前正在以流模式使用AudioTrack来播放一些预先录制的曲目。播放和停止机制正常工作。但是,当我按下暂停并尝试恢复之后,缓冲区只读取-1,表示已达到EOF。

我尝试标记并重置输入流,就像在某些帖子中建议的那样,但它没有帮助。

public void pauseTrack() {
  currentAudioTrack.pause();
  isPaused = true;
}

public void resumeTrack() {
  isPaused = false;
}

@Override public void run() {
  try {
    while (offset < audioFile.length()) {
      if (isPaused)
        continue;
      currentAudioTrack.play();
      int numberOfBytesRead = fileInputStream.read(audioData);
      if (numberOfBytesRead != -1) {
        currentAudioTrack.write(audioData, 0, numberOfBytesRead);
        offset+=numberOfBytesRead;
      }
      else {
        return;
      }
    }
    Log.v("status", "finished reading");
  } catch (IOException io) {
    Log.v("Exception", "IOException found: " + io.getLocalizedMessage());
  } catch (IllegalStateException ie) {
    Log.v("Exception","IllegalStateException:" + ie.getLocalizedMessage());
  }
}

我做错了什么?

3 个答案:

答案 0 :(得分:1)

为了给帖子一些关闭,我最终改为AudioTrack静态模式。这种变化不是因为暂停情况,而是最终解决了。由于缓冲区写入是一次完成的,因此它不会呈现流模式的挑战。

答案 1 :(得分:0)

试试这个

public void pauseTrack()
{
  currentAudioTrack.pause();
  isPaused = true;
}

public void resumeTrack() 
{
  isPaused = false;
}

@Override public void run() 
{
  try {
        while (offset < audioFile.length()) 
        {
          if(isPaused != true)
          {
              currentAudioTrack.play();
              int numberOfBytesRead = fileInputStream.read(audioData);
              if (numberOfBytesRead != -1) {
                currentAudioTrack.write(audioData, 0, numberOfBytesRead);
                offset+=numberOfBytesRead;
              }
              else {
                return;
              }
          }

        }
    Log.v("status", "finished reading");
  } catch (IOException io) {
    Log.v("Exception", "IOException found: " + io.getLocalizedMessage());
  } catch (IllegalStateException ie) {
    Log.v("Exception","IllegalStateException:" + ie.getLocalizedMessage());
  }
}

答案 2 :(得分:0)

如下所示,我使用了skip()方法来跳过触发暂停时记录的偏移量。效果很好。


public void play() {
try {

     dis.skip(offset);  //skip "offset * bufferSize" in the **dis** data input stream 

     while (((i = dis.read(music_chunk, 0 , 0)) > -1) && !isPaused) {
           i = dis.read(music_chunk, 0, bufferSize);
           track.write(music_chunk, 0, i);   // track is the AudioTrack
           position += bufferSize;
     }
     track.stop();
}

public void pause() {   
      track.pause();
      offset      = position ;
      isPaused    = true;   
}

请在运行之前根据需要调整以上代码。

谢谢