声音溢出?

问题描述 投票:0回答:1

我有一个活动,点击一个按钮随机选择一个单词并播放它的声音。它来自一个单词列表,以及“res”部分中相应的“原始”声音子文件夹。它适用于六十或七十次点击,但它不再播放声音 - 虽然它不会崩溃。这是“声音溢出”的问题吗?也许我没有妥善管理媒体播放器?这是相关的代码:

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);
}
android audio-player
1个回答
1
投票

从代码看,每次单击按钮时,您都会创建一个新的MediaPlayer实例。而是在声音完成后释放媒体播放器,并在下次单击按钮时重新创建它。更好的是,尝试创建一个媒体播放器单例,这样你只有一个媒体播放器实例。

查看这篇文章here

© www.soinside.com 2019 - 2024. All rights reserved.