AsyncPlayer.java revision 54b6cfa9a9e5b861a9930af873580d6dc20f773c
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.media;
18
19import android.content.Context;
20import android.net.Uri;
21import android.os.PowerManager;
22import android.util.Log;
23
24import java.io.IOException;
25
26/**
27 * Plays a series of audio URIs, but does all the hard work on another thread
28 * so that any slowness with preparing or loading doesn't block the calling thread.
29 */
30public class AsyncPlayer {
31    private static final int PLAY = 1;
32    private static final int STOP = 2;
33
34    private static final class Command {
35        Command next;
36        int code;
37        Context context;
38        Uri uri;
39        boolean looping;
40        int stream;
41
42        public String toString() {
43            return "{ code=" + code + " looping=" + looping + " stream=" + stream
44                    + " uri=" + uri + " }";
45        }
46    }
47
48    private final class Thread extends java.lang.Thread {
49        Thread() {
50            super("AsyncPlayer-" + mTag);
51        }
52
53        public void run() {
54            while (true) {
55                Command cmd = null;
56
57                synchronized (mLock) {
58                    if (mHead != null) {
59                        cmd = mHead;
60                        mHead = cmd.next;
61                        if (mTail == cmd) {
62                            mTail = null;
63                        }
64                    }
65                }
66
67                switch (cmd.code) {
68                case PLAY:
69                    try {
70                        // Preparing can be slow, so if there is something else
71                        // is playing, let it continue until we're done, so there
72                        // is less of a glitch.
73                        MediaPlayer player = new MediaPlayer();
74                        player.setDataSource(cmd.context, cmd.uri);
75                        player.setAudioStreamType(cmd.stream);
76                        player.setLooping(cmd.looping);
77                        player.prepare();
78                        if (mPlayer != null) {
79                            // stop the previous one.
80                            mPlayer.stop();
81                            mPlayer.release();
82                        }
83                        player.start();
84                        mPlayer = player;
85                    }
86                    catch (IOException e) {
87                        Log.w(mTag, "error loading sound for " + cmd.uri, e);
88                    }
89                    break;
90                case STOP:
91                    if (mPlayer != null) {
92                        mPlayer.stop();
93                        mPlayer.release();
94                        mPlayer = null;
95                    } else {
96                        Log.w(mTag, "STOP command without a player");
97                    }
98                    break;
99                }
100
101                synchronized (mLock) {
102                    if (mHead == null) {
103                        // nothing left to do, quit
104                        // doing this check after we're done prevents the case where they
105                        // added it during the operation from spawning two threads and
106                        // trying to do them in parallel.
107                        mThread = null;
108                        releaseWakeLock();
109                        return;
110                    }
111                }
112            }
113        }
114    }
115
116    private String mTag;
117    private Command mHead;
118    private Command mTail;
119    private Thread mThread;
120    private MediaPlayer mPlayer;
121    private Object mLock = new Object();
122    private PowerManager.WakeLock mWakeLock;
123
124    // The current state according to the caller.  Reality lags behind
125    // because of the asynchronous nature of this class.
126    private int mState = STOP;
127
128    /**
129     * Construct an AsyncPlayer object.
130     *
131     * @param tag a string to use for debugging
132     */
133    public AsyncPlayer(String tag) {
134        if (tag != null) {
135            mTag = tag;
136        } else {
137            mTag = "AsyncPlayer";
138        }
139    }
140
141    /**
142     * Start playing the sound.  It will actually start playing at some
143     * point in the future.  There are no guarantees about latency here.
144     * Calling this before another audio file is done playing will stop
145     * that one and start the new one.
146     *
147     * @param context Your application's context.
148     * @param uri The URI to play.  (see {@link MediaPlayer#setDataSource(Context, Uri)})
149     * @param looping Whether the audio should loop forever.
150     *          (see {@link MediaPlayer#setLooping(boolean)})
151     * @param stream the AudioStream to use.
152     *          (see {@link MediaPlayer#setAudioStreamType(int)})
153     */
154    public void play(Context context, Uri uri, boolean looping, int stream) {
155        Command cmd = new Command();
156        cmd.code = PLAY;
157        cmd.context = context;
158        cmd.uri = uri;
159        cmd.looping = looping;
160        cmd.stream = stream;
161        synchronized (mLock) {
162            enqueueLocked(cmd);
163            mState = PLAY;
164        }
165    }
166
167    /**
168     * Stop a previously played sound.  It can't be played again or unpaused
169     * at this point.  Calling this multiple times has no ill effects.
170     */
171    public void stop() {
172        synchronized (mLock) {
173            // This check allows stop to be called multiple times without starting
174            // a thread that ends up doing nothing.
175            if (mState != STOP) {
176                Command cmd = new Command();
177                cmd.code = STOP;
178                enqueueLocked(cmd);
179                mState = STOP;
180            }
181        }
182    }
183
184    private void enqueueLocked(Command cmd) {
185        if (mTail == null) {
186            mHead = cmd;
187        } else {
188            mTail.next = cmd;
189        }
190        mTail = cmd;
191        if (mThread == null) {
192            acquireWakeLock();
193            mThread = new Thread();
194            mThread.start();
195        }
196    }
197
198    /**
199     * We want to hold a wake lock while we do the prepare and play.  The stop probably is
200     * optional, but it won't hurt to have it too.  The problem is that if you start a sound
201     * while you're holding a wake lock (e.g. an alarm starting a notification), you want the
202     * sound to play, but if the CPU turns off before mThread gets to work, it won't.  The
203     * simplest way to deal with this is to make it so there is a wake lock held while the
204     * thread is starting or running.  You're going to need the WAKE_LOCK permission if you're
205     * going to call this.
206     *
207     * This must be called before the first time play is called.
208     *
209     * @hide
210     */
211    public void setUsesWakeLock(Context context) {
212        if (mWakeLock != null || mThread != null) {
213            // if either of these has happened, we've already played something.
214            // and our releases will be out of sync.
215            throw new RuntimeException("assertion failed mWakeLock=" + mWakeLock
216                    + " mThread=" + mThread);
217        }
218        PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
219        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, mTag);
220    }
221
222    private void acquireWakeLock() {
223        if (mWakeLock != null) {
224            mWakeLock.acquire();
225        }
226    }
227
228    private void releaseWakeLock() {
229        if (mWakeLock != null) {
230            mWakeLock.release();
231        }
232    }
233}
234
235