Call Release and play multiple sound - android

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

Related

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

How to stop an object with the press of a button

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

How to avoid IllegalStateException with MediaPlayer

I have a stop button and a play button. When I click the play button, the audio plays fine and when I press stop, the audio stops. However, if I accidently hit the stop button twice in a row, an IllegalStateException gets thrown and force closes. How can I keep this force close from happening. Essentially what I want is that if someone accidently hits the stop button twice, the program does nothing. Here is the code:
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alphabet);
Button play = (Button) findViewById(R.id.button1);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp = MediaPlayer.create(getBaseContext(), R.raw.e_1100);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
});
Button stop = (Button) findViewById(R.id.button2);
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mp != null && mp.isPlaying()) {
mp.stop();
mp.release();
}
else if (mp.isPlaying() == false) {
// What do I put here???
}
}
});
}
}
try this
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}

Stop button is not working

This is a code for play and stop mediaplayer
It made music successfully and played that.But stop button didn't work
Why it's not working?
Please lead me to the correct code
Thanks
mp = MediaPlayer.create(this, Uri.parse(Environment.getExternalStorageDirectory().getPath()+ "/Titraj/"+name+".mp3"));
play.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
if(mp.isPlaying()){
if(mp!=null){
mp.pause();
play.setImageResource(R.drawable.play);
}
}else{
if(mp!=null){
mp.start();
play.setImageResource(R.drawable.pa);
}
}
}
});
stop.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
if(mp.isPlaying()){
if(mp!=null){
mp.stop();
}
}
}
});
mp.setOnCompletionListener(new OnCompletionListener(){
#Override
public void onCompletion(MediaPlayer arg0) {
play.setImageResource(R.drawable.play);
}
});
Use this one....
stop.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
});
Also must check you haven't set android:focusable = false for your button in xml file.
Try this in your on stop method
mp.stop();
mp.release();
mp= null;
mp = MediaPlayer.create(this, Uri.parse(Environment.getExternalStorageDirectory().getPath()+ "/Titraj/"+name+".mp3"));
play.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
if(mp.isPlaying()){
if(mp!=null){
mp.pause();
play.setImageResource(R.drawable.play);
}
}else{
if(mp!=null){
mp.start();
play.setImageResource(R.drawable.pa);
}
}
}
});
stop.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
if(mp.isPlaying()){
mp.stop();
}
}
});
mp.setOnCompletionListener(new OnCompletionListener(){
#Override
public void onCompletion(MediaPlayer arg0) {
play.setImageResource(R.drawable.play);
}
});
Check this code i hop it working....

Categories

Resources