声音应该只播放一次但是播放两次

时间:2017-01-02 07:59:23

标签: java android

我正在使用闪存卡构建应用程序。当您单击“下一步”按钮时,它会播放声音(卡的名称),如果您单击该卡,它也会播放相同的声音。唯一的事情就是当我点击“下一步”按钮时,它会同时播放两次声音,使其发出机器人声音。我假设我正在两次意外地发出声音,但我不知道在哪里或如何解决它。我一直在寻找这个地方,但找不到办法来解决这个问题 这是我的代码:

 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  

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

哇,哇。我想到了。这整个时间我认为这完全是声音本身的一个问题,但事实证明问题出在这里:

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

我打电话给changeNumber(screennumber); btnnext.setEnabled(true); 两次。愚蠢的错误。无论如何,谢谢你的帮助!