I am playing a sound file using this code inside a broadcast receiver activity:
notification.sound = Uri.parse("android.resource://emad.app/raw/seven_chimes");
I would like to detect when this file has finished playing.
I tried a loop like this but I think this is only good for the media player because it always = false even though I made sure the sound file was still playing:
/*
* Stay here until the chime sound is finished.
*/
while (manager.isMusicActive()){
}
Can you show me what I should use instead of manager.isMusicActive()?
You can use the MediaPlayer class and add a Completion listener to be activated when the sound finishes playing
MediaPlayer mp = MediaPlayer.create(this,Uri.parse("android.resource://emad.app/raw/seven_chimes"));
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
performOnEnd();
}
});
mp.start();
Not working with broadcast receiver but this is what worked for my current project using Kotlin to track when the audio file has finished playing.
playButton.setOnClickListener {
if (isPlaying) {
pauseSound()
}else {
playSound()
}
mediaPlayer.setOnCompletionListener {
playButton.text = "Play"
isPlaying = false
}
}
isPlaying is boolean, I will explain more if someone is confused. Hope it helps someone else in the future. Happy coding!
try using service to play the music..
after it play once, then stop your service and you can add your program on the onDestroy() service method..
hope it helps :)
Related
I have yet to find an answer to this.
I have a local file (R.raw.Bob); and I am trying to use MediaPlayer to play the file.
Sometimes it plays, sometimes it does not. I have another file which plays seemingly fine every time.
My activity flow is like this: In onCreate I do the following:
MediaPlayer mBackground = MediaPlayer.create(MainAct.this, R.raw.background);
mBackground.start(); // Works as expected.
Now in a different part of the activity I have the following:
MediaPlayer mBob= MediaPlayer.create(MainActivity.this, R.raw.Bob);
mBob.start();
And nothing occurs. I have used Log.i() and the execution goes through the relevant code but the file does not start.
Why does MediaPlayer sometimes work and sometimes does not, and is there a more reliable way of playing sound files?
Try this to start:
MediaPlayer mBob = MediaPlayer.create(MainActivity.this, R.raw.Bob);
mBob.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(final MediaPlayer mp) {
mp.start();
}
});
and this to stop:
mBob.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
}
});
I am not really sure if the error is because of I have an alarm or while loop:
MediaPlayer mpChange;
MediaPlayer saved;
mpChange = MediaPlayer.create(this, R.raw.change);
saved = MediaPlayer.create(this, R.raw.saved);
When I add a user I call a function and inside I informed the user message has saved by:
saved.start();
After that I check if user has special meaning or not and again inform the user if it does not:
else
{
/*Implement Audio Change*/
while(saved.isPlaying() == true)
{
//Nothing except wait
System.out.println("looop");
}
//saved.stop();
System.out.println("finished");
mpChange.start();
}
Code is working fine and I don't get any error or conflict between the voices. However, I get an error with in my application which says:
Application is not responding. Would you like to close?
I was not sure if it is the while loop or MediaPlayer.
Last output was:
looop
looop
looop
looop
finished
Thanks in advance for any help.
saved.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mpChange.start();
}
});
try this code in else part remove while loop
I'm trying to write a function to play a short sound (in /res/raw) in my program, called at effectively random times throughout the program. So far I have this function:
public void playSound() {
MediaPlayer mp = new MediaPlayer();
mp = MediaPlayer.create(this, R.raw.ShortBeep);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setLooping(false);
mp.start();
}
It works fine for awhile, but after exactly 30 plays of the sound, it stops making sound.
According to the Docs
... failure to call release() may cause subsequent instances of MediaPlayer objects to fallback to software implementations or fail altogether.
When you are done with it call mp.release() so that it can release the resources. I don't know what the limit is and I'm sure it depends on many factors. Either way you should be calling this function on your MediaPlayer object, especially if it will be used more than once.
I've just solved the exact same problem, but I'm using Xamarin. I ended up changing from holding on to a MediaPlayer instance for the lifetime of the activity to creating an instance each time I want to play a sound. I also implemented the IOnPreparedListener and IOnCompletionListener.
Hopefully you can get the idea despite it being C# code
public class ScanBarcodeView :
MvxActivity,
MediaPlayer.IOnPreparedListener,
MediaPlayer.IOnCompletionListener
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.ScanBarcodeView);
((ScanBarcodeViewModel) ViewModel).BarcodeScanFailed += (sender, args) => PlaySound(Resource.Raw.fail);
((ScanBarcodeViewModel) ViewModel).DuplicateScan += (sender, args) => PlaySound(Resource.Raw.tryagain);
}
private void PlaySound(int resource)
{
var mp = new MediaPlayer();
mp.SetDataSource(ApplicationContext, Android.Net.Uri.Parse($"android.resource://com.company.appname/{resource}"));
mp.SetOnPreparedListener(this);
mp.SetOnCompletionListener(this);
mp.PrepareAsync();
}
public void OnPrepared(MediaPlayer mp)
{
mp.Start();
}
public void OnCompletion(MediaPlayer mp)
{
mp.Release();
}
}
So, each time I want a sound to be played I create a MediaPlayer instance, so the data source, tell it that my Activity is the listener to Prepared and Completion events and prepare it. Since I'm using PrepareAsync I don't block the UI thread. When the media player is prepared the Start method on the MediaPlayer is called, and when the sound has finished playing the MediaPlayer object is released.
Before I made these changes I would get to 30 sounds played and it would all stop working. Now I've gone way past 30, also multiple sounds can be played simultaneously.
Hope that helps.
I am trying to play two sound items, one after the other
MediaPlayer mp = null;
protected void produceErrorSound(int index) {
if (mp != null) {
mp.reset();
mp.release();
}
mp = MediaPlayer.create(this, index);
mp.start();
}
public void correctAnswerAndNext(){
produceErrorSound(R.raw.right1) ;
produceErrorSound(R.raw.right1) ;
}
but only second sound is produced.
is there any alternative approach?
I can't see any wait mechanism in your code.
You can use an onCompletionListener to receive a callback when your first MediaPlayer has finished playback. At that point you can start the second MediaPlayer.
An alternative way in Jellybean (and later versions) is to use the audio chaining functionality (i.e. setNextMediaPlayer) to automatically start another MediaPlayer as soon as the current one has finished playing. Something like this (I've omitted the calls to setDataSource etc for brevity):
mediaPlayer1.prepare();
mediaPlayer2.prepare();
mediaPlayer1.start();
mediaPlayer1.setNextMediaPlayer(mediaPlayer2);
I am creating an android application where I'm playing a music file from my phone. I am implementing this using services. So there is a problem in my service. When I start the service the music from my app starts playing. When I press Home Key and Went to YouTube application and played any video, The service is still running in the background paying the music file. How can I stop my service from playing the music file, when some other music file is started.
Thanks in advance.
Poll the list of running services on start of a new activity and, if it requires use of the speaker, pause yours and let it finish?
Before starting a new service, stop the running service.
When stopping the running service, make sure you stop the player too.
When the Activity or Service is starting, check whether the music is playing or not. If playing, stop it else return null as below:
I think u have the below lines in your onCreate Method of your Activity:
MediaPlayer mp= MediaPlayer.create(this, R.raw.<Your Music File>);
mp.setLooping(true);
Add the below lines of code in onPause, onStop methods in your Activity:
if(mp.isPlaying())
mp.stop();
else
return;
Create two method like this.
For audio play.
private void playAudioFile()
{
try
{
mp=new MediaPlayer();
mp.reset();
mp.setDataSource(audiofileName));
mp.prepare();
mp.start();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
and this for killMedia player.
private void killMediaPlayer()
{
if(mp != null)
{
try
{
mp.release();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
use this done it's work for me.
and call like this
killMediaPlayer();
playaudio();