Mediaplayer循环因Android错误而停止

时间:2015-04-20 16:59:36

标签: android android-mediaplayer

// Will need this in the callbacks 
final AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.sample);

// Build and start first player 
final MediaPlayer player1 = MediaPlayer.create(this, R.raw.sample);
player1.start(); 

// Ready second player 
final MediaPlayer player2 = MediaPlayer.create(this, R.raw.sample);
player1.setNextMediaPlayer(player2); 

player1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
    @Override 
    public void onCompletion(MediaPlayer mediaPlayer) {

        // When player1 completes, we reset it, and set up player2 to go back to player1 when it's done 
        mediaPlayer.reset();
        try { 
            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            mediaPlayer.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        } 

        player2.setNextMediaPlayer(player1);
    } 
}); 
player2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    @Override 
    public void onCompletion(MediaPlayer mediaPlayer) {
        // Likewise, when player2 completes, we reset it and tell it player1 to user player2 after it's finished again 
        mediaPlayer.reset();
        try { 
            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            mediaPlayer.prepare();
        } catch (Exception e) {
            e.printStackTrace();
        } 

        player1.setNextMediaPlayer(player2);
    } 
}); 

// This loop repeats itself endlessly in this fashion without gaps 

这是我发现循环音频文件没有任何间隙的唯一方法,一切正常。但在随机完成10-15个循环后,Mediaplayer每次都会显示不同的错误并停止播放音频。试过不同的音频与不同的编码类型不同的文件格式一切,但我随机得到不同的相同错误。提前谢谢。

  

E / MediaPlayer(24311):错误(1,-38)

     

E / MediaPlayer(23256):错误(1,-1007)

     

E / MediaPlayer(23546):错误(1,-2147483648)

1 个答案:

答案 0 :(得分:-1)

这很可能是垃圾收集问题,因为您正在多次重置媒体播放器。你重复声音的方式是一种非常黑客的方式。我不会真的建议这样做,虽然我听说在使用某些文件类型循环时,set循环确实会造成间隙。您是否尝试将文件格式化为ogg?