Andy
Andy

Reputation: 99

Sound overflow?

I have an activity where clicking a button selects a word at random and plays its sound. It comes from a list of words, and a corresponding "raw" sub folder of sounds, in the "res" part. It works well for sixty or seventy clicks, but then it no longer plays the sounds - although it doesn't crash. Is it a question of "sound overflow"? Perhaps I don't manage properly the mediaplayer mp? Here is the related code:

public String randomWord(){
    boolean OK;
    OK = false;

    while (!OK) {

        Random rand = new Random();

        numeroAuHasard = 5 + rand.nextInt(nombreDeMots-5);
        // nombre aléatoire entre 5 et 175 (si nombreDeMots == 176)

        mysteryWord = listeDesMots.get(numeroAuHasard);

        if ( mysteryWord.charAt(mysteryWord.length() - 1) == '1' ) // je veux que le mot se termine par '1'
        {
            OK = true;
        }

        for (int i = 0; i<mysteryWord.length();i++){
            if(mysteryWord.charAt(i) == '_'){// je veux que le mot ne contienne pas '_'
                OK = false;
            }
        }
    }

    // mysteryWord = "francois1"; // pour test de check "ç"

    return mysteryWord;
}


// bouton qui sélectionne un mot au hasard et le joue
public void listen(){
    final Button boutonGenerique = (Button) findViewById(R.id.listen);
    final TextView monMessage = (TextView) findViewById(R.id.zone_trado_scrollable);
    final TextView maReponse = (TextView) findViewById(R.id.reponse);

    View.OnClickListener monEcouteur = new View.OnClickListener() {
        public void onClick(View v) {

            // remise à zéro des deux champs
            monMessage.setText("");
            maReponse.setText("");

            // sélection d'un mot au hasard
            marcel = randomWord();

            // important de mettre ceci à l'intérieur du listener,
            // car c'est recréé avec une nouvelle ressource chaque fois qu'on clique
            final int resRaw = getResources().getIdentifier(marcel, "raw", getPackageName());
            final MediaPlayer mp = MediaPlayer.create(SpellingActivity.this, resRaw);


            if (marcel == "off1"){
                monMessage.setText(Html.fromHtml("<i>caveat: this is the word with two consonants</i>"));
            }

            // on joue le mot
            mp.start();
        }
    };
    boutonGenerique.setOnClickListener(monEcouteur);
}

Upvotes: 0

Views: 113

Answers (1)

Alok
Alok

Reputation: 163

From the code it looks like you create a new instance of MediaPlayer everytime a button is clicked. Instead release the media player after the sound is completed and recreate it next time when the button is click. Even better, try to create a media player singleton so that you have only one instance of the media player.

Check this post here

Upvotes: 1

Related Questions