我目前正在尝试设计一个流媒体音乐播放器的简单应用。我有歌曲的网址,我正在设置MediaPlayer
,如下所示。第一首歌的一切都还可以,但是当我播放另一首歌时,程序在模拟时没有崩溃,但没有播放,我收到以下错误:
E/MediaPlayer: Attempt to call getDuration without a valid mediaplayer
E/MediaPlayer: error (-38, 0)
E/MediaPlayer: Error (-38,0)
PlayerService.java
public class MusicPlayerService extends Service {
private SongItem mSong;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mSong = ListSong.getListSong().get(ListSong.getSelectedItem());
registerLocalFilter();
playMedia();
return START_STICKY;
}
private void playMedia() {
if (handler == null) {
thread = new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
handler = new Handler();
handler.post(playAudioFromURL);
Looper.loop();
}
});
thread.start();
} else {
handler.post(playAudioFromURL);
}
}
private Runnable playAudioFromURL = new Runnable() {
@Override
public void run() {
if (mediaPlayer != null) {
mediaPlayer.release();
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(mSong.getSongUrl());
mediaPlayer.setOnPreparedListener(onPreparedListener);
mediaPlayer.setOnCompletionListener(onCompletionListener);
mediaPlayer.setOnSeekCompleteListener(onSeekCompleteListener);
mediaPlayer.setOnErrorListener(onErrorListener);
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
Log.w(TAG, "playAudioFromURL: " + e.toString());
} catch (IllegalArgumentException ex) {
Log.w(TAG, "playAudioFromURL: " + ex.toString());
} catch (IllegalStateException ex) {
Log.w(TAG, "playAudioFromURL: " + ex.toString());
}
}
};
private MediaPlayer.OnPreparedListener onPreparedListener = new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
ListSong.setPlaying(true);
sendLoadComplete();
updateTimer();
mp.start();
}
};
}
我在mp.start()
中写了onPrepared()
并在Media Player called in state 0, error (-38,0)使用mediaPlayer.prepareAsync();
解决方案,但它无效。
请帮助我!
答案 0 :(得分:1)
在MediaPlayer mediaPlayer.setDataSource(mSong.getSongUrl());
中的mediaPlayer.reset();
之前,它可能会解决您的问题。
答案 1 :(得分:0)
希望对大家有所帮助
mediaPlayer = new MediaPlayer();
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(songURL);
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(mp -> {
mp.start();
updateProgressBar();
});
} catch (IOException e) {
e.printStackTrace();
}