【问题标题】:Sound overflow?声音溢出?
【发布时间】:2015-10-20 03:04:32
【问题描述】:

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

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】:

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

    查看此帖子here

    【讨论】:

    • 我听从了你的建议。我添加了公共静态 MediaPlayer mp;在类的开头,并且在 listen() 方法中,媒体播放器仅使用 mp = MediaPlayer.create(SpellingActivity.this, resRaw); 调用它有效。谢谢。
    猜你喜欢
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    • 2014-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多