How to stop an object with the press of a button - android

I am fairly new to programming and having a tough time with a small problem. I have created an object which is initialized easily and starts working, how do i stop that object from functioning.
Following is my code:
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
animationFart();
playRandomSound();
}
private void playRandomSound() {
// TODO Auto-generated method stub
int randomInt = (new Random().nextInt(soundList.size()));
int sound = soundList.get(randomInt);
MediaPlayer mp = MediaPlayer.create(btn.getContext(), sound);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
});
How can i stop this with the press of a button.

Define MediaPlayer mp; globally and use mp.stop();:
if (mp!=null && mp.isPlaying()) {
mp.stop();
}

use this class
public class AudioPlayer {
private MediaPlayer mediaPlayer;
public void play(Context context, int resId) {
stop();
mediaPlayer = MediaPlayer.create(context, resId);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
stop();
}
});
mediaPlayer.start();
}
public void stop() {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
public boolean isPlaying() {
return mediaPlayer != null;
}
}

Related

Code to make a single MediaPlayer play more than one piece of sound in android studio

Being a novice coder, trying to code an app that plays a sound on buttonclick in a fragment; successfully did it but I want to add more small pieces of sounds to play one after another. How can I add those sounds(sound2, sound3, sound4, etc) after that 'R.raw.sound1'? Please guide..
buttonPlayAudioVar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp != null) {
if(mp.isPlaying()){
mp.stop();
mp.release();
}
}
mp = MediaPlayer.create(getActivity().getApplicationContext(), R.raw.sound1);
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
mp.release();
mp = null;
}
});
}
});
//you can add all the songs in a array
ArrayList<String> songsArray = new ArrayList<>();
int position = 0;
buttonPlayAudioVar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer(songsArray, position);
}
});
private void mediaPlayer(ArrayList<String> songsArray) {
if (mp != null) {
if (mp.isPlaying()) {
mp.stop();
mp.release();
}
}
if (position > songsArray.size() - 1) {
return;
}
try {
mp.setDataSource(songsArray.get(position));
position++;
mp.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
mp.release();
mp = null;
mediaPlayer(songsArray, position);
}
});
}

Android is hanging when I press button to play music in second time

