onDestroy mediaplayer release - android

I want when I click on back button on the phone to close current activity and get back to menu and stop Media Player
But I get error: Unfortunately Weapons has stopped! upon clicking on back button
So how to fix that?
public class pushke extends Activity {
private SeekBar volumeSeekbar = null;
private AudioManager audioManager = null;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.guns);
initControls();
final MediaPlayer mp=MediaPlayer.create(this, R.raw.uzi);
ImageButton btn1 = (ImageButton) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mp.isPlaying()){
mp.pause();
mp.seekTo(0);
}
else{
mp.start();
}
}
});
}
private void initControls()
{
try
{
volumeSeekbar = (SeekBar)findViewById(R.id.seekBar1);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
volumeSeekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar arg0)
{ }
#Override
public void onStartTrackingTouch(SeekBar arg0)
{ }
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2)
{
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mp.release();
}
}
Logcat:

1) I want when I click on back button on the phone to close current
activity and get back to menu and stop Media Player
1) What do you mean by menu? I mean application menu or device menu or notification bar etc.
2) But I get error: Unfortunately Weapons has stopped! upon clicking on
back button So how to fix that?
2)
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(mp!=null){
mp.stop();
mp.release();
mp = null;
}
}
EDIT:
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.guns);
initControls();
mp=MediaPlayer.create(this, R.raw.uzi);
ImageButton btn1 = (ImageButton) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mp.isPlaying()){
mp.pause();
mp.seekTo(0);
}
else{
mp.start();
}
}
});
}

In On destroy before releasing media player please stop the media player

Related

How to make ImageButton repeat a sound each time it's clicked

I am trying to get the Image Button to play a sound each time it's clicked. For example, if the sound is playing for few seconds and I press the button again it should start from the beginning. I managed to get the sound working but it's not repeating it. How can I get it to start over?
ImageButton bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (ImageButton) findViewById(R.id.clickme);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.bird);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
}
Try this:
#Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.bird);
}
mp.start();
} catch(Exception e) {
e.printStackTrace();
}
}
Use MediaPlayer.seekto() to seek to the start of the audio file.
ImageButton bt;
private MediaPlayer mp = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (ImageButton) findViewById(R.id.clickme);
mp = MediaPlayer.create(this, R.raw.bird);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying()) {
mp.seekTo(0);
} else {
mp.start();
}
}
});
}

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

Getting java.lang.IllegalStateException When I unlcok screen

When i launch app and lock the screen without clicking(playing audio) button and after when i unlock the screen and press the play button i am getting Exception.
public class DemoActivity extends Activity {
MediaPlayer mp;
Button btn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mp = MediaPlayer.create(DemoActivity.this,R.raw.mus);
btn = (Button) findViewById(R.id.btnOk);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (btn.getText().toString().equalsIgnoreCase("play")) {
mp.start();
btn.setText("Pause");
} else if (btn.getText().toString().equalsIgnoreCase("pause")) {
mp.pause();
btn.setText("Play");
}
}
});
#Override
public void onPause() {
super.onPause();
if (mp.isPlaying()) {
mp.start();
} else {
mp.release();
}
}
#Override
protected void onRestart() {
try {
if (mp.isPlaying() && mp!=null) {
mp.start();
} else {
mp.release();
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
super.onRestart();
}
#Override
protected void onDestroy() {
super.onDestroy();
mp.release();
}
}
Here is my code please try to give me a solution.
Thanks in advance
please try call mp.prepare() before every mp.start(). You are getting the error because the mp is not yet ready for your use, and calling start() on that will cause IllegalStateException.

how to make mediaplayer is playing even after exit application

whenever i click back or click home the sound is stop.. how to make the sound is still playing even when i click home or back button.. sorry for my english.. thank you
here is my main_activity code
public class Child extends Activity{
private static final String isPlaying = "Media is Playing";
private MediaPlayer player;
private Button jakartaButton;
private Button acehButton;
private Button jogjaButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.child);
// Get the button from the view
jakartaButton = (Button) this.findViewById(R.id.jakarta);
jakartaButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
playSound(1);
}
});
acehButton = (Button) this.findViewById(R.id.aceh);
acehButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
playSound(2);
}
});
jogjaButton = (Button) this.findViewById(R.id.jogja);
jogjaButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
playSound(3);
}
});
}
#Override
public void onPause() {
try{
super.onPause();
player.pause();
}catch (Exception e){
}
}
private void playSound(int arg){
try{
if (player.isPlaying()) {
player.stop();
player.release();
}
}catch(Exception e){
Toast.makeText(this, " Masuk Exception", Toast.LENGTH_LONG).show();
}
if (arg == 1){
Toast.makeText(this, isPlaying+" jakarta", Toast.LENGTH_LONG).show();
player = MediaPlayer.create(this, R.raw.jakarta);
}else if (arg == 2){
Toast.makeText(this, isPlaying+" aceh", Toast.LENGTH_LONG).show();
player = MediaPlayer.create(this, R.raw.aceh);
}else if (arg == 3){
Toast.makeText(this, isPlaying+" jogja", Toast.LENGTH_LONG).show();
player = MediaPlayer.create(this, R.raw.yogya);
}
player.setLooping(true); // Set looping
player.start();
}
whenever i click back or click home the sound is stop.. how to make the sound is still playing even when i click home or back button.. sorry for my english..
There is a Google sample project about playing music across different Android platforms, like Phone, Pad, Watch, Auto... It can keep music playing even app is exited. Take a deep look at here , and I think you will be inspired a lot.

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

Categories

Resources