Sound should only play once but plays twice instead - java

I am building an app with flash cards. When you click the "next" button it plays a sound(the name of the card) and it also plays the same sound if you click on the card. The only thing is when I click on the "next" button it plays the sound twice, simultaneously, causing it to sound robotic. I assume I'm calling the sound twice by accident but I don't know where or how to fix it. I've been looking all over the place but can't find a way to fix this.
Here is my code:
private String[] soundfile={"aa.m4a","bb.m4a...
public void onClick(View arg0) {...
//when btnplay is clicked
else if(arg0.getId()==R.id.imagenumber){
//call the method playsound
playSound(soundfile[screennumber].toString());
}//end btnsound clicked
//begin changeCard
private void changeCard(int screen){
switch (screen){
case 0: imagenumber.setImageResource(aa);
mediap2 = MediaPlayer.create(this, R.raw.aa);
break;...
mediap2.start();
}//end changeCard
//begin playSound on click
public void playSound(String soundName){
Boolean mpPlayingStatus;
try{//try to check MediaPlayer status
mpPlayingStatus=mp.isPlaying();
}
catch (Exception e){
mpPlayingStatus=false;
}
if(mpPlayingStatus==true){//if the MediaPlayer is playing a voice, stop it to play new voice
mp.stop();
mp.release();//remove sound from memory
}
else{
try
{
mp = new MediaPlayer();
AssetFileDescriptor afd = getAssets().openFd(soundName);
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare();
mp.start();//play sound
}//try block
catch(Exception e) {
Log.i("Error playing sound: ", e.toString());
}
}
}//end playSound
Thanks for the help!

Oh wow. I figured it out. This whole time I thought it was strictly an issue with the sound itself but it turns out the problem was here:
if(arg0.getId()==R.id.btnprevious){
screennumber--;//minus 1 to the screennumber
changeNumber(screennumber);
if(screennumber==0){
//disable btnprevious
btnprevious.setEnabled(false);
}else{
//enable btnprevious
btnprevious.setEnabled(true);
}
changeNumber(screennumber);
btnnext.setEnabled(true);
}
Where I called changeNumber(screennumber);
btnnext.setEnabled(true);
twice. Silly mistake. Thanks for your help anyway!

Related

Playing songs one after another in Android(Java)

I want to play songs one after another in my music player app. I checked this question but my music player plays the next song only once. After that it stops. For example, it's playing Song A, then it'll play next Song B, but after song B it won't play Song C.
Here is my code:
OnCompleteListener:
//mp is MediaPlayer object, al is ArrayList of songs and their ids(R.raw.song), song_no is the index of the song in al
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
song_no = (song_no +1) % al.size();
playSong();
}
});
I have the same code for "next" button which works perfectly, even after reaching the end of list it loops back.
playSong function:
public void playSong()
{
song = Uri.parse("android.resource://" + getPackageName() + "/" + al.get(song_no).id());
try
{
mp.stop();
mp.reset();
mp.release();
mp = null;
}
catch(Exception e)
{
Log.d("playSong", e.toString();
}
mp = MediaPlayer.create(getApplicationContext(), song);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
I tried removing mp.reset(), mp.release() and mp = null but it still played the next song only once.
It looks like you want a Queue data structure, hopefully is gonna be easier to handle than keeping track of indexes.
Your al variable would store a queue of songs to play, in your onCompletion method you can call a playNextSong() method that handles the queue using poll() or remove() to get the next song and play until the queue is empty.
If you want to keep your ArrayList, Try debugging your song_no and song variables to narrow down if the problem is in the song order logic or the MediaPlayer usage.

How do I make a button click play music and the same button click restart the music

I want to create a button in which a click causes the Media player to start and play music, and another click on the same button (While the music is playing) to restart the music. I am a complete beginner in java and android, so please explain each step.
Ofcourse this can be done, you have to maintain states for your clicks.
So add conditions ,
On Click -:
if(mediaPlayer Not Running)--> Start Media Player
if(mediaPlayer Running)--> Restart The media Player.
So you have to play with these conditions.
use below code for puase and start music on same button click:
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// check for already playing
if(mp.isPlaying()){
if(mp!=null){
mp.pause(); //mp.stop(); for stop music
// Changing button image to play button
btnPlay.setImageResource(R.drawable.btn_play);
}
}else{
// Resume song
if(mp!=null){
mp.setDataSource("/sdcard/Music/maine.mp3");//Write your location here
mp.prepare();
mp.start();
// Changing button image to pause button
btnPlay.setImageResource(R.drawable.btn_pause);
}
}
}
});

