/** * Plays a series of audio URIs, but does all the hard work on another thread * so that any slowness with preparing or loading doesn't block the calling thread. */public class Mp3OrPcmAsyncPlayer implements IPcmPlayCompleteListener, OnCompletionListener { public static final int PLAY = 1; public static final int STOP = 2; private static final boolean mDebug = true; // 獲得目前狀態 public int getState() { return mState; } // 代表Mp3類型 public static final int TYPE_MP3 = 0x0101; // 代表PCM類型 public static final int TYPE_PCM = 0x0102; private static final class Command { // 每次把播放或者停止請求封裝成一個對象 int code; Context context; String path; int type; boolean looping; int stream; long requestTime; // 這個PcmInfo是代表一個pcm檔案的各種參數的類集合,比如什麼採樣率啊,什麼的 PcmInfo info; public String toString() { return "{ code=" + code + " looping=" + looping + " stream=" + stream + " path=" + path + " }"; } } private final LinkedList<Command> mCmdQueue = new LinkedList(); private void startSound(final Command cmd) { // Preparing can be slow, so if there is something else // is playing, let it continue until we're done, so there // is less of a glitch. try { // 播放mp3類型檔案if (cmd.type == TYPE_MP3) {if (mDebug)Log.d(mTag, "Starting playback mp3 : " + cmd.path);MediaPlayer player = new MediaPlayer();player.setOnCompletionListener(PGAsyncPlayer.this);//player.setAudioStreamType(cmd.stream);player.setDataSource(cmd.path);//player.setLooping(cmd.looping);player.prepare();player.start();if (mPlayer != null) {mPlayer.release();}mPlayer = player;long delay = SystemClock.uptimeMillis() - cmd.requestTime;if (delay > 1000) {Log.w(mTag, "Notification sound delayed by " + delay + "msecs");}// 播放PCM類型檔案} else if (cmd.type == TYPE_PCM) {if (mDebug)Log.d(mTag, "Starting playback pcm : " + cmd.path);Thread pcm = new Thread() {@Overridepublic void run(){try {playPcmFile(cmd.path, cmd.info.getSampleRate(),cmd.info.getChannel(), cmd.info.getAudioFormat(), PGAsyncPlayer.this);} catch (InitializeException e) {e.printStackTrace();}}};pcm.start();} else {} } catch (Exception e) { Log.w(mTag, "error loading sound for " + cmd.path, e); } } private final class CmdQueueThread extends java.lang.Thread { CmdQueueThread() { super("AsyncPlayer-" + mTag); } public void run() { while (true) { Command cmd = null; synchronized (mCmdQueue) { if (mDebug) Log.d(mTag, "RemoveFirst"); // 取出第一個cmd來執行 cmd = mCmdQueue.removeFirst(); } switch (cmd.code) { case PLAY: if (mDebug) Log.d(mTag, "PLAY"); startSound(cmd); break; case STOP: if (mDebug) Log.d(mTag, "STOP");if (mPlayer != null) {long delay = SystemClock.uptimeMillis() - cmd.requestTime;if (delay > 1000) {Log.w(mTag, "Notification stop delayed by " + delay + "msecs");}mPlayer.stop();mPlayer.release();mPlayer = null;} else {Log.w(mTag, "STOP command without a player");}stopPlayPcmFile(); break; } synchronized (mCmdQueue) { if (mCmdQueue.size() == 0) { // nothing left to do, quit // doing this check after we're done prevents the case where they // added it during the operation from spawning two threads and // trying to do them in parallel. mThread = null; return; } } } } } private String mTag; private CmdQueueThread mThread; private MediaPlayer mPlayer; // The current state according to the caller. Reality lags behind // because of the asynchronous nature of this class. private int mState = STOP; /** * Construct an AsyncPlayer object. * * @param tag a string to use for debugging */ public PGAsyncPlayer(String tag) { if (tag != null) { mTag = tag; } else { mTag = "AsyncPlayer"; } } /** * Start playing the sound. It will actually start playing at some * point in the future. There are no guarantees about latency here. * Calling this before another audio file is done playing will stop * that one and start the new one. * * @param context Your application's context. * @param uri The URI to play. (see {@link MediaPlayer#setDataSource(Context, Uri)}) * @param looping Whether the audio should loop forever. * (see {@link MediaPlayer#setLooping(boolean)}) * @param stream the AudioStream to use. * (see {@link MediaPlayer#setAudioStreamType(int)}) */ public void play(Context context, String path, boolean looping, int stream, PcmInfo info) { Command cmd = new Command(); cmd.requestTime = SystemClock.uptimeMillis(); cmd.code = PLAY; cmd.context = context; cmd.path = path; cmd.looping = looping; cmd.stream = stream; // 外界使用的時候,如果info沒有傳如,就說明想播放mp3檔案,反之,想播放pcm檔案 if (info == null) { cmd.type = TYPE_MP3; } else { cmd.type = TYPE_PCM; cmd.info = info; } synchronized (mCmdQueue) { enqueueLocked(cmd); mState = PLAY; } } /** * Stop a previously played sound. It can't be played again or unpaused * at this point. Calling this multiple times has no ill effects. */ public void stop() { synchronized (mCmdQueue) { // This check allows stop to be called multiple times without starting // a thread that ends up doing nothing. Log.w(mTag, "current state : " + mState); if (mState != STOP) { Command cmd = new Command(); cmd.requestTime = SystemClock.uptimeMillis(); cmd.code = STOP; enqueueLocked(cmd); mState = STOP; } } } // 加入一個請求到鏈表 private void enqueueLocked(Command cmd) { mCmdQueue.add(cmd); if (mThread == null) { mThread = new CmdQueueThread(); mThread.start(); } } // 播放完的回調 public static interface OnSoundPlayCompletedListener{void onPlayCompleted();void onPlayError();} private OnSoundPlayCompletedListener mListener; public void setOnPlayCompletedListener(OnSoundPlayCompletedListener listener) {mListener = listener;}@Overridepublic void onPlayPcmAudioComplete() {if (mListener != null) {mListener.onPlayCompleted();}}@Overridepublic void onCompletion(MediaPlayer mp) {if (mListener != null) {mListener.onPlayCompleted();}}// 開啟播放外放public static void enableSpeaker(Activity context) {final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);if (!audioManager.isSpeakerphoneOn()) {audioManager.setMicrophoneMute(false);audioManager.setSpeakerphoneOn(true);// 使用擴音器外放,即使已經插入耳機context.setVolumeControlStream(AudioManager.STREAM_MUSIC);// 控制聲音的大小audioManager.setMode(AudioManager.STREAM_MUSIC);}}/** * 播放pcm檔案資源 * @param pcmFilePath 檔案路徑 * @param sampleRate 採樣率 * @param channel 聲道 * @param audioFormat 格式 * @param listener 回調監聽 * @throws InitializeException */AudioTrack mAudioTrack = null; public void playPcmFile(String pcmFilePath, int sampleRate, int channel, int audioFormat, IPcmPlayCompleteListener listener) throws InitializeException { Log.e("test ","playPcmFile pcmFilePath = " + pcmFilePath + " sampleRate = " + sampleRate + " channel = " + channel + " audioFormat = " + audioFormat); if (TextUtils.isEmpty(pcmFilePath) || !pcmFilePath.endsWith(".pcm")) return; IPcmPlayCompleteListener pcmListener = listener; // 轉換音頻聲道 if (channel == AudioFormat.CHANNEL_IN_MONO) { channel = AudioFormat.CHANNEL_OUT_MONO; } else if (channel == AudioFormat.CHANNEL_IN_STEREO) { channel = AudioFormat.CHANNEL_OUT_STEREO; } // 根據檔案路徑組建檔案 File file = new File(pcmFilePath); FileInputStream in = null; try { in = new FileInputStream(file); } catch (FileNotFoundException e) { Log.e("test","create the file failed when we want to play pcm file !"); e.printStackTrace(); return; } // 獲得滿足條件的最小緩衝區大小 int bufferSizeInBytes = AudioTrack.getMinBufferSize(sampleRate, channel, audioFormat); // 2倍緩衝區 byte[] buffer = new byte[bufferSizeInBytes * 2]; try { // 雖然每次都new出來一個新的AudioTrack對象,比較耗效能,但是為了安全考慮,比如使用者 // 重新開啟錄音功能,假如此時的採樣率22050初始化AudioRecord對象不成功, // 就會改變當前的採樣率。所以錄製的音頻採樣率有可能與前幾次的不一樣,所以我們不能 // 緩衝一個AudioTrack引用來重複使用,這是我的理解 mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, channel, audioFormat, buffer.length, AudioTrack.MODE_STREAM); } catch (IllegalArgumentException e) { throw new InitializeException( "Can't initialize the AudioTrack instance," + "maybe be your parameters not right!"); } // 開始放音,其實此時還在準備等待資料 mAudioTrack.setStereoVolume(1.0f, 1.0f); mAudioTrack.play(); try { while ((in.read(buffer)) != -1) { mAudioTrack.write(buffer, 0, buffer.length); } } catch (Exception e) { Log.e("AudioTrack", "Playback Failed"); } // 播放結束,回調介面方法 if (pcmListener != null) { pcmListener.onPlayPcmAudioComplete(); } // 播放結束,釋放資源 if (mAudioTrack != null) { // 釋放資源 mAudioTrack.release(); mAudioTrack = null; } } /** * 停止播放pcm音頻檔案 */ public void stopPlayPcmFile() { Log.e("test","Stop play pcm !"); if (mAudioTrack == null) return; int state = mAudioTrack.getState(); if (state == AudioTrack.STATE_INITIALIZED) { try { if (mAudioTrack != null) { mAudioTrack.stop(); } } catch (IllegalStateException e) { Log.e("test","AudioTrack.stop() exception and state = " + mAudioTrack.getState()); } } }}