如何在android中循环声音

时间:2011-06-26 02:33:55

标签: java android audio

按下按钮时,首先声音有效。然后再次按下该按钮它将停止并且第二个声音激活我的代码是否正常?

package com.Randomsentence;
    import java.util.Random;
    import android.app.Activity;
    import android.content.res.Resources;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;

    public class Randomsentence extends Activity {
      boolean showRandom = false;
      TextView txt;
      int time = 30;
      int random;
      public String[] myString;
      Button bt1;
      boolean check = false;

      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        txt=(TextView)findViewById(R.id.txt);
        bt1 = (Button)findViewById(R.id.bt1);
        Medaiplayer mp = new Medaiplayer();
        Mediaplayer mp2 = new Mediaplayer();
        bt1.setOnClickListener(new View.OnClickListener() {

          @Override
      public void onClick(View v) {
        // TODO Auto-generated method stub
        showRandom = !showRandom;
                t = new Thread() {
                    public void run() {
                        try {
                            while(showRandom){
         mp = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile1); 
         mp.setLooping(true);
         mp.start();
                mp2.reset();
                mp2.prepare();
                sleep(1000);
                handler.sendMessage(handler.obtainMessage());
                            }
                mp.reset();
                mp.prepare();
            mp2 = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile2);      
            mp2.setLooping(true);   
            mp2.start();

                }catch(Exception ex){
                    ex.printStackTrace();
                }
                    }
                };
                t.start();

                }

        });

  }

      // our handler
      Handler handler = new Handler() {
        public void handleMessage(Message msg) {//display each item in a single line
          {

              Random rgenerator = new Random();
              Resources res = getResources();
              myString = res.getStringArray(R.array.myArray);
              String q = myString[rgenerator.nextInt(myString.length)];
              txt.setText(q);

          }
        }
      };
    }

2 个答案:

答案 0 :(得分:21)

添加以下行:

mp.setLooping(true);

如果要停止循环,请设置为false。

答案 1 :(得分:1)

您的代码有几处错误。错别字,案件,

例如:Medaiplayer应该是MediaPlayer

仅此一项就足以导致错误。另外,在方法之外声明变量是一个好主意。