Mediaplayer gap before playing another

I have a few media players setup to play one after another on a button click however there is a noticeable gap between the media players playing ie. once mediaplayer one has finished there is a half a second before mediaplayer two plays, for the purpose I'm using the mediaplayers for the gap in audio is very noticeable, so what I'm asking is, is there a way to remove this gap. Now I don't know if I'm going wrong using different mediaplayers each time however this is what I've come up with so far.
Basically I've got onCompleteionListeners for each mediaplayer and within those I have the next mediaplayer play until the last. Any pointers would be appreciated.
public void onClick(View v) {
mpButtonThree = MediaPlayer.create(MainActivity.this, R.raw.audioReplay);
if (mpButtonThree==null){
//display a Toast message here
return;
}
mpButtonThree.start();
mpButtonThree.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mpButtonThree) {
mpButtonThree.release();
mpButtonOne = MediaPlayer.create(MainActivity.this, audioReplayPrimary);
if (mpButtonOne==null){
//display a Toast message here
return;
}
mpButtonOne.start();
mpButtonOne.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mpButtonOne) {
mpButtonOne.release();
mpButtonTwo = MediaPlayer.create(MainActivity.this, audioReplaySecondary);
if (mpButtonTwo==null){
//display a Toast message here
return;
}
mpButtonTwo.start();
mpButtonTwo.setOnCompletionListener(new soundListener1()
{
});
}
If You play files in series you can use single media player object.
create function that plays next media file and put it into OnCompletion.
This should remove gap between playing, because You don't have to release and create media player every time

Replaying the sound as many times as button is clicked

I have the following code:
if (someId.matches("A") || someId.matches("a")) {
tvLetCap.setText("A");
tvLetLow.setText("a");
ivLetterIcon.setImageResource(R.drawable.apple);
btnDisplayWord.setText("A is for APPLE");
mpSound = MediaPlayer.create(this, R.raw.sound);
mpSound.setLooping(false);
btnPlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
/*try {
Uri uri = Uri.parse("android.resource://com.mypack.testing/" + R.raw.sound);
mpSound.setDataSource(getApplicationContext(),uri);
mpSound.prepare();
*/
mpSound.start();
btnPlay.setVisibility(View.GONE);
btnStop.setVisibility(View.VISIBLE);
btnStop.setOnClickListener(stopSound);
/*}
catch (IOException e){
Log.e("REPLAYING", "prepare() failed");
}*/
}
});
mpSound.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mpSound.release();
btnPlay.setVisibility(View.VISIBLE);
btnStop.setVisibility(View.GONE);
}
});
}
It plays fine with the codes commented out but whenever I try to replay the file my app FC. The sound file is located in res/raw/sound.mp3
How can I modify the code so it plays as many times as the btnPlay is pressed.
You've released the media player. If you want to reuse it, don't do that.
There are some methods for mediaplayer...
http://developer.android.com/reference/android/media/MediaPlayer.html
Maybe you need to use mpSound.reset() in onClick method for button (some time ago i had such mistake :p)? :)

Play and stop MediaPlayer in Android

Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
MediaPlayer mp = MediaPlayer.create(main.this, R.raw.lastmohican);
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (mp.isPlaying()) {
mp.stop();
} else {
mp.start();
}
}
}
I can play this music by one click and with another click music is stopped, but when I click together music does not start. Any idea why?
I'm not sure I understand your problem, but if you are wondering why the audio will not start back up after you press the button a third time, it is because you are calling stop() on the media player when you should be calling pause(). Stop requires you to prepare the media again before you can begin playback. Have a look at the MediaPlayer Documentation. If that is not your problem you need to provide a better description.
Its solved you should change code for this type
if (mp.isPlaying()) {
mp.stop();
mp.prepareAsync();
mp.seekTo(0);
} else {
mp.start();
}

Categories

Resources