Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop sound in android

When press button first sound active. Then press that button again it will stop and second sound active My code is OK?

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);

          }
        }
      };
    }
like image 335
user814154 Avatar asked Nov 30 '22 04:11

user814154


1 Answers

Add the line:

mp.setLooping(true);

Then set false when you want to stop it looping.

like image 93
Kenny Avatar answered Dec 06 '22 20:12

Kenny