简体   繁体   中英

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)? :)

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