I want to write a program which can pause and play every media players in android. How can i set priority of this program higher than the others? also i wrote the following code
public static final String SERVICECMD = "com.android.music.musicservicecommand";
public static final String CMDNAME = "command";
public static final String CMDPAUSE = "pause";
public static final String CMDPLAY = "play";
public static final String CMDTOGGLEPAUSE = "togglepause";
AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (mAudioManager.isMusicActive()) {
Intent i = new Intent(SERVICECMD);
i.putExtra(CMDNAME, CMDPAUSE);
MainActivity.this.sendBroadcast(i);
Toast.makeText(this, "media player is pause!", Toast.LENGTH_LONG).show();
}
if (!mAudioManager.isMusicActive()) {
Intent i = new Intent(SERVICECMD);
i.putExtra(CMDNAME, CMDPLAY);
MainActivity.this.sendBroadcast(i);
Toast.makeText(this, "media player is play!", Toast.LENGTH_LONG).show();
}
and it can pause every players but i dont know how to play them again. I can play some players but not all of them i dont know why ???
Have an onClick for a play and pause button
You'll have to find a way to retrieve all of the MediaPlayer Objects.
Pausing:
mMediaPlayer.pause(); // Pause the MediaPlayer
Playing:
mMediaPlayer.prepare(); // Prepares the MediaPlayer to play a song
** Please have an onPrepare method as well
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start(); // play!
}
Also, here's a reference for you:
https://github.com/naman14/Timber
This open source music app should have most of the relevant resources you need to creating a music player controller or etc. You'll be able to understand how it works.
Also, the code you've presented won't allow me to help you with identifying any issues unless you have not implemented the MediaPlayer Object.
Here's why: Difference between Audiomanager and MediaPlayer
-- EDIT --
Here's how you can stop other MediaPlayer instances via the MediaPlayerRegistry.
Android: How to stop other active media players?
Related
I am ringing my device in different activity and stopping it in different activity.
But the problem is device ringing is starting and stopping in same activity but not stopping in different activity..
The code is
Ringtone ringtone;
ringtone = RingtoneManager.getRingtone(mContext.getApplicationContext(),
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE));
AudioManager audioManager = (AudioManager) mContext.getApplicationContext().getSystemService(AUDIO_SERVICE);
int volume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
ringtone.setStreamType(AudioManager.STREAM_ALARM);
ringtone.stop(); //ringing is not stoping
Is there any other way to stop forcefully all ringing in my device..
If ringing is same in all of the Activities I suggest you to use Singleton class to access your RingtoneManager and AudioManager
public class Utilities {
// static variable of Ringtone
private static Ringtone mRingtone = null;
// static variable of AudioManager
private static AudioManager mAudioManager = null;
// static method to get instance of Ringtone
public static Rington getRingtone(Context mContext) {
if (mRingtone == null) {
mRingtone = RingtoneManager.getRingtone(mContext.getApplicationContext(),
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE));
}
return mRingtone;
}
// static method to get instance of AudioManager
public static AudioManager getAudioManager(Context mContext) {
if (mAudioManager == null) {
mAudioManager = mContext.getApplicationContext().getSystemService(AUDIO_SERVICE);
}
return mAudioManager;
}
}
Now in your Activity use something like this
Ringtone ringtone = Utilities.getRingtone(this)
AudioManager audioManager = Utilities.getAudioManager(this);
int volume = audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
ringtone.setStreamType(AudioManager.STREAM_ALARM);
ringtone.stop(); //this will stop ringing
I also did something similar to create a musicPlayer, as music should stop even if the user stops it from notification or somewhere else, I created a service and used Singleton instances to Play, Pause, Stop etc,.
Learn more about Singleton Classes here!
Edit 1
You code for removing Silent Mode looks fine to me, there must be something else wrong about Alarm not playing in Silent mode
This is an alternative solution for Sound in Silent Mode.
For removing silence/vibration mode I used the Alert Audio as MediaPlayer because music/media can be played even if the phone is on DND mode, I created an Emergency Alert App, which will make sound only when there is an emergency and some other Certain Action is performed.
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 20, 0);
Hope this will help!
I'm developing an application with playing audio. In several cases I change the AudioStreamType to AudioManager.STREAM_RING(is mode when music is playing both: speakers and headset). When I use Bluetooth headset, I have a small annoying delay.
So i was reading that Bluetooth has a buffer and and this is logical
, but how I can solve this? Also i tried to change buffer size or delay for mediaPlayer.
So, i create a mediaPlayer like as:
#Override
public void onInit() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setLooping(true);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
songManager = new SongsManager(context);
}
#Override
public void onPrepare() {
// prepare media player
if (mediaPlayer != null) {
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
absolutePathToPlayingSong = /*some place*/;
mediaPlayer.setDataSource(/*some place*/);
mediaPlayer.prepare();
mediaPlayer.setVolume(volumeLvl, volumeLvl);
}
AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audio.setStreamVolume(AudioManager.STREAM_MUSIC, 20, 0);
}
then i just start player:
mediaPlayer.start();
So, i already tried:
to change a prepare() to prepareAsync() - probably it was tiny help, to may be i had a sound hallucinations. Unfortunately it broke a seekTo() in one place
added onPrepared() and start playing from listener - I not sure that it help
Give me please any advance^ how to fix delay for Bluetooth headset? I checked this device in YouTube application and it work great. So problem in my application. sorry my bad English!)
I have 2 target devices android 7.0(SDK 24) and android 4.2 (SDK 16)
I have to stop external media player if my app audio starts playing. In case of youtube, it stops automatically but google's media player, doesn't stops.
I have used following code.
AudioManager audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
AudioManager.OnAudioFocusChangeListener audioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
#Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS:
if (TextToSpeechController.getMediaPlayerInstance().isPlaying()) { TextToSpeechController.getMediaPlayerInstance().stop();}
break;
}
};
audioManager.requestAudioFocus(audioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
But it is stopping my other audio's as well.
Any help would be appreciated.
Try this
AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
if(manager.isMusicActive())
{
// do something - or don't
}
I have a problem with the MediaPlayer.
I have a MediaPlayer class that starts as soon as the user launches the App, but as soon as the user taps on the "credits" button another activity starts with the credits screen, but the MediaPlayer stops playing the audio stream.
Is there a way to avoid this?
MediaPlayer setup:
player = new MediaPlayer();
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
I change page with this:
Intent intent = new Intent(this, Credits.class);
startActivity(intent);
Create a local service and put the MediaPlayer in that Service. Bind to the Service from whatever Activity needs to control the MediaPlayer.
This is not possible since the mediaActivity will be pause. You might consider using a dialog instead of an intent for the credits.
I'm making music player app with simple functionality. But when I listen music on my phone with Android 6, sometimes music stops playing until I turn on display again with power button. Then next song is playing, so it seems like it's problem with loading next song. I tried to write new app just to test it out, for this purpose I used this tutorial:
https://code.tutsplus.com/tutorials/background-audio-in-android-with-mediasessioncompat--cms-27030
To this example I added ArrayList with paths to songs. In mediaPlayer onCompletionListener I increase track counter and load new song to media player.
My code:
private void initMediaPlayer() {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setVolume(1.0f, 1.0f);
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer)
{
onTrackCompletion();
}
});
private void onTrackCompletion()
{
NextTrack();
Play();
}
private void NextTrack()
{
playlistPosition++;
if (playlistPosition == playlists.get(playlistCurrent).size){
playlistPosition = 0;
}
sendAction(ACTION_TRACK_NEXT);
if(mMediaPlayer.isPlaying()){
Pause();
}
loadSong();
Play();
}
private void loadSong()
{
String path = playlists.get(playlistCurrent).getPath(playlistPosition);
if(path == null || path == "")
{
return;
}
try
{
try
{
mMediaPlayer.setDataSource(path);
} catch( IllegalStateException e ) {
mMediaPlayer.release();
initMediaPlayer();
mMediaPlayer.setDataSource(path);
}
initMediaSessionMetadata();
} catch (IOException e) {
return;
}
try {
mMediaPlayer.prepare();
} catch (IOException e) {}
sendTrackData();
}
I don't know anymore why this doesn't work. In manifest I have WAKE_LOCK permission. I also set wake lock for Media player.
Edit:
Today I tried to move loading song into onPlayFromMediaId. I made broadcast from AutoActivity where is Media player to Main Activity and send back onPlayFromMediaId with path to song. But seems like this doesn't work either.I also find out that changing volume with buttons also wake up app.
Edit2:
I made many tests and added debug string in many places in code. And I found out that app stops at mediaplayer.prepare() until I trigger any action on phone (turn on display, volume up/down, click headset button). But I don't know how to fix this bug. I tried to use prepareAsync, but didn't help.
Unless you use foreground service, the system will kill your process and mediaplayer will stop.
below is a part from from a foreground service ( notification example).
builder.setContentTitle(aMessage) // required
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(this.getString(R.string.app_name)) // required
.setAutoCancel(false)
.setContentIntent(pendingIntent)
.setVibrate(new long[]{0L})
.setPriority(Notification.PRIORITY_HIGH);
int mId = 1489;
startForeground(mId, builder.build());
The above code is tested and working fine.