Android 媒体播放器问题
public class PlayAudio extends BroadcastReceiver{
private Context mContext;
MediaPlayer mp;
@Override
public void onReceive(Context context, Intent intent) {
mContext = context;
mIntent = intent;
playSound("sound.mp3");
}
private void playSound(String file){
mp = MediaPlayer.create(mContext, Uri.parse("file://"+file));
if (mp.isPlaying())
{
mp.stop();
}
mp.setLooping(true);
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
}
当我检查 mp 是否正在播放时出现错误。我如何检查 MediaPlayer(mp) 是否正在播放以便我可以停止它?
public class PlayAudio extends BroadcastReceiver{
private Context mContext;
MediaPlayer mp;
@Override
public void onReceive(Context context, Intent intent) {
mContext = context;
mIntent = intent;
playSound("sound.mp3");
}
private void playSound(String file){
mp = MediaPlayer.create(mContext, Uri.parse("file://"+file));
if (mp.isPlaying())
{
mp.stop();
}
mp.setLooping(true);
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
}
I am getting an error when i check if mp is playing. How can i check if MediaPlayer(mp) is playing so that i can stop it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先上面的代码有点混乱
在上面的代码中,每次调用playsound() 时都会创建媒体播放器的新实例,您需要做的就是在playaudio 类的oncreate() 中仅实例化一次mp 并重复使用它。
另外,如果您使用 create 实例化媒体播放器,您准备的内容将在内部调用,您不应再次调用它。http://developer.android.com/reference/android/media/MediaPlayer.html#create(android.content.Context, android. net.Uri)
创建后检查 mp 是否为空,以验证媒体播放器实例是否创建成功。
First a bit of confusion in the above code
In the above code new instance of media player will get created each time you call playsound() what you need to do is instantiate mp only once in oncreate() of playaudio class and use it repeatedly.
Also if you use create to instantiate mediaplayer you prepare gets called internally you should not call it again.http://developer.android.com/reference/android/media/MediaPlayer.html#create(android.content.Context, android.net.Uri)
Check if mp is null after you do create to verify if mediaplayer instance was created successfully.