I am aware that when I want to stop other application from playing audio, I use audiofocus
: http://ift.tt/1py0w48
However, I want to stop the audio that has been started by my own application.
I have few activities, one is the main screen, then the list of songs, each with own play/pause button. That works fine, when I hit play:
- I check if I am already playing something and if so, I stop the player.
- I start the song and set
playing = songTitle
so I will know that I'm already playing something.
However, when I change the activity or even go back from application to desktop, the music still plays - that's fine. But when I go back to my application it does not know that I am already playing a song and now when I click the song, two songs are playing at the same time.
What I want to do:
To make it work I would like to stop all the music I started to play (if any) on the very start of the onCreate
for my SongsActivity
. The problem is, I cannot just craete a new MediaPlayer
and use stop()
method because it's not attached with the songs that was previously started by another instance of MediaPlayer
.
I use the WebView to display the interface:
public class SongsActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String path = getExternalFilesDir(null).toString() + "/";
final WebView webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
final MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw._first_song);
WebViewClient webViewClient= new WebViewClient(){
String playing = ""; //what we have started lately
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
if(url.contains("mp3")){
String songTitle = url.replace("file:///android_asset/mp3-", "");
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
}
if(!playing.equals(songTitle)) {
mediaPlayer.reset();
int resID = getApplicationContext().getResources().getIdentifier("_" + songTitle, "raw", getApplicationContext().getPackageName());
try {
AssetFileDescriptor afd = getApplicationContext().getResources().openRawResourceFd(resID);
if (afd != null) {
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
}
afd.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
playing = songTitle;
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
@Override
public void onCompletion(MediaPlayer mp) {
webView.reload(); //so the pause button will restart to play state
}
});
}
}
return true;
}
@Override
public void onLoadResource(WebView view, String url){}
};
webView.setWebViewClient(webViewClient);
webView.loadUrl("file:///android_asset/songs.html");
}
...
}
Aucun commentaire:
Enregistrer un commentaire