2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.systemui.media;
19 import android.content.Context;
20 import android.media.AudioManager;
21 import android.media.MediaPlayer;
22 import android.media.MediaPlayer.OnCompletionListener;
23 import android.net.Uri;
24 import android.os.Handler;
25 import android.os.Looper;
26 import android.os.Message;
27 import android.os.PowerManager;
28 import android.os.SystemClock;
29 import android.util.Log;
31 import java.io.IOException;
32 import java.lang.IllegalStateException;
33 import java.lang.Thread;
34 import java.util.LinkedList;
38 * This class is provides the same interface and functionality as android.media.AsyncPlayer
39 * with the following differences:
40 * - whenever audio is played, audio focus is requested,
41 * - whenever audio playback is stopped or the playback completed, audio focus is abandoned.
43 public class NotificationPlayer implements OnCompletionListener {
44 private static final int PLAY = 1;
45 private static final int STOP = 2;
46 private static final boolean mDebug = false;
48 private static final class Command {
56 public String toString() {
57 return "{ code=" + code + " looping=" + looping + " stream=" + stream
58 + " uri=" + uri + " }";
62 private LinkedList<Command> mCmdQueue = new LinkedList();
64 private Looper mLooper;
67 * Besides the use of audio focus, the only implementation difference between AsyncPlayer and
68 * NotificationPlayer resides in the creation of the MediaPlayer. For the completion callback,
69 * OnCompletionListener, to be called at the end of the playback, the MediaPlayer needs to
70 * be created with a looper running so its event handler is not null.
72 private final class CreationAndCompletionThread extends Thread {
74 public CreationAndCompletionThread(Command cmd) {
81 mLooper = Looper.myLooper();
83 AudioManager audioManager =
84 (AudioManager) mCmd.context.getSystemService(Context.AUDIO_SERVICE);
86 MediaPlayer player = new MediaPlayer();
87 player.setAudioStreamType(mCmd.stream);
88 player.setDataSource(mCmd.context, mCmd.uri);
89 player.setLooping(mCmd.looping);
91 if ((mCmd.uri != null) && (mCmd.uri.getEncodedPath() != null)
92 && (mCmd.uri.getEncodedPath().length() > 0)) {
93 if (!audioManager.isMusicActiveRemotely()) {
95 audioManager.requestAudioFocus(null, mCmd.stream,
96 AudioManager.AUDIOFOCUS_GAIN);
98 audioManager.requestAudioFocus(null, mCmd.stream,
99 AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
103 player.setOnCompletionListener(NotificationPlayer.this);
105 if (mPlayer != null) {
110 catch (Exception e) {
111 Log.w(mTag, "error loading sound for " + mCmd.uri, e);
113 mAudioManager = audioManager;
120 private void startSound(Command cmd) {
121 // Preparing can be slow, so if there is something else
122 // is playing, let it continue until we're done, so there
123 // is less of a glitch.
125 if (mDebug) Log.d(mTag, "Starting playback");
126 //-----------------------------------
127 // This is were we deviate from the AsyncPlayer implementation and create the
128 // MediaPlayer in a new thread with which we're synchronized
129 synchronized(mCompletionHandlingLock) {
130 // if another sound was already playing, it doesn't matter we won't get notified
131 // of the completion, since only the completion notification of the last sound
134 && (mLooper.getThread().getState() != Thread.State.TERMINATED)) {
137 mCompletionThread = new CreationAndCompletionThread(cmd);
138 synchronized(mCompletionThread) {
139 mCompletionThread.start();
140 mCompletionThread.wait();
143 //-----------------------------------
145 long delay = SystemClock.uptimeMillis() - cmd.requestTime;
147 Log.w(mTag, "Notification sound delayed by " + delay + "msecs");
150 catch (Exception e) {
151 Log.w(mTag, "error loading sound for " + cmd.uri, e);
155 private final class CmdThread extends java.lang.Thread {
157 super("NotificationPlayer-" + mTag);
164 synchronized (mCmdQueue) {
165 if (mDebug) Log.d(mTag, "RemoveFirst");
166 cmd = mCmdQueue.removeFirst();
171 if (mDebug) Log.d(mTag, "PLAY");
175 if (mDebug) Log.d(mTag, "STOP");
176 if (mPlayer != null) {
177 long delay = SystemClock.uptimeMillis() - cmd.requestTime;
179 Log.w(mTag, "Notification stop delayed by " + delay + "msecs");
184 mAudioManager.abandonAudioFocus(null);
185 mAudioManager = null;
187 && (mLooper.getThread().getState() != Thread.State.TERMINATED)) {
191 Log.w(mTag, "STOP command without a player");
196 synchronized (mCmdQueue) {
197 if (mCmdQueue.size() == 0) {
198 // nothing left to do, quit
199 // doing this check after we're done prevents the case where they
200 // added it during the operation from spawning two threads and
201 // trying to do them in parallel.
211 public void onCompletion(MediaPlayer mp) {
212 if (mAudioManager != null) {
213 mAudioManager.abandonAudioFocus(null);
215 // if there are no more sounds to play, end the Looper to listen for media completion
216 synchronized (mCmdQueue) {
217 if (mCmdQueue.size() == 0) {
218 synchronized(mCompletionHandlingLock) {
219 if(mLooper != null) {
222 mCompletionThread = null;
229 private CmdThread mThread;
230 private CreationAndCompletionThread mCompletionThread;
231 private final Object mCompletionHandlingLock = new Object();
232 private MediaPlayer mPlayer;
233 private PowerManager.WakeLock mWakeLock;
234 private AudioManager mAudioManager;
236 // The current state according to the caller. Reality lags behind
237 // because of the asynchronous nature of this class.
238 private int mState = STOP;
241 * Construct a NotificationPlayer object.
243 * @param tag a string to use for debugging
245 public NotificationPlayer(String tag) {
249 mTag = "NotificationPlayer";
254 * Start playing the sound. It will actually start playing at some
255 * point in the future. There are no guarantees about latency here.
256 * Calling this before another audio file is done playing will stop
257 * that one and start the new one.
259 * @param context Your application's context.
260 * @param uri The URI to play. (see {@link MediaPlayer#setDataSource(Context, Uri)})
261 * @param looping Whether the audio should loop forever.
262 * (see {@link MediaPlayer#setLooping(boolean)})
263 * @param stream the AudioStream to use.
264 * (see {@link MediaPlayer#setAudioStreamType(int)})
266 public void play(Context context, Uri uri, boolean looping, int stream) {
267 Command cmd = new Command();
268 cmd.requestTime = SystemClock.uptimeMillis();
270 cmd.context = context;
272 cmd.looping = looping;
274 synchronized (mCmdQueue) {
281 * Stop a previously played sound. It can't be played again or unpaused
282 * at this point. Calling this multiple times has no ill effects.
285 synchronized (mCmdQueue) {
286 // This check allows stop to be called multiple times without starting
287 // a thread that ends up doing nothing.
288 if (mState != STOP) {
289 Command cmd = new Command();
290 cmd.requestTime = SystemClock.uptimeMillis();
298 private void enqueueLocked(Command cmd) {
300 if (mThread == null) {
302 mThread = new CmdThread();
308 * We want to hold a wake lock while we do the prepare and play. The stop probably is
309 * optional, but it won't hurt to have it too. The problem is that if you start a sound
310 * while you're holding a wake lock (e.g. an alarm starting a notification), you want the
311 * sound to play, but if the CPU turns off before mThread gets to work, it won't. The
312 * simplest way to deal with this is to make it so there is a wake lock held while the
313 * thread is starting or running. You're going to need the WAKE_LOCK permission if you're
314 * going to call this.
316 * This must be called before the first time play is called.
320 public void setUsesWakeLock(Context context) {
321 if (mWakeLock != null || mThread != null) {
322 // if either of these has happened, we've already played something.
323 // and our releases will be out of sync.
324 throw new RuntimeException("assertion failed mWakeLock=" + mWakeLock
325 + " mThread=" + mThread);
327 PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
328 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, mTag);
331 private void acquireWakeLock() {
332 if (mWakeLock != null) {
337 private void releaseWakeLock() {
338 if (mWakeLock != null) {