2014-03-06 63 views
0

我試圖用一個MediaPlayer的連續播放多首歌曲。第一首歌曲將根據需要播放,但之後,一首特定歌曲(按字母順序排列的第一首歌曲)將一遍又一遍地播放。我也跟着這樣的:Android Mediaplayer play different songs after eachother的Android的MediaPlayer將無法播放不同的歌曲

public void startPlayer(View view) { 
    game = new Game(); 
    TextView textView = (TextView) findViewById(R.id.title); 

    // start first song 
    Music firstSong = game.getNextSong(); 
    textView.setText(firstSong.getID()); 
    mediaPlayer = MediaPlayer.create(view.getContext(), firstSong.getID()); 

    // make sure rest of songs play 
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
       @Override 
       public void onCompletion(MediaPlayer mediaPlayer) { 
        goToNextSong(); 
       } 
      }); 

    // actually start! 
    mediaPlayer.start(); 
} 

public void goToNextSong() { 
    Music nextSong = game.getNextSong(); 
    TextView textView = (TextView) findViewById(R.id.title); 

    // if we still have music to play 
    if (nextSong != null) { 
     try { 
      // set the new title 
      textView.setText(nextSong.getID()); 
      mediaPlayer.stop(); 
      mediaPlayer.reset(); 

      // get the music file 
      FileDescriptor fd = getResources().openRawResourceFd(
        nextSong.getID()).getFileDescriptor(); 
      mediaPlayer.setDataSource(fd); 

      // play it! 
      mediaPlayer.prepare(); 
      mediaPlayer.start(); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
} 

即使當我設置FD到特定的歌曲,它仍然會按照字母順序播放第一首歌曲。 nextSong.getID()返回R.raw.somesong。文本視圖(設置爲歌曲ID)更改爲正確的歌曲。幫幫我?

+0

是什麼getNextSong();? –

+0

它返回一個音樂對象並增加歌曲列表計數器。 Music對象具有返回R.raw.songtitle的getID()。 – Olga

+0

@olgash你是否在你發佈的鏈接中的問題的編輯部分嘗試過代碼? –

回答

0

所以我還沒有找到一種方法來保持相同的MediaPlayer並播放不同的歌曲,所以我只是每次做出一個新的。有用!

public void startPlayer() { 
    game = new Game(); 
    goToNextSong(); 
} 

public void goToNextSong() { 
    Music nextSong = game.getNextSong(); 
    TextView textView = (TextView) findViewById(R.id.title); 

    // if we still have music to play 
    if (nextSong != null) { 
     try { 
      // set the new title 
      textView.setText(nextSong.getID()); 

      // stop old music player 
      if (mediaPlayer != null) { 
       mediaPlayer.stop(); 
      } 

      // create new music player 
      mediaPlayer = MediaPlayer.create(textView.getContext(), 
        nextSong.getID()); 

      // make sure rest of songs play 
      mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
         @Override 
         public void onCompletion(MediaPlayer mediaPlayer) { 
          goToNextSong(); 
         } 
        }); 

      // actually start! 
      mediaPlayer.start(); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } else { 
     // we're done! 
     mediaPlayer.release(); 
     mediaPlayer = null; 
    } 
} 
相關問題