MediaPlayer sound not always playing, not getting granted audio focus - android

I'm having an issue with some android code to play a sound notification on certain events.
Here's the code:
int result = audioManager.requestAudioFocus(MainRunningService.afChangeListener,AudioManager.STREAM_NOTIFICATION,AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
mp = new MediaPlayer();
mp.setDataSource(context, soundToPlay);
mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mp.prepare();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
try {
Log.d(LOGTAG, "SoundService MUSIC: MUSIC IS NOW COMPLETE");
mp.release();
mp = null;
Log.d(LOGTAG, "SoundService MUSIC: MUSIC IS NOW COMPLETE - RELEASED");
} catch (Exception e) {
e.printStackTrace();
}
}
});
mp.setLooping(false);
mp.start();
}
else{
Log.w(LOGTAG, "SoundService Audiofocus was not granted");
}
What I'm finding is that sometimes it will play, whereas other times it won't play. When it doesn't play it's hitting the "SoundSerice Audiofocus was not granted" log line. I've looked at the system logs, but can't find anything that says why it's not been granted.
Once this has happened, then every request seems to fail.
Does anyone have any pointers to what I might be doing wrong?

//call the method playAssistClip() on button click or wherever you want.
private MediaPlayer mp;
private void playAssistClip() {
if (workoutReps.equalsIgnoreCase("6x6x6")) {
mp = MediaPlayer.create(ProcessWorkout.this,
R.raw.six_six_six_formated_ogg);
mp.setOnCompletionListener(new OnCompletionListener() {
//do something after the audi ends
mp.reset();
mp.release();
finish();
}
});
mp.start();
//to get the duration of clip
spentTimeOnWorkout = mp.getDuration();
}

Related

How to play/stop default sound automatically in Android?

I want to play and stop the default sound with following rules:
If the sound is not playing, let play it in 10 seconds.
If the sound is playing, let stop it and play at the first position.
Based on these above rules, I design a function as follows:
public MediaPlayer mp =null;
public void playDefaultSound(){
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
mp = MediaPlayer.create(getApplicationContext(), notification);
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(getApplicationContext(), notification);
}
mp.start();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
mp.stop();
mp.release();
}
}, 10000);
} catch (Exception e) {
e.printStackTrace();
}
}
But sometime I still listen two sound are playing (in case of the first sound play and I call the playDefaultSound() function again). Do you think is it correct to delete the mp = MediaPlayer.create(getApplicationContext(), notification); bellow mp.release()? How could I correct the function to satisfy these rules? Thanks all
final MediaPlayer mp = new MediaPlayer();
public void playDefaultSound(){
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
try {
if (mp != null && mp.isPlaying()) {
mp.seekTo(0);
} else {
mp.reset();
mp.setDataSource(getApplicationNotification(), notification);
mp.start();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
mp.stop();
mp.release();
}
}, 10000);
} catch (Exception e) {
e.printStackTrace();
}
}
P.S. - Always see the state diagram or lifecycle of things whenever stuck.
Ref : [Android Media Player State Diagram][1]
[1]: https://developer.android.com/reference/android/media/MediaPlayer.html#StateDiagram "MediaPlayer State Diagram"

Android Mediaplayer Won't Stop

I have the following code to play an mp3 file from the web and this is working but when I use the stop functionality the audio does not stop. Can anyone point me towards a resource to find out more about this or tell me where I am going wrong? Thanks.
showAudio.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
if (!showAudio.getText().equals("Stop")) {
try {
String url = lblAudio.getText().toString();
if (url.length() > 2) {
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
mediaPlayer.start();
showAudio.setText("Stop");
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), "Sorry, there was a problem playing audio.", Toast.LENGTH_SHORT).show();
}
} else {
try {
mediaPlayer.stop();
mediaPlayer.release();
} catch (Exception ex) {
ex.printStackTrace();
}
showAudio.setText("Audio");
}
}
});
You are creating a new MediaPlayer every time you click the button. Create the player outside of the click handler.
Try out :
try {
if(mediaPlayer.isPlaying())
{
mediaPlayer.stop();
mediaPlayer.release();
}
} catch(Exception ex) {
ex.printStackTrace();
}
Try making your media player a global variable and make it static....
I have a working media player that starts and stops
Uri ringtone;
MediaPlayer mp;
ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
mp = MediaPlayer.create(getApplicationContext(), ringtone);
//code to start the mediaplayer
if (Flags.notificationReceived) {
showAlert(Flags.patientModel);
Flags.notificationReceived = false;
mp.start();
mp.setLooping(true);
vibrate(2000);
}
//code to stop the media player
if (mp.isPlaying()) {
mp.stop();
mp.reset();
mp.release();
mp = MediaPlayer.create(getApplicationContext(), ringtone);
}

How to correctly change MediaPlayer audio stream type?

