使用Jlayer和AudioTrack实现在线流媒体边下边播功能
生活随笔
收集整理的這篇文章主要介紹了
使用Jlayer和AudioTrack实现在线流媒体边下边播功能
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
jlayer:mp3解碼庫
http://www.javazoom.net/javalayer/javalayer.html
思路:通過http得到在線音頻文件的輸入流,將未解碼的音頻流使用jlayer進行解碼操作,保存解碼后的音頻數據到隊列中,通過另一線程讀取解碼后的音頻數據,從而邊下邊播的功能
/*** 解碼操作*/ private class DecodeThread extends Thread {private InputStream inputStream = null;private URL url = null;private int sampleRate;private int channel;public DecodeThread(URL url, int sampleRate, int channel) {this.url = url;this.sampleRate = sampleRate;this.channel = channel;}@Overridepublic void run() {try {ByteArrayOutputStream outStream = new ByteArrayOutputStream(8 * 1024);HttpURLConnection conn = (HttpURLConnection) url.openConnection();inputStream = new BufferedInputStream(conn.getInputStream(), 8 * 1024);Bitstream bitstream = new Bitstream(inputStream);Decoder decoder = new Decoder();boolean done = false;SampleBuffer output;int frameIndex = 0;while (!done) {Header frameHeader = bitstream.readFrame();if (frameHeader == null) {done = true;} else {output = (SampleBuffer) decoder.decodeFrame(frameHeader, bitstream);short[] pcm = output.getBuffer();byte[] frameData = new byte[pcm.length];for (int i = 0; i < pcm.length / 2; i++) {int j = i * 2;frameData[j] = (byte) (pcm[i] & 0xff);frameData[j + 1] = (byte) ((pcm[i] >> 8) & 0xff);}audioFrame.add(frameData);frameIndex++;}bitstream.closeFrame();}//TODO 緩存音頻數據outStream.close();} catch (IOException e) {e.printStackTrace();} catch (BitstreamException e) {e.printStackTrace();} catch (DecoderException e) {e.printStackTrace();}}} /*** 播放*/ private class PlayThread extends Thread {@Overridepublic void run() {mAudioTrack.play();int tempFrameIndex = 0;while (!isEnd) {if (!isPausing) {handler.sendEmptyMessage(SimplePlayerHelper.STATE_PLAY);try {Thread.sleep(50);} catch (InterruptedException e) {e.printStackTrace();}List<byte[]> tempFrame = new ArrayList<byte[]>();synchronized (audioFrame) {tempFrame.addAll(audioFrame.subList(tempFrameIndex, tempFrameIndex > audioFrame.size() - 40 ? audioFrame.size() : tempFrameIndex + 40));}if (tempFrameIndex > 0 && tempFrame.isEmpty()) {handler.sendEmptyMessage(SimplePlayerHelper.STATE_END);isEnd = true;onCompletionListener.onCompletion(mMyAudioTrack);}for (int i = 0; i < tempFrame.size(); i++) {mAudioTrack.write(tempFrame.get(i), 0, tempFrame.get(i).length);}tempFrameIndex += tempFrame.size();}}audioFrame.clear();mAudioTrack.stop();}}僅支持MP3流的在線播放功能,可使用其他音頻解碼庫實現多種音頻編碼格式的在線播放功能
總結
以上是生活随笔為你收集整理的使用Jlayer和AudioTrack实现在线流媒体边下边播功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 采访了 10 位身价过亿的 CEO,我终
- 下一篇: 无法访问网址的最基本原因分析,让你永远无