Playing BG Music Across Activities in Android

后端 未结 6 880
南方客
南方客 2020-11-27 06:27

Hello! First time to ask a question here at stackoverflow. Exciting! Haha.

We\'re developing an Android game and we play some background music for our intro

6条回答
  •  春和景丽
    2020-11-27 07:03

    If I understand your situation correctly, then I have confronted the same problem a few times. I am using a different thread to play music in my applications. This implementation passes a static reference to a Context that I know will be alive for the time that the music will be playing.

    public class AudioPlayer extends Thread {
    private Context c;
    private Thread blinker;
    private File file;
    
    public AudioPlayer (Context c, File file) {
        this.c = c;
        this.file = file;
    }
    
    public void go () {
        blinker = this;
        if(!blinker.isAlive()) {
            blinker.start();
        }
    }
    
    public void end () {
        Thread waiter = blinker;
        blinker = null;
        if (waiter != null)
            waiter.interrupt ();
    }
    
    public void run () {
        MediaPlayer ap = MediaPlayer.create(c, Uri.fromFile(file));
        int duration = ap.getDuration();
        long startTime = System.currentTimeMillis();
        ap.start();
        try {
            Thread thisThread = Thread.currentThread();
            while (this.blinker == thisThread && System.currentTimeMillis() - startTime < duration) {           
                Thread.sleep (500);  // interval between checks (in ms)
            }
            ap.stop ();
            ap.release ();
            ap = null;
        } catch (InterruptedException e) {
            Log.d("AUDIO-PLAYER", "INTERRUPTED EXCEPTION");
            ap.stop ();
            ap.release();
            ap = null;
        }
        }
    }
    

提交回复
热议问题