非阻塞式播放pcm和mp3文件类

/**
 * 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() {
					@Override
					public 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;
	}

	@Override
	public void onPlayPcmAudioComplete() {
		if (mListener != null) {
			mListener.onPlayCompleted();
		}
	}

	@Override
	public 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());
            }
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值