AudioManager volume starts high then goes low - android

I have the following code to play the default ringtone when a call is incoming.
Here is the code:
public AudioPlayer(Context c){
AudioManager am = (AudioManager)c.getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_RINGTONE);
mp = new MediaPlayer();
}
public void playRingtone(){
try{
mp.setDataSource(mContext.getApplicationContext(), Settings.System.DEFAULT_RINGTONE_URI);
mp.prepare();
mp.start();
}
catch(Exception e){
System.out.println("AudioManager: " + e.getLocalizedMessage());
}
}
public void stopRingtone(){
if(mp.isPlaying()){
mp.stop();
mp.reset();
mp.release();
}
}
This code starts playing the ringtone at the proper volume level but then cuts out and plays really really low. What is the reason for the change in volume and how can I fix it?
Thank you for your help

Related

Wait for a sound to end playing. Is this correct?

In my application I need to play a sound in different moments and wait for it to end before doing anything else. Right now I have this code for playing sound:
private MediaPlayer mPlayer = null;
private boolean playSound(){
mPlayer = new MediaPlayer();
try{
mPlayer.setDataSource(openFileInput(fileName).getFD());
mPlayer.prepare();
mPlayer.start();
} catch (Exception e){
e.printStackTrace();
Log.e("player", "error playing sound: "+fileName);
return false;
}
while(mPlayer.isPlaying());
mPlayer.release();
mPlayer = null;
return true;
}
It's not working as I expected: when changing an image before playing the sound the change happens after the sound is played (I suppose it's for the thread queue or something like this)
I don't know if this is a bad solution or if there is any better solution for my case:
the sound playing must start after all previous work is finished.
the app must not do any other work while playing the sound.
the code to execute after the sound playing is not always the same.
You should implement a completion listener:
public class myclass extends .... implements OnCompletionListener, ... {
private int nextAction; // not the smatest solution, but good enough :)
...
private boolean playSound(next){
nextAction = next;
mPlayer = new MediaPlayer();
try{
mPlayer.setDataSource(openFileInput(fileName).getFD());
mPlayer.prepare();
mPlayer.setOnCompletionListener(this);
mPlayer.start();
} catch (Exception e){
e.printStackTrace();
Log.e("player", "error playing sound: "+fileName);
return false;
}
#Override
public void onCompletion(MediaPlayer mp) {
// do your stuff, destroy the mplayer, if needed
switch(nextAction){
case ACTION1: ...; break;
case ACTION2: ...; break; //..and so on
}
}

MediaPlayer sound not always playing, not getting granted audio focus

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();
}

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();
}
});
}

MediaPlayer vs SoundPool for only 1 simultaneous stream

I'm working on a game in which one single sound is played each time the phone is shaked.
Does it make sense to use a SoundPool and load sounds in the onCreate of my activity, or is it ok to create a mediaplayer each time, as shown below:
private void onShake() {
MediaPlayer mp= MediaPlayer.create(this, whipSound[currentWhip][force]);
mp.start();
}
My guess is that SoundPool is better because the sounds are loaded only once. Am I right?
Thanks
Julien
As expected, SoundPool is much faster...
You can create the mediaPlayer outside the onShake method, and then reset and start it on every shake:
MediaPlayer mp= MediaPlayer.create(this, whipSound[currentWhip][force]);
...
private void onShake() {
mp.reset();
mp.start();
}
//or
private void onShake() {
try {
mp.stop();
mp.prepare();
} catch (IllegalStateException e) { /* Ignore */
} catch (IOException e) {/* Ignore */ }
try {
mp.start();
} catch (IllegalStateException e) {
Log.e(TAG, "MediaPlayer failed ", e);
}
}

Categories

Resources