Stop played sound in android - java

I used this code for play a sound by click on a button.
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.stop();
}
try {
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("sound/07.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
it's working well but i can't stop sound!
I use mp.stop(); .but click on button plays sound again!

when your onClickListener runs, the if statement checks after that other codes run. try to put an else statement after if you code should be like this :
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.stop();
}else{
try {
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("sound/07.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});

Related

Android MediaPlayer: How to stop if another audio file is being loaded?

I have a problem with the Android MediaPlayer. As soon as a new sound file is clicked by user input, the old one does not stop, so all audio files overlap.
I already tried common methods like MediaPlayer.stop(); and
MediaPlayer.release();
These methods always result in an app crash, although they are called in the correct order
public void Abspielen(String Datei) {
try {
AndreasPlayer = MediaPlayer.create(MainActivity.this, getResources().getIdentifier(Datei, "raw", getPackageName()));
AndreasPlayer.start();
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Abspielen("filename");
}
I worked out the following solution:
public void Abspielen(String Datei) {
try {
stopKnopf = findViewById(R.id.fab2);
stopKnopf.show();
try {
if (AndreasPlayer.isPlaying()) {
AndreasPlayer.reset();
}
} catch (Exception ex) {
}
AndreasPlayer = MediaPlayer.create(MainActivity.this, getResources().getIdentifier(Datei, "raw", getPackageName()));
AndreasPlayer.start();
stopKnopf.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AndreasPlayer.reset();
stopKnopf.hide();
}
});
AndreasPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
AndreasPlayer.reset();
stopKnopf.hide();
}
});
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}

I get error (1, 19) when tapping on multiple buttons that play sound

It works for a few buttons, but when I tap about 6 then only some of them work. The ones that don't work give the error (1, -19). I do the media player state wrapper set up, so if I need to use that to get states of my "mp"s, let me know.
public class SoundFile {
public SoundFile(final Activity activity, final String soundfile, int imgButtonId, ArrayList<MediaPlayerStateWrapper> mps) {
this.mp = new MediaPlayerStateWrapper();
try {
this.afd = activity.getAssets().openFd(soundfile + ".mp3");
} catch (IOException e) {
e.printStackTrace();
}
this.allMps = mps;
mps.add(this.mp);
this.position = (ImageButton) activity.findViewById(imgButtonId);
this.position.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mp.reset();
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepareAsync();
mp.start();
}catch (Exception ex){
ex.printStackTrace();
}
....
You have to add an onPreparedListener. Here is what I did and it worked.
try {
mp = new MediaPlayer();
mp.reset();
try {
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IOException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mp.release();
}
});
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mpm) {
mpm.start();
mp.start();
}
});
mp.prepareAsync();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
}

Creating an listview which displays records

outputfile= Environment.getExternalStorageDirectory().getAbsolutePath()+"/recording.3gp";;
audiorecorder = new MediaRecorder();
audiorecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
audiorecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
audiorecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
audiorecorder.setOutputFile(outputfile);
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
audiorecorder.prepare();
audiorecorder.start();
}
catch (IllegalStateException e)
{
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
record.setEnabled(true);
stop.setEnabled(true);
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_SHORT);
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
audiorecorder.stop();
audiorecorder.release();
audiorecorder =null;
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(getApplicationContext(), "Record successfully recorded", Toast.LENGTH_SHORT);
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MediaPlayer m = new MediaPlayer();
try{
m.setDataSource(outputfile);
}
catch ( IOException e)
{
e.printStackTrace();
}
try{
m.prepare();
}
catch(IOException e)
{
e.printStackTrace();
}
m.start();
Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_SHORT);
}
});
This is the record ive created .I created another intent which contains a listview which i want to display in it the records SAVED.
any idea how to save the records? and then how to display them in the listview?

Unable to stop MusicPlayer even after finishing an Activity.

