I am using a MediaPlayer instance in order to stream audio files from an Internet location. The audio player is in a separate activity. The user can select from a list of audio files and come to this activity to play the audio.
Now the user might go back to the previous activity (with the list) and select another audio file. In this case, I want to stop any other audio that is playing and start playing the new audio which was selected.
Is there any way I can know whether an audio file is playing without having to hold on to the MediaPlayer object?
Thanks.
Edit
I did find out how to know whether an audio is playing. We can do it by using an object of AudioManager and calling isAudioPlaying(). This will return a true if any audio is playing.
Now the other question, how do I stop an audio currently playing? I do not have an instance of the MediaPlayer object which was created to start the audio (coz the user has already left the activity once and has come back with a new object of the activity and thus a new instance of the MediaPlayer)
Audio focus is managed by the system. The system forces audio playback from an app to fade out when another app requests audio focus. In addition, the system also mutes audio playback when an incoming call is received. Android 8.0 (API level 26) through Android 11 (API level 30)
Adjust the Data saver settings. You can choose which apps will still run even when Data saver is on. Navigate to Settings, and then search for and select Special access. Tap Allowed to use data while Data saver is on again, and then tap the switch next to the music app you want to keep running.
We can play and control the audio files in android by the help of MediaPlayer class.
You'll need to call stop()
on the MediaPlayer
instance. To make this work in your application, you'll either need to:
stop()
within the audio playing activity (in onDestroy()
), for exampleUsing a Service
will allow your code to continue running outside of the Activity life-cycle, and is the only way to persist a MediaPlayer
object like you need to in this case.
Alternatively, you may be able to create a custom subclass of Application
and store the MediaPlayer
there, but using a Service
is considered better practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With