-1

So I have a button that plays the selected file. However I want to pause the play when the button is pressed again. I checked a few StackOverflow posts and tutorials and the pause method is what was used in most cases. However it is not working for me. The audio keeps on playing. Am I missing something or is there a problem with my code? Any help is appreciated. Thanks!

buttonPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String fileName = getFileSelected();
                MediaPlayer m = new MediaPlayer();
                    if ( !m.isPlaying() && (getFileSelected().endsWith(".3gp") || getFileSelected().endsWith(".wav"))) {
                    try {
                        m.setDataSource(getActivity().getApplicationContext().getExternalFilesDir(null).toString() + File.separator + fileName);
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (IllegalArgumentException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IllegalStateException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        try {
                            m.prepare();
                        } catch (IllegalStateException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                            isPlaying = true;
                            buttonPlay.setText("Stop");
                        m.start();
                        Toast.makeText(getActivity().getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
                    }
                    else{
//                            m.stop();
//                            m.release();
//                            m = null;
                            m.pause();
                            isPlaying = false;
                            setButtonLabel(R.id.btnPlay, "Play Selected Recording");
                       }

            }
        });
skbrhmn
  • 1,124
  • 1
  • 14
  • 36
  • 1
    You are doing the same mistake as [here](http://stackoverflow.com/questions/6234838/mediaplayer-pause-doesnt-work-in-android), You shouldn't initialize new instance of `MediaPlayer` inside `onClick`. – Shree Krishna Jun 17 '16 at 05:18

3 Answers3

2

Your MediaPlayer does not pause because you are fetching music file, initializing mediaPlayer, preparing it and starting media player every time the button is clicked!

You should initialize media player only once and out side the button click listener and just start or pause it when button is clicked.

String fileName = getFileSelected();
MediaPlayer m = new MediaPlayer();

buttonPlay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

                if ( !m.isPlaying() && (getFileSelected().endsWith(".3gp") || getFileSelected().endsWith(".wav"))) {
                try {
                    m.setDataSource(getActivity().getApplicationContext().getExternalFilesDir(null).toString() + File.separator + fileName);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (IllegalArgumentException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IllegalStateException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    try {
                        m.prepare();
                    } catch (IllegalStateException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                        isPlaying = true;
                        buttonPlay.setText("Stop");
                    m.start();
                    Toast.makeText(getActivity().getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
                }
                else{
//                            m.stop();
//                            m.release();
//                            m = null;
                            m.pause();
                            isPlaying = false;
                            setButtonLabel(R.id.btnPlay, "Play Selected Recording");
                       }

            }
        });
Apurva
  • 7,871
  • 7
  • 40
  • 59
1

this code surely work.Try it.

public AudioManager audioManager = null;
public boolean playing;
Button btnRequestFocus = (Button) findViewById(R.id.btnRequestFocus);

    btnRequestFocus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            boolean gotFocus = requestAudioFocusForMyApp(MainActivity.this);
            if (gotFocus) {
                //play audio.

            }
        }
    });


    Button btnReleaseFocus = (Button) findViewById(R.id.btnReleaseFocus);
    btnReleaseFocus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Stop playing audio.
            releaseAudioFocusForMyApp(MainActivity.this);
        }
    });
}

private boolean requestAudioFocusForMyApp(final Context context) {

    AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

    // Request audio focus for playback
    int result = am.requestAudioFocus(afChangeListener,
            // Use the music stream.
            AudioManager.STREAM_MUSIC,
            // Request permanent focus.
            AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE);

    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        Log.d("AudioFocus", "Audio focus received");

        return true;
    } else {
        Log.d("AudioFocus", "Audio focus NOT received");
        return false;
    }
}

void releaseAudioFocusForMyApp(final Context context) {
    AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
     tts.stop();

    am.abandonAudioFocus(afChangeListener);
}
AudioManager.OnAudioFocusChangeListener afChangeListener = new     AudioManager.OnAudioFocusChangeListener() {
    public void onAudioFocusChange(int focusChange) {
        if (focusChange == AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE)   {
            // Lower the volume
        } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
            // Raise it back to normal
        }
    }
0
if (m.isPlaying()) {
  m.pause();
  isPlaying = false;
  setButtonLabel(R.id.btnPlay, "Play Selected Recording");
} else {
  Toast.makeText(this, "Media Player is not playing", Toast.LENGTH_LONG).show();
}
Sohail Zahid
  • 8,099
  • 2
  • 25
  • 41