Android的AudioTrack类可以播放pcm或wav格式的语音文件,小编使用AudioTrack制作了一个小功能,包含了播放,暂停,关闭这三个按钮,如果你想使用AudioTrack播放pcm等语音格式的文件,就可以直接将小编的方法复制过去使用了,代码如下:
public class AudioPlayer{ private String audioUrl; private AudioTrack audioTrack; private int bufferSize; private Thread playVoiceThread = null; private boolean isPause; public AudioPlayer(String audioUrl) { this.audioUrl = audioUrl; initAudioPlayer(); } //初始化 private void initAudioPlayer() { bufferSize = audioTrack.getMinBufferSize(16000, AudioFormat.CHANNEL_OUT_MONO,AudioFormat.ENCODING_PCM_16BIT); audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,16000,AudioFormat.CHANNEL_OUT_MONO,AudioFormat.ENCODING_PCM_16BIT,bufferSize,AudioTrack.MODE_STREAM); } //开始播放 public void startPlay(){ //首次点击播放才会进来,如果多次点击播放,则做任何事情 if(playVoiceThread == null){ playVoiceThread = new Thread(new Runnable() { @Override public void run() { try { FileInputStream inputStream = new FileInputStream(new File(audioUrl)); byte[] buffer = new byte[bufferSize]; int readCount = 0; while (inputStream.available() > 0){ if(isPause){ continue; } readCount = inputStream.read(buffer,0,buffer.length); if(readCount > 0){ audioTrack.write(buffer,0,readCount); audioTrack.play(); } } //播放完自动停止 stopPlay(); } catch (Exception e) { e.printStackTrace(); } } }); playVoiceThread.start(); }else{ //暂停之后再点播放,则直接继续之前的进度播放 isPause = false; } } //停止播放 public void stopPlay(){ if(playVoiceThread != null){ playVoiceThread.interrupt(); playVoiceThread = null; } if(audioTrack != null){ audioTrack.stop(); audioTrack.release(); audioTrack = null; } } //暂停播放 public void pausePlay(){ //播放线程启动了才允许暂停 if(playVoiceThread != null){ isPause = true; audioTrack.pause(); } } }
我们只需要在初始化自定义的AudioPlayer类的时候,传入pcm或wav格式的语音文件的路径即可,代码如下:
AudioPlayer audioPlayer = new AudioPlayer("d://music/xxxx.pcm");
然后直接调用AudioPlayer类的开始录音,暂停录音,关闭录音方法即可,代码如下:
//开始 audioPlayer.startPlay(); //暂停 audioPlayer.pausePlay(); //关闭 audioPlayer.stopPlay();
上面小编对Android AudioTrack类封装得代码,是可以直接复制使用的,而你只需要对应修改一下“16000”, “AudioFormat.CHANNEL_OUT_MONO”,“AudioFormat.ENCODING_PCM_16BIT”这三个参数即可(因为不同的机器可能有不同的比特率等参数)。
小编项目的效果如图所示(很丑不好意思):