我正在制作播放直播电台的应用。我在MainActivity类中创建了一个按钮,它启动了播放服务,如下所示:
Intent intent = new Intent(MainActivity.this, StreamRadio.class);
startService(intent);
以下是我的StreamRadio类中的代码。
public class StreamRadio extends Service implements MediaPlayer.OnErrorListener {
private static final String TAG = "Information progress";
public MediaPlayer mediaPlayer;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource("http:/xx.xx.xxx.xxx:xxxx/");
Log.d(TAG, "Connected to http:/xx.xx.xxx.xxx:xxxx");
mediaPlayer.prepareAsync();
Log.d(TAG, "Preparing Async");
} catch (IOException e) {
Log.e("TAG", "IOException");
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "Mediaplayer prepared");
mediaPlayer.start();
}
});
Log.d(TAG, "Nearly finished");
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "Service is destroyed");
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}
}
}
再次单击MainActivity中的按钮时,服务将停止。
该服务在点击时启动并销毁。这是logcat输出(物理设备):
02-03 09:42:05.719 9318-9318/ D/Information progress: Connected to http:/81.18.165.234:8361
02-03 09:42:05.719 9318-9318/ D/Information progress: Preparing Async
02-03 09:42:05.719 9318-9318/ D/Information progress: Nearly finished
02-03 09:42:05.729 9318-9318/ E/MediaPlayer: Error (1,-1)
在模拟器上我收到此错误:
02-03 10:08:26.054 2797-2797/ D/Information progress: Connected to http:/81.18.165.234:8361
02-03 10:08:26.055 2797-2797/ D/Information progress: Preparing Async
02-03 10:08:26.056 2797-2797/ D/Information progress: Nearly finished
02-03 10:08:26.060 2797-2808/ E/MediaPlayer: error (1, -2147483648)
02-03 10:08:26.060 2797-2797/ E/MediaPlayer: Error (1,-2147483648)
所以我想我的问题如下: 为什么prepareAsync无法正常工作,因为没有logcat消息“Mediaplayer prepared”,我该如何解决? 我在清单中给了应用程序互联网权限。关于SO的其他问题似乎与我的不一样。
提前致谢!
答案 0 :(得分:0)
我认为问题出在您的数据源中,请检查您是否正在为数据源分配“Stream URL”。例如http://live.streamtheworld.com:80/WXYZFMMOBILECMP3
或强>
请尝试以下链接,它可能有所帮助: https://github.com/tjnicolaides/Radio-Station-Stream-App-for-Android