I used these codes from this reference. They want to click on button to play music and then click again to stop playing. (in their comment they said it was worked for them but hanging for me)
It is work just for first time. I mean for first click the music is playing. for second click the music is stop but for third click the phone emulator show this error:
unfortunately your program has stopped.
This is my code:
public MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button) findViewById(R.id.btnRain);
//mp = MediaPlayer.create(this, R.raw.rain);
mp = MediaPlayer.create(MainActivity.this, R.raw.rain);
btn.setOnClickListener(new View.OnClickListener() {
#Override
//MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.soundFileName);
// mp.start();
public void onClick(View v) {
if (mp.isPlaying()) {
mp.stop();
mp.release();
}
else {
mp.start();
}
}
});
}
In onCreate initialize mp as :
mp = new MediaPlayer();
The error is you are releasing the media player object mp, which destroys the object, call reset method instead of release.
if (mp.isPlaying())
{
mp.stop();
mp.reset();
}
else {
mp = MediaPlayer.create(LegalActivity.this, R.raw.free1);
mp.start();
}
use this below code for play and pause the music:
public MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button) findViewById(R.id.btnRain);
//mp = MediaPlayer.create(this, R.raw.rain);
mp = MediaPlayer.create(MainActivity.this, R.raw.rain);
btn.setOnClickListener(new View.OnClickListener() {
#Override
//MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.soundFileName);
// mp.start();
public void onClick(View v) {
if (mp.isPlaying()) {
mp.pause();
}
else {
mp.start();
}
}
});
}
This is an AUDIO activity that works fine and it allows you to upload songs with a spinner.
public class AUDIO extends Activity{
Spinner spCanciones;
Button btnRep,btnGra,btnParar;
File audios;
String cancionSelec;
String arquivoGravar;
private MediaPlayer mediaplayer;
private boolean pause;
private MediaRecorder mediaRecorder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio);
spCanciones=(Spinner)findViewById(R.id.spCanciones);
btnGra=(Button)findViewById(R.id.btnGra);
btnParar=(Button)findViewById(R.id.btnParar);
btnRep=(Button)findViewById(R.id.btnRep);
mediaplayer=new MediaPlayer();
enlazarSpinner();
//REPRODUCIR
btnRep.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
reproducir();
}
});
//PARAR
btnParar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaplayer.isPlaying())
mediaplayer.stop();
pause=false;
}
});
//GRABAR
btnGra.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
grabarAudio();
}
});
}
public void enlazarSpinner(){
final ArrayList<String>songs=new ArrayList<>();
audios=new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"/AUDIO/");
String [] play=audios.list();
for (int i=0;i<play.length;i++)songs.add(play[i]);
ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, songs);
// Opcional: layout usuado para representar os datos no Spinner
adaptador.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Enlace do adaptador co Spinner do Layout.
spCanciones.setAdapter(adaptador);
// Escoitador
spCanciones.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
cancionSelec = songs.get(pos);
Log.i("Cancion", cancionSelec);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}); // Fin da clase anónima
}
public void reproducir(){
try {
mediaplayer.reset();
mediaplayer.setDataSource(Environment.getExternalStorageDirectory().getAbsolutePath()+"/AUDIO/"+cancionSelec);
mediaplayer.prepare();
mediaplayer.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("MULTIMEDIA",e.getMessage());
}
}
public void grabarAudio(){
String timeStamp = DateFormat.getDateTimeInstance().format(
new Date()).replaceAll(":", "").replaceAll("/", "_")
.replaceAll(" ", "_");
mediaRecorder = new MediaRecorder();
arquivoGravar = Environment.getExternalStorageDirectory().getAbsolutePath()+"/AUDIO/"+ timeStamp + ".3gp";
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setMaxDuration(10000);
mediaRecorder.setAudioEncodingBitRate(32768);
mediaRecorder.setAudioSamplingRate(8000); // No emulador só 8000 coma
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mediaRecorder.setOutputFile(arquivoGravar);
try {
mediaRecorder.prepare();
} catch (Exception e) {
// TODO Auto-generated catch block
mediaRecorder.reset();
}
mediaRecorder.start();
AlertDialog.Builder dialog = new AlertDialog.Builder(this)
.setMessage("GRAVANDO").setPositiveButton(
"PREME PARA PARAR",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
}
});
dialog.show();
enlazarSpinner();
}
#Override
protected void onPause() {
super.onPause();
if (mediaplayer.isPlaying()){
mediaplayer.pause();
pause = true;
}
}
#Override
protected void onResume() {
super.onResume();
if (pause) {
mediaplayer.start();
pause = false;
}
}
#Override
protected void onSaveInstanceState(Bundle estado) {
estado.putBoolean("MEDIAPLAYER_PAUSE", pause);
super.onSaveInstanceState(estado);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.putBoolean("MEDIAPLAYER_PAUSE", false);
pause = savedInstanceState.getBoolean("MEDIAPLAYER_PAUSE");
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mediaplayer.isPlaying()) mediaplayer.stop();
if (mediaplayer != null) mediaplayer.release();
mediaplayer = null;
}
}

Android audio play and stop

this is the method am using..and will call whenever required...in my case i want to control that audio by one button whether it may toggle or button...
click to start and stop in one button
private void playSound() {
if (isFlashLightOn) {
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off);
} else {
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});mp.start(); playing=true;
}
An edited version of your code
private void playSound() {
if (isFlashLightOn) {
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off);
} else {
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
}
mp.prepareAsync(); //prepares the MediaPlayer
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
//MediaPlayer instance prepared
mp.start(); //play the content
playing=true;//update the flag
}
});
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release(); //playback finished
playing=false; //update the flag
}
});
}
more info on MediaPlayer here
Onclick pause:
public void pause(View view) {
Toast.makeText(getApplicationContext(),
"Pausando..", Toast.LENGTH_SHORT)
.show();
if (mp != null && mp.isPlaying()) {
mp.pause();
}
}//pause
Onclik stop-
public void stop(View view) {
Toast.makeText(getApplicationContext(),
"Stop", Toast.LENGTH_SHORT)
.show();
if (mp != null) {
mp.stop();
}//if
}//stop

