检查音乐是否在 android 媒体播放器 API 中播放
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10160089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if music playing in android media player API
提问by Zahid Habib
I'm using this code below to play an audio file in android
我正在使用下面的代码在 android 中播放音频文件
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource("fileSourceHere");
mediaPlayer.prepare();
mediaPlayer.start();
I have a button on that program. When click on that button, it'll check if music playing. If music playing, it'll stop that. How can I check if music playing? I tried the code below but it didn't work
我在那个程序上有一个按钮。单击该按钮时,它会检查是否正在播放音乐。如果音乐播放,它会停止。如何检查音乐是否正在播放?我尝试了下面的代码,但没有用
if(mediaPlayer.isPlaying() == true){
mediaPlayer.pause();
}else{
mediaPlayer.start();
}
回答by Jawad Zeb
To check if Music playing by any other app. Use
检查音乐是否由任何其他应用程序播放。用
AudioManager.isMusicActive();
And if you want to know about your app music.
如果您想了解您的应用音乐。
Add Listener to listen
添加监听器进行监听
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
you can add a boolean variable to check isPlaying;
您可以添加一个布尔变量来检查 isPlaying;
boolean isPlaying= false; //false by default
and when you start mediaPlayer
at the very moment set isPlaying=true
and you are good to go.
当你start mediaPlayer
在那个时刻准备isPlaying=true
好开始的时候。
回答by dakshbhatt21
Try this:
尝试这个:
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource("fileSourceHere");
mediaPlayer.prepare();
mediaPlayer.start();
if(mediaPlayer.isPlaying())
{
//stop or pause your media player mediaPlayer.stop(); or mediaPlayer.pause();
mediaPlayer.pause();
}
else
{
mediaPlayer.start();
}