Thread and mediaplayer problems, Timer with sound

2019-09-17 15:19发布

问题:

I'm developing an Android application that is based on a timer that every second must play a sound that you selected before.

Here is the problem:

  • No objects can run Media Player in a Thread or a Runnable
  • I can not call methods that reproduce the sound
  • I can not run it on a timer task

Can you think of anything?

Thanks

thread:

public void run(){
while(!detenido) //Bolean for stop the thread {

        try {
            Servicio servicios = new Servicio();
            switch(segundosesperar){ //Int to select the ms to slep
            case 0:
                this.sleep(1500);
                servicios.intento1(); //the metod with " mp.start()"
                dormir = 1500;
                break;
            case 1:
                this.sleep(1600);
                servicios.intento1();
                dormir = 1600;
                break;
            case 2:
                this.sleep(1700);
                servicios.intento1();
                dormir = 1700;
                break;
            case 3:
                this.sleep(1800);
                servicios.intento1();
                dormir = 1800;
                break;
            case 4:
                this.sleep(1900);
                servicios.intento1();
                dormir = 1900;
                break;
            case 5:
                this.sleep(2000);
                servicios.intento1();
                dormir = 2000;
                break;
            default:
                this.sleep(1750);
                servicios.intento1();
                dormir = 1750;
                break;

            }

        } catch (InterruptedException e) {

            e.printStackTrace();
        }
         piedras =piedras+1; //Counter cronometer +1
         cron = piedras+""; 
         //Set the counter in the activity
            handler.setHcron(cron);
            handler.act();


            cronoparaganar = cron;


            if ( piedras == piedrasmodo){
                tocarsirena = true;
            }
          } 
            }

Metod in the service to start a play sound:

public void intento1(){

    mp= MediaPlayer.create(this, R.raw.censura);
    mp.start();

}

回答1:

You can run a MediaPlayer in an extra Service.

Check this out for information about Service.
Also, this link might be useful to handle the MediaPlayer with a Service.

You could then call the functions of your Service to handle the MediaPlayer.