I've set MediaPlayer to play different songs. However, when I try to close the Application, the Activity gets closed, but the song still run in the Background. Here is how I've coded it!
try {
mp.setDataSource(text);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mp.prepare();
mp.setVolume(0.4f, 0.4f);
songPlayer.setDataSource(song);
songPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer songPlayer) {
songPlayer.start();
}
});
songPlayer.prepare();
songPlayer.setLooping(true);
voicePlayer.setDataSource(voice);
voicePlayer.setLooping(true);
voicePlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer voicePlayer) {
voicePlayer.start();
}
});
voicePlayer.prepare();
voicePlayer.setVolume(0.5f,0.5f);
}
catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (IllegalMonitorStateException e)
{
e.printStackTrace();
}
//THIS IS WHERE I THINK THE ERROR IS :
//WHERE `mp` IS LOOPED WITH DELAY OF 5000ms
try {
final Handler hlr = new Handler();
final Runnable looper = new Runnable() {
#Override
public void run() {
if (mp != null) {
if (mp.isPlaying()) {
mp.stop();
}
}
mp.start();
}
};
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
hlr.postDelayed(looper, 5000);
}
});
}
catch(IllegalStateException e)
{
e.printStackTrace();
}
}
}
And there is also One method which restarts the activity after a specified time. And the code for that Activity is :
public void snoozeup(View view)
{
SharedPreferences sa = getSharedPreferences("SnoozeList", Context.MODE_PRIVATE);
int snox = sa.getInt("SnoozeX",0);
if(snox==2) {
Handler handler = new Handler();
Runnable x = new Runnable() {
#Override
public void run()
{
Intent intent = new Intent(Time_Date.this, Time_Date.class);
intent.putExtra("finisher", state);
startActivity(intent);
}
};
handler.postDelayed(x, 120000);
}
else
{
Handler handler = new Handler();
Runnable x = new Runnable() {
#Override
public void run() {
startActivity(new Intent(Time_Date.this, Time_Date.class));
}
};
handler.postDelayed(x, 180000);
}
try
{
if (mp != null && mp.isPlaying())
{
Log.d("TAG------->", "mp is running");
mp.stop();
Log.d("TAG------->", "mp is stopped");
mp.reset();
mp.release();
Log.d("TAG------->", "mp is released");
mp=null;
}
if (voicePlayer != null && voicePlayer.isPlaying()) {
Log.d("TAG------->", "voiceplayer is running");
voicePlayer.stop();
Log.d("TAG------->", "voiceplayer is stopped");
voicePlayer.release();
Log.d("TAG------->", "voiceplayer is released");
}
if (songPlayer != null && songPlayer.isPlaying()) {
Log.d("TAG------->", "songplayer is running");
songPlayer.stop();
Log.d("TAG------->", "songplayer is stopped");
songPlayer.release();
Log.d("TAG------->", "songplayer is released");
}
}
catch(Exception e)
{
e.printStackTrace();
}
finish();
}
The problem is with mp . Other instances of MediaPlayer gets stopped. But not mp. And sadly, Can't see any error in logcat as well. So where am I doing wrong? Any help will be appreciated.
In order to stop the music you should put this code in the onPause() method.
This method can be overrided from your class that inherite from Activity
#Override
protected void onPause() {
super.onPause();
mp.stop
}
You can also take a look at Managing the Activity Lifecycle to better understand how an activity is managed by Android.
You are destroying your activity, but you need to stop/destroy your media player too. Please write down the following code in your activity.
#Override
public void onDestroy() {
super.onDestroy();
if (mp!= null) {
//destory ur object here.
}
}
Put in either onPause() or onDestroy() Example:
#Override
protected void onPause() {
super.onPause();
mp.stop();
}

Stopping mediaplayer using mediaplayer.stop is not working

I am new in android programming. I have a problem in stopping mediaplayer when I click the button for stop. I think I have some problem with my code because my sounds are looping that's is why mp.stop(); is not working or probably because of the sleep? I am not sure. Is there anyone who can help me with these? Thanks in advance.
Here is my code for stop:
bb5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0){
if (mp.isPlaying()){
mp.stop();
}
} // END onClick()
});
Here is my code for playing the sound:
protected void managerOfSound() {
int size = tempq.size();
for (int i = 0; i < tempq.size(); i++) {
String u =tempq.get(i);
//WHOLE
if (u.equals("a4")){
mp = MediaPlayer.create(this, R.raw.a4);
mp.start();
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
// TODO Auto-generated catch block
}
}else if (u.equals("b4")){
mp = MediaPlayer.create(this, R.raw.b4);
mp.start();
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
// TODO Auto-generated catch block
}
}else if (u.equals("c4")){
mp = MediaPlayer.create(this, R.raw.c4);
mp.start();
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
// TODO Auto-generated catch block
}

Categories

Resources