I have a simple mp service to play, pause, resume audio. All works fine.
But, last night I have decided to add a feature for user to route audio to ear-piece or speaker and have been battling with mp.setAudioStreamType().
Problem is that I can't change it while service connected and mp created. I don't want to terminate service and/or unbind and rebind as it would require a lot of refactoring
How do I supposed to change AudioStreamType while playing an audio?
Here is my code:
Player service:
public class PService extends Service {
private MediaPlayer mp = new MediaPlayer();
public static final String PLAYING_FINISHED_MSG = "1";
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
mp.stop();
mp.release();
}
private void playSong(String file) {
try {
mp.reset();
mp.setDataSource(file);
mp.setAudioStreamType(MYAPP.getAudioStreamType());
mp.prepare();
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
Intent i = new Intent();
i.setAction(MDService.PLAYING_FINISHED_MSG);
sendBroadcast(i);
}
});
toggle route button onclick
currentlyPlayingFile = file;
currentlyPlayingPhone = phone;
lastDurationBeforePause = mpInterface.getCurrentPosition();
if(MYAPP.getAudioStreamType() == AudioManager.STREAM_MUSIC)
{
MYAPP.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
recording_player_route_button.setImageResource(R.drawable.route_off);
}
else{
MYAPP.setAudioStreamType(AudioManager.STREAM_MUSIC);
recording_player_route_button.setImageResource(R.drawable.route_on);
}
try {
mpInterface.playFile(file);
player_seekbar.setProgress(0);
player_seekbar.setMax(mpInterface.getDuration());
//seekto last millisecond after switching from/to sepaker
if(seekTo>0)
{
mpInterface.seekTo(seekTo);
}
isPauseButtonPressed = false;
handleSeekBarUpdate.postDelayed(handleSeekBarUpdateJob, 1);
} catch (RemoteException e) {
e.printStackTrace();
}
The MODIFY_AUDIO_SETTINGS permission is needed in the Manifest for this to work.
AudioManager am=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_NORMAL);
MediaPlayer mp=new MediaPlayer();
Uri ringtoneUri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
try
{
mp.setDataSource(getApplicationContext(), ringtoneUri);
mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mp.prepare();
mp.start();
}
catch(Exception e)
{
//exception caught in the end zone
}

media player issue while continuously click on button?

i am playing mp3 sound using default media player of android, my code for plying sound below
MediaPlayer mp=MediaPlayer.create(hello.this,R.raw.abc);
if(mp!=null)
{
mp.start();
}
i need to play same sound on same button click. when i click continuously on button after some time sound is not working and i getting error MediaPlayer(7395): error (-19, 0).
Does any body have idea for this issue,
Please send me
Thank in advance.
call
mp.reset();
because ever time you are decalaring object
or declare on class level Mediaplayer OBject
Make global variable of mediaplayer and try this way
MediaPlayer mp;
if (mp!=null) {
mp.stop();
mp.release();
}
mp= MediaPlayer.create(hello.this,R.raw.abc);
mp.start();
mp = new MediaPlayer();
mp.create(this, R.raw.testmed);
mp.setVolume(100, 100);
mp.setOnPreparedListener(this);
mp.prepare();
Then you will need to define this and it should work:
public void onPrepared(MediaPlayer player) {
mp.start();
}
you can play music like below
// for play the song
MediaPlayer mp = new MediaPlayer();
try
{
mp.reset();
mp.setDataSource(songPath);
mp.prepare();
mp.start();
btnPlay.setBackgroundResource(R.drawable.img_btn_pause);
} catch (IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
I have found solution for this issue. i have correct this issue using below code, May help other also.
Thanks
Call Method like
PlaySound(R.raw.abc);
//Method
private void PlaySound(int Sound_id)
{
mplayer = MediaPlayer.create(Act_Oceanwaves.this,Sound_id);
if(mplayer!=null)
{
mplayer.start();
}
mplayer.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
mp.release();
}
});
}

error -19,0 from using Mediaplayer?

E/MediaPlayer(20473): error (-19, 0)
I/MyApp (20473): Decoding lala.mp3
I/StagefrightPlayer( 68): setDataSource('mypath')
E/AudioFlinger( 68): no more track names available
E/AudioTrack( 68): AudioFlinger could not create track, status: -12
E/AudioSink( 68): Unable to create audio track
Does any1 know why i'm getting this? This usually happens after playing about 100+ of so audio files using mediaPLayer. I'm playing it like this
public RenderResultFormat DoIt() {
if(mp!=null){
mp.release();
mp = null;
}
AudioRenderer mr = new AudioRenderer(); mp = mr.AudioRenderer(filePath);}
private class AudioRenderer extends Activity {
private MediaPlayer AudioRenderer(String filePath) {
//delcare mediaplayer variables, path etc
mp= MediaPlayer.create(this, path);
if(mp != null){
int duration = mp.getDuration();
mp.start();
try {
Thread.sleep(duration);
} catch (InterruptedException e2) {
e2.printStackTrace();
System.out.println("I've been interrupted >:(");
}
}
}return mp;}
Am i missing something? Quite new to android development. Thank you
This solution works well for me (playing a ressource). Just implement an OnCompletionListener
private void playbeep(int id) {
MediaPlayer mPlayer;
mPlayer = MediaPlayer.create(context, id);
mPlayer.start();
mPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}

Categories

Resources