Call Release and play multiple sound

with this code I want to stop all the sounds that are being executed, and play only the button clicked, but calling the release, the sound becomes null and you can not run the sound again. but if you do not call release give me problem anyway. how can I find a solution to this conundrum?
Code:
public MediaPlayer mediaPlayer = null;
public Boolean playing = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button)findViewById(R.id.b1);
b1.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v){
if(mediaPlayer != null && mediaPlayer.isPlaying()) mediaPlayer.stop();
mediaPlayer = MediaPlayer.create(menu.this, R.raw.b1);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
playing=true;
};
});
}
});
Button b2 = (Button)findViewById(R.id.b2);
b2.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v){
if(mediaPlayer != null && mediaPlayer.isPlaying()) mediaPlayer.stop();
mediaPlayer = MediaPlayer.create(getBaseContext(),R.raw.b2);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
};
});
}
});
}});
I solved by this:
b1.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v){
if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
mediaPlayer.stop();
mediaPlayer.release();
}
mediaPlayer = MediaPlayer.create(menu.this, R.raw.b1);
mediaPlayer.start();
}});

sound doesn't stop when the user press back key

I'm newbie in android programming. I have the following code with a mediaplayer. when the user presses the back key or goes to another activity the sound won't stop.
what's the problem? I have the onDestory method but my problem exists!
public class Elementary1Activity extends Activity implements Runnable, OnClickListener, OnSeekBarChangeListener{
private SeekBar seekBar;
private ImageButton startMedia;
private ImageButton pauseMedia;
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.elementary1);
AudioControl();
}
public void AudioControl(){
seekBar = (SeekBar) findViewById(R.id.seekBarnew2);
startMedia = (ImageButton) findViewById(R.id.playbuttonnew2);
pauseMedia = (ImageButton) findViewById(R.id.pausebuttonnew2);
seekBar.setOnSeekBarChangeListener(this);
startMedia.setOnClickListener(this);
pauseMedia.setOnClickListener(this);
}
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
public void onClick(View v) {
pauseMedia.setVisibility(View.VISIBLE);
seekBar.setVisibility(View.VISIBLE);
startMedia.setVisibility(View.INVISIBLE);
if (v.equals(startMedia)) {
if (mp != null && mp.isPlaying()) return;
if(seekBar.getProgress() > 0) {
mp.start();
return;
}
mp = MediaPlayer.create(Elementary1Activity.this, R.raw.e1);
mp.start();
seekBar.setProgress(0);
seekBar.setMax(mp.getDuration());
new Thread(this).start();
}
if (v.equals(pauseMedia) && mp!=null) {
mp.pause();
pauseMedia.setVisibility(View.INVISIBLE);
startMedia.setVisibility(View.VISIBLE);
}
}
#Override
public void onDestroy() {
super.onStop();
mp= MediaPlayer.create(Elementary1Activity.this,R.raw.e1);
if(mp.isPlaying())
{
mp.stop();
mp.release();
finish();
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if(fromUser) mp.seekTo(progress);
}
}
I'd use onPause() event in your Elementary1Activity to manage the music pausing.
Something like:
#Override
public void onPause() {
super.onPause();
if (mp!=null) {
mp.pause();
}
}
You can do two things. If you want that MediaPlayer stop when you push back button and you want to close the app the best option is:
#Override
public void onDestroy(){
if(mp != null){
if(mp.isPlaying()){
mp.stop
}
mp.release();
}
super.onDestroy();
}
And if you want to make that MediaPlayer stop when you change of activity:
#Override
public void onPause(){
if (mp != null && mp.isPlaying()){
mp.pause();
}
}
Apart of that, don't create a new MediaPlayer when you want to close your app.

Categories

Resources