我尝试了一切,没有任何作用......我尝试了很多来自stackflow的代码,但仍然没有: MediaPlayer play songs serially Android app force closes when playing next song in array list 等...
我只需要从媒体播放器自动播放下一首歌曲。 这是我现在的代码:
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.TextView;
import java.io.IOException;
public class MainActivity extends ActionBarActivity {
final String songs_url[] = {
"http://www.aap.nl/images/stories/audio/am2012-10sec-bel.mp3",
"http://www.cse.org.uk/downloads/file/42187%20CSE%20-%20Free%20loft%20&%20Cavity%20Wall%20Insulation%20-%2010%20sec.mp3",
"http://soundsleepstudio.com/soundsleep/Sounds/washing-machine-10-sec.mp3"
};
private TextView SongTitle;
private int counter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE); //fullscreen
setContentView(R.layout.activity_main);
counter = 0;
final ImageButton btnPlay = (ImageButton) findViewById(R.id.playAndPauseButton);
SongTitle = (TextView) findViewById(R.id.textViewSongTitle);
final MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
btnPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SongTitle.setText(songs_url[counter]);
if (mediaPlayer.isPlaying()) {
btnPlay.setBackgroundResource(R.drawable.playbutton);
mediaPlayer.pause();
} else {
btnPlay.setBackgroundResource(R.drawable.pausebutton);
try {
mediaPlayer.setDataSource(songs_url[0]);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
for (int i = 0; i < 10; i++) {
try {
mediaPlayer.setDataSource(songs_url[counter]);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
}
});
}
答案 0 :(得分:3)
您无法为MediaPlayer设置新的数据源。首先需要重置它然后设置数据源。例如:
mediaPlayer.reset();
mediaPlayer.setDataSource(songs_url[counter]);
mediaPlayer.prepare();
mediaPlayer.start();