我在一个活动中有一个MediaPlayer,只要用户点击一首特定歌曲就会调用该活动。一旦MediaPlayer播放,如果用户点击回来,他们可以选择另一首歌曲。
问题在于,在选择第二首歌曲时,再次创建MediaPlayer,并且一次开始播放两首歌曲。我尝试在活动开始时使用“if MediaPlayer.isplaying,MediaPlayer.stop”,但是一旦用户按下并滚动另一首歌,MediaPlayer就会停止。
代码如下所示。如果你能保持基本的答案,我会很感激,因为我对java的理解有限(我正在尝试开发!)。
包含MediaPlayer的活动:
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();
}
}
}
感谢您的帮助。