Android流媒體播放器

來源:互聯網
上載者:User

        今天比較開心,看到論壇上很多人都在詢問如何寫網路流媒體播放器?是否需要兩個播放器輪流交替?因為Android沒有提供像J2me那樣的流建立的形式,總之還是不太好寫,最近也在研究android流媒體播放,這裡提供一個很早之前寫的demo,以供大家相互學習和參考。 

 

/**<br /> * Android提供的介面仍然是不能直接通過流建立Player,但是Android提供了很全面的檔案系統介面,現在用一種新的方法來解決: <br><br /> * <1>,把下載下來的資料先寫到臨時的檔案中 <br><br /> * <2>,用臨時檔案建立Player<br><br /> * todo: <br><br /> * <1>,清理沒有用的臨時檔案。<br><br /> * <2>,暫停邏輯的最佳化。---拋出異常。。。。<br><br /> * <3>,分段下載的邏輯處理,這和<2>有關係。<br><br /> * <4>,整體最佳化<br /> *<br /> * @author shenrenkui<br /> *<br /> */<br />public class AudioPlayer implements OnErrorListener, OnBufferingUpdateListener,<br /> MediaPlayer.OnCompletionListener {<br /> private static final String TAG = "AudioPlayer";<br /> private MediaPlayer mPlayer;<br /> private String current;<br /> private static final int MIN_BUFF = 100 * 1024;<br /> private int totalKbRead = 0;<br /> private Handler handler = new Handler();<br /> private File DLTempFile;<br /> private File BUFFTempFile;<br /> private final String TEMP_DOWNLOAD_FILE_NAME = "tempMediaData";<br /> private final String TEMP_BUFF_FILE_NAME = "tempBufferData";<br /> private final String FILE_POSTFIX = ".dat";<br /> private final int PER_READ = 1024;<br /> private boolean pause;<br /> private boolean stop;<br /> private final int UNKNOWN_LENGTH = -1;<br /> private Handler mHandler = null;</p><p> public void setHandler(Handler handler) {<br /> mHandler = handler;<br /> }</p><p> public void play(final String path) {<br /> downloadOver = false;<br /> totalKbRead = 0;<br /> try {<br /> Log.v(TAG, "playing: " + path);<br /> if (path.equals(current) && mPlayer != null) {<br /> mPlayer.start();<br /> return;<br /> }<br /> current = path;<br /> mPlayer = null;<br /> new PlayThread(current).start();<br /> } catch (Exception e) {</p><p> }<br /> }</p><p> private void setListener() {<br /> if (mPlayer != null) {<br /> mPlayer.setOnErrorListener(this);<br /> mPlayer.setOnBufferingUpdateListener(this);<br /> mPlayer.setOnCompletionListener(this);<br /> }<br /> }</p><p> /**<br /> * 下載資料,分段下載<br /> * todo:連網方式和分段<br /> * @param mediaUrl<br /> * @param start<br /> * @param end<br /> */<br /> private void playFromNet(String mediaUrl, int start, int end) {<br /> URLConnection cn = null;<br /> FileOutputStream out = null;<br /> InputStream is = null;<br /> try {<br /> cn = new URL(mediaUrl).openConnection();<br /> cn.connect();<br /> is = cn.getInputStream();<br /> int mediaLength = cn.getContentLength();<br /> if (is == null) {<br /> return;<br /> }<br /> deleteTempFile(true);<br /> DLTempFile = File.createTempFile(TEMP_DOWNLOAD_FILE_NAME,<br /> FILE_POSTFIX);<br /> out = new FileOutputStream(DLTempFile);<br /> byte buf[] = new byte[PER_READ];<br /> int readLength = 0;<br /> while (readLength != -1 && !stop) {<br /> if (pause) {<br /> try {<br /> Thread.sleep(1000);<br /> } catch (InterruptedException e) {<br /> e.printStackTrace();<br /> }<br /> continue;<br /> }<br /> readLength = is.read(buf);<br /> if (readLength > 0) {<br /> try {<br /> out.write(buf, 0, readLength);<br /> totalKbRead += readLength;<br /> } catch (Exception e) {<br /> Log.e(TAG, e.toString());<br /> }<br /> }<br /> dealWithBufferData();<br /> }<br /> if (totalKbRead == mediaLength) {<br /> downloadOver = true;<br /> dealWithLastData();<br /> // 刪除臨時檔案<br /> if (DLTempFile != null && DLTempFile.exists()) {<br /> DLTempFile.delete();<br /> }<br /> }<br /> } catch (MalformedURLException e) {<br /> Log.e(TAG, e.toString());<br /> } catch (IOException e) {<br /> Log.e(TAG, e.toString());<br /> } finally {<br /> if (out != null) {<br /> try {<br /> out.close();<br /> } catch (IOException e) {<br /> e.printStackTrace();<br /> }<br /> }<br /> if (is != null) {<br /> try {<br /> is.close();<br /> } catch (IOException e) {<br /> e.printStackTrace();<br /> }<br /> }<br /> }<br /> }</p><p> private boolean downloadOver = false;<br /> private boolean wasPlayed = false;</p><p> private void dealWithBufferData() {<br /> if (mPlayer == null || !wasPlayed) {<br /> if (totalKbRead >= MIN_BUFF) {<br /> try {<br /> startMediaPlayer();<br /> } catch (Exception e) {<br /> }<br /> }<br /> } else if (mPlayer.getDuration() - mPlayer.getCurrentPosition() <= 1000) {<br /> deleteTempFile(true);<br /> transferBufferToMediaPlayer();<br /> }<br /> }</p><p> private void startMediaPlayer() {<br /> try {<br /> deleteTempFile(true);<br /> BUFFTempFile = File.createTempFile(TEMP_BUFF_FILE_NAME,<br /> FILE_POSTFIX);<br /> FileSystemUtil.copyFile(DLTempFile, BUFFTempFile);<br /> mPlayer = new MediaPlayer();<br /> setListener();<br /> mPlayer.setDataSource(BUFFTempFile.getAbsolutePath());<br /> mPlayer.prepare();<br /> mPlayer.start();<br /> wasPlayed = true;<br /> } catch (IOException e) {</p><p> }<br /> }</p><p> private void transferBufferToMediaPlayer() {<br /> try {<br /> boolean wasPlaying = mPlayer.isPlaying();<br /> int curPosition = mPlayer.getCurrentPosition();<br /> mPlayer.pause();<br /> BUFFTempFile = File.createTempFile(TEMP_BUFF_FILE_NAME,<br /> FILE_POSTFIX);<br /> FileSystemUtil.copyFile(DLTempFile, BUFFTempFile);<br /> mPlayer = new MediaPlayer();<br /> mPlayer.setDataSource(BUFFTempFile.getAbsolutePath());<br /> mPlayer.prepare();<br /> mPlayer.seekTo(curPosition);<br /> boolean atEndOfFile = mPlayer.getDuration()<br /> - mPlayer.getCurrentPosition() <= 1000;<br /> if (wasPlaying || atEndOfFile) {<br /> mPlayer.start();<br /> }<br /> } catch (Exception e) {<br /> }<br /> }</p><p> private void dealWithLastData() {<br /> Runnable updater = new Runnable() {<br /> public void run() {<br /> transferBufferToMediaPlayer();<br /> }<br /> };<br /> handler.post(updater);<br /> }</p><p> public void onCompletion(MediaPlayer mp) {<br /> if (mHandler != null) {<br /> mHandler.sendEmptyMessage(Preferences.MEDIA_ENDED);<br /> }<br /> }</p><p> public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {<br /> if (mediaPlayer != null) {<br /> mediaPlayer.stop();<br /> mediaPlayer.release();<br /> }<br /> if (mHandler != null) {<br /> mHandler.sendEmptyMessage(Preferences.MEDIA_ERROR);<br /> }<br /> return true;<br /> }</p><p> public void onBufferingUpdate(MediaPlayer arg0, int percent) {<br /> Log.d(TAG, "onBufferingUpdate called ---> percent:" + percent);<br /> if (mHandler != null) {<br /> mHandler.sendEmptyMessage(Preferences.EMDIA_BUFF_CHANGE);<br /> }<br /> }</p><p> private class PlayThread extends Thread {<br /> private String url;</p><p> PlayThread(String url) {<br /> this.url = url;<br /> }</p><p> public void run() {<br /> if (!URLUtil.isNetworkUrl(url)) {<br /> mPlayer = new MediaPlayer();<br /> setListener();<br /> try {<br /> // if (url.startsWith("content://")) {<br /> // mPlayer.setDataSource(MediaPlayService.this, Uri<br /> // .parse(url));<br /> // } else {<br /> mPlayer.setDataSource(url);<br /> // }<br /> mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);<br /> setVolume(0f);<br /> mPlayer.prepare();<br /> mPlayer.start();<br /> } catch (IllegalArgumentException e) {<br /> Log.e(TAG, e.toString());<br /> } catch (IllegalStateException e) {<br /> Log.e(TAG, e.toString());<br /> } catch (IOException e) {<br /> Log.e(TAG, e.toString());<br /> }<br /> } else {<br /> playFromNet(url, 0, UNKNOWN_LENGTH);<br /> }<br /> }<br /> }</p><p>} 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.