我在一个活动中有一个 MediaPlayer,每当用户单击特定歌曲时都会调用它。播放 MediaPlayer 后,如果用户单击返回,他们可以选择另一首歌曲。
问题是,在选择第二首歌曲时,MediaPlayer 会再次创建,并且两首歌曲同时开始播放。我尝试在活动开始时使用“if MediaPlayer.isplaying, MediaPlayer.stop”,但是一旦用户按下并滚动播放另一首歌曲,MediaPlayer 就会停止。
代码如下所示。如果您能保持基本的答案,我将不胜感激,因为我对 java 的了解有限(我正在尝试开发!)。
包含 MediaPlayer 的 Activity:
package music.tabber;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class MusicPlayer extends Activity {
private ImageButton playButton;
private TextView songTitleLabel;
private TextView songArtistLabel;
private MediaPlayer mediaPlayer = new MediaPlayer();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playing);
Bundle extras = getIntent().getExtras();
String songPath = extras.getString("songPath");
String songTitle = extras.getString("songTitle");
String songArtist = extras.getString("songArtist");
playButton = (ImageButton) findViewById(R.id.playButton);
songTitleLabel = (TextView) findViewById(R.id.songTitleLabel);
songArtistLabel = (TextView) findViewById(R.id.songArtistLabel);
playSong(songPath);
songArtistLabel.setText(songArtist);
songTitleLabel.setText(songTitle);
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if(mediaPlayer.isPlaying()){
if(mediaPlayer!=null){
mediaPlayer.pause();
playButton.setImageResource(R.drawable.ic_play);
}
}else{
if(mediaPlayer!=null){
mediaPlayer.start();
playButton.setImageResource(R.drawable.ic_pause);
}
}
}
});
}
private void playSong(String songPath) {
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(songPath);
mediaPlayer.prepare();
mediaPlayer.start();
// Changing Button Image to pause image
playButton.setImageResource(R.drawable.ic_pause);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
谢谢你的帮助。