简体   繁体   中英

Sound should only play once but plays twice instead

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); changeNumber(screennumber); btnnext.setEnabled(true);
twice. Silly mistake. Thanks for your help anyway!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM