简体   繁体   中英

Play mp3 file in android from an array

I have an array with 0 and 1 and I am trying to play a mp3 file every time for every "1" in my array and when I have a "0" I want the app to wait a second. I tried this code, it works but the app is blocked when I enter in the loop. There are other ways to do this?

while(j < c.size()){
    if(c.get(j)==1) {
        mediaPlayer.start();
        SystemClock.sleep(1000);
    }
    else SystemClock.sleep(1000);

    j++;
}

With the sleep you are blocking the Main Thread, do it in a different one with an AsyncTask for example as @vilpe89 said. https://developer.android.com/reference/android/os/AsyncTask.html

Try with a AsyncTask, you can play the music in background. in the while, put a boolean connected to button for change the flag an call the method.

pd: sry my bad english xD

public void mAsyncTask() {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                while (--Here put a boolean--) {
                    mediaPlayer.start();
                    try {
                        Thread.sleep(--put here a pause in millisec--);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }
        }.execute();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM