• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  *
17  * This file has been copied from com.android.server.NotificationPlayer. The only modification is
18  * the addition of a volume parameter. Hopefully the framework will adapt AsyncPlayer to support
19  * all the functionality in this class, at which point this one can be deleted.
20  */
21 
22 package com.android.mms.transaction;
23 
24 import java.util.LinkedList;
25 
26 import android.content.Context;
27 import android.media.AudioManager;
28 import android.media.MediaPlayer;
29 import android.media.MediaPlayer.OnCompletionListener;
30 import android.net.Uri;
31 import android.os.Looper;
32 import android.os.PowerManager;
33 import android.os.SystemClock;
34 import android.util.Log;
35 
36 /**
37  * @hide
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.
42  */
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;
47 
48     private static final class Command {
49         int code;
50         Context context;
51         Uri uri;
52         boolean looping;
53         int stream;
54         float volume;
55         long requestTime;
56 
57         @Override
toString()58         public String toString() {
59             return "{ code=" + code + " looping=" + looping + " stream=" + stream
60                     + " uri=" + uri + " }";
61         }
62     }
63 
64     private LinkedList<Command> mCmdQueue = new LinkedList<Command>();
65 
66     private Looper mLooper;
67 
68     /*
69      * Besides the use of audio focus, the only implementation difference between AsyncPlayer and
70      * NotificationPlayer resides in the creation of the MediaPlayer. For the completion callback,
71      * OnCompletionListener, to be called at the end of the playback, the MediaPlayer needs to
72      * be created with a looper running so its event handler is not null.
73      */
74     private final class CreationAndCompletionThread extends Thread {
75         public Command mCmd;
CreationAndCompletionThread(Command cmd)76         public CreationAndCompletionThread(Command cmd) {
77             super();
78             mCmd = cmd;
79         }
80 
81         @Override
run()82         public void run() {
83             Looper.prepare();
84             mLooper = Looper.myLooper();
85             synchronized(this) {
86                 AudioManager audioManager =
87                     (AudioManager) mCmd.context.getSystemService(Context.AUDIO_SERVICE);
88                 try {
89                     MediaPlayer player = new MediaPlayer();
90                     player.setAudioStreamType(mCmd.stream);
91                     player.setDataSource(mCmd.context, mCmd.uri);
92                     player.setLooping(mCmd.looping);
93                     player.setVolume(mCmd.volume, mCmd.volume);
94                     player.prepare();
95                     if ((mCmd.uri != null) && (mCmd.uri.getEncodedPath() != null)
96                             && (mCmd.uri.getEncodedPath().length() > 0)) {
97                         if (mCmd.looping) {
98                             audioManager.requestAudioFocus(null, mCmd.stream,
99                                     AudioManager.AUDIOFOCUS_GAIN);
100                         } else {
101                             audioManager.requestAudioFocus(null, mCmd.stream,
102                                     AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
103                         }
104                     }
105                     player.setOnCompletionListener(NotificationPlayer.this);
106                     player.start();
107                     if (mPlayer != null) {
108                         mPlayer.release();
109                     }
110                     mPlayer = player;
111                 }
112                 catch (Exception e) {
113                     Log.w(mTag, "error loading sound for " + mCmd.uri, e);
114                 }
115                 mAudioManager = audioManager;
116                 this.notify();
117             }
118             Looper.loop();
119         }
120     }
121 
startSound(Command cmd)122     private void startSound(Command cmd) {
123         // Preparing can be slow, so if there is something else
124         // is playing, let it continue until we're done, so there
125         // is less of a glitch.
126         try {
127             if (mDebug) Log.d(mTag, "Starting playback");
128             //-----------------------------------
129             // This is were we deviate from the AsyncPlayer implementation and create the
130             // MediaPlayer in a new thread with which we're synchronized
131             synchronized(mCompletionHandlingLock) {
132                 // if another sound was already playing, it doesn't matter we won't get notified
133                 // of the completion, since only the completion notification of the last sound
134                 // matters
135                 if((mLooper != null)
136                         && (mLooper.getThread().getState() != Thread.State.TERMINATED)) {
137                     mLooper.quit();
138                 }
139                 mCompletionThread = new CreationAndCompletionThread(cmd);
140                 synchronized(mCompletionThread) {
141                     mCompletionThread.start();
142                     mCompletionThread.wait();
143                 }
144             }
145             //-----------------------------------
146 
147             long delay = SystemClock.uptimeMillis() - cmd.requestTime;
148             if (delay > 1000) {
149                 Log.w(mTag, "Notification sound delayed by " + delay + "msecs");
150             }
151         }
152         catch (Exception e) {
153             Log.w(mTag, "error loading sound for " + cmd.uri, e);
154         }
155     }
156 
157     private final class CmdThread extends java.lang.Thread {
CmdThread()158         CmdThread() {
159             super("NotificationPlayer-" + mTag);
160         }
161 
162         @Override
run()163         public void run() {
164             while (true) {
165                 Command cmd = null;
166 
167                 synchronized (mCmdQueue) {
168                     if (mDebug) Log.d(mTag, "RemoveFirst");
169                     cmd = mCmdQueue.removeFirst();
170                 }
171 
172                 switch (cmd.code) {
173                 case PLAY:
174                     if (mDebug) Log.d(mTag, "PLAY");
175                     startSound(cmd);
176                     break;
177                 case STOP:
178                     if (mDebug) Log.d(mTag, "STOP");
179                     if (mPlayer != null) {
180                         long delay = SystemClock.uptimeMillis() - cmd.requestTime;
181                         if (delay > 1000) {
182                             Log.w(mTag, "Notification stop delayed by " + delay + "msecs");
183                         }
184                         mPlayer.stop();
185                         mPlayer.release();
186                         mPlayer = null;
187                         mAudioManager.abandonAudioFocus(null);
188                         mAudioManager = null;
189                         if((mLooper != null)
190                                 && (mLooper.getThread().getState() != Thread.State.TERMINATED)) {
191                             mLooper.quit();
192                         }
193                     } else {
194                         Log.w(mTag, "STOP command without a player");
195                     }
196                     break;
197                 }
198 
199                 synchronized (mCmdQueue) {
200                     if (mCmdQueue.size() == 0) {
201                         // nothing left to do, quit
202                         // doing this check after we're done prevents the case where they
203                         // added it during the operation from spawning two threads and
204                         // trying to do them in parallel.
205                         mThread = null;
206                         releaseWakeLock();
207                         return;
208                     }
209                 }
210             }
211         }
212     }
213 
214     @Override
onCompletion(MediaPlayer mp)215     public void onCompletion(MediaPlayer mp) {
216         if (mAudioManager != null) {
217             mAudioManager.abandonAudioFocus(null);
218         }
219         // if there are no more sounds to play, end the Looper to listen for media completion
220         synchronized (mCmdQueue) {
221             if (mCmdQueue.size() == 0) {
222                 synchronized(mCompletionHandlingLock) {
223                     if(mLooper != null) {
224                         mLooper.quit();
225                     }
226                     mCompletionThread = null;
227                 }
228             }
229         }
230     }
231 
232     private String mTag;
233     private CmdThread mThread;
234     private CreationAndCompletionThread mCompletionThread;
235     private final Object mCompletionHandlingLock = new Object();
236     private MediaPlayer mPlayer;
237     private PowerManager.WakeLock mWakeLock;
238     private AudioManager mAudioManager;
239 
240     // The current state according to the caller.  Reality lags behind
241     // because of the asynchronous nature of this class.
242     private int mState = STOP;
243 
244     /**
245      * Construct a NotificationPlayer object.
246      *
247      * @param tag a string to use for debugging
248      */
NotificationPlayer(String tag)249     public NotificationPlayer(String tag) {
250         if (tag != null) {
251             mTag = tag;
252         } else {
253             mTag = "NotificationPlayer";
254         }
255     }
256 
257     /**
258      * Start playing the sound.  It will actually start playing at some
259      * point in the future.  There are no guarantees about latency here.
260      * Calling this before another audio file is done playing will stop
261      * that one and start the new one.
262      *
263      * @param context Your application's context.
264      * @param uri The URI to play.  (see {@link MediaPlayer#setDataSource(Context, Uri)})
265      * @param looping Whether the audio should loop forever.
266      *          (see {@link MediaPlayer#setLooping(boolean)})
267      * @param stream the AudioStream to use.
268      *          (see {@link MediaPlayer#setAudioStreamType(int)})
269      * @param volume The volume at which to play this sound, as a fraction of the system volume for
270      *          the relevant stream type. A value of 1 is the maximum and means play at the system
271      *          volume with no attenuation.
272      */
play(Context context, Uri uri, boolean looping, int stream, float volume)273     public void play(Context context, Uri uri, boolean looping, int stream, float volume) {
274         Command cmd = new Command();
275         cmd.requestTime = SystemClock.uptimeMillis();
276         cmd.code = PLAY;
277         cmd.context = context;
278         cmd.uri = uri;
279         cmd.looping = looping;
280         cmd.stream = stream;
281         cmd.volume = volume;
282         synchronized (mCmdQueue) {
283             enqueueLocked(cmd);
284             mState = PLAY;
285         }
286     }
287 
288     /**
289      * Stop a previously played sound.  It can't be played again or unpaused
290      * at this point.  Calling this multiple times has no ill effects.
291      */
stop()292     public void stop() {
293         synchronized (mCmdQueue) {
294             // This check allows stop to be called multiple times without starting
295             // a thread that ends up doing nothing.
296             if (mState != STOP) {
297                 Command cmd = new Command();
298                 cmd.requestTime = SystemClock.uptimeMillis();
299                 cmd.code = STOP;
300                 enqueueLocked(cmd);
301                 mState = STOP;
302             }
303         }
304     }
305 
enqueueLocked(Command cmd)306     private void enqueueLocked(Command cmd) {
307         mCmdQueue.add(cmd);
308         if (mThread == null) {
309             acquireWakeLock();
310             mThread = new CmdThread();
311             mThread.start();
312         }
313     }
314 
315     /**
316      * We want to hold a wake lock while we do the prepare and play.  The stop probably is
317      * optional, but it won't hurt to have it too.  The problem is that if you start a sound
318      * while you're holding a wake lock (e.g. an alarm starting a notification), you want the
319      * sound to play, but if the CPU turns off before mThread gets to work, it won't.  The
320      * simplest way to deal with this is to make it so there is a wake lock held while the
321      * thread is starting or running.  You're going to need the WAKE_LOCK permission if you're
322      * going to call this.
323      *
324      * This must be called before the first time play is called.
325      *
326      * @hide
327      */
setUsesWakeLock(Context context)328     public void setUsesWakeLock(Context context) {
329         if (mWakeLock != null || mThread != null) {
330             // if either of these has happened, we've already played something.
331             // and our releases will be out of sync.
332             throw new RuntimeException("assertion failed mWakeLock=" + mWakeLock
333                     + " mThread=" + mThread);
334         }
335         PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
336         mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, mTag);
337     }
338 
acquireWakeLock()339     private void acquireWakeLock() {
340         if (mWakeLock != null) {
341             mWakeLock.acquire();
342         }
343     }
344 
releaseWakeLock()345     private void releaseWakeLock() {
346         if (mWakeLock != null) {
347             mWakeLock.release();
348         }
349     }
350 }
351 
352