這篇文章給大家介紹Android應(yīng)用中怎么實(shí)現(xiàn)一個(gè)視頻點(diǎn)播功能,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
創(chuàng)新互聯(lián)建站于2013年開(kāi)始,是專(zhuān)業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目成都網(wǎng)站制作、成都做網(wǎng)站網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元威遠(yuǎn)做網(wǎng)站,已為上家服務(wù),為威遠(yuǎn)各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:028-86922220
采用了本地代理服務(wù)的方式,通過(guò)原始url給播放器返回一個(gè)本地代理的一個(gè)url ,代理URL類(lèi)似:http://127.0.0.1:57430/xxxx;然后播放器播放的時(shí)候請(qǐng)求到了你本地的代理上了。
優(yōu)化點(diǎn)
1. 文件的緩存超過(guò)限制后沒(méi)有按照l(shuí)ru算法刪除.
Files類(lèi)。
由于在移動(dòng)設(shè)備上file.setLastModified() 方法不支持毫秒級(jí)的時(shí)間處理,導(dǎo)致超出限制大小后本應(yīng)該刪除老的,卻沒(méi)有刪除拋出了異常。注釋掉主動(dòng)拋出的異常即可。因?yàn)槲募男薷臅r(shí)間就是對(duì)的。
static void setLastModifiedNow(File file) throws IOException { if (file.exists()) { long now = System.currentTimeMillis(); boolean modified = file.setLastModified(now/1000*1000); // on some devices (e.g. Nexus 5) doesn't work if (!modified) { modify(file); // if (file.lastModified() < now) { // VideoCacheLog.debug("LruDiskUsage", "modified not ok "); // throw new IOException("Error set last modified date to " + file); // }else{ // VideoCacheLog.debug("LruDiskUsage", "modified ok "); // } } } }
2. 處理返回給播放器的http響應(yīng)頭消息,響應(yīng)頭消息的獲取處理改為head請(qǐng)求(需要服務(wù)器支持)
HttpUrlSource類(lèi)。fetchContentInfo方法是獲取視頻文件的Content-Type,Content-Length信息,是為了播放器播放的時(shí)候給播放器組裝http響應(yīng)頭信息用的。所以這一塊需要用數(shù)據(jù)庫(kù)保存,這樣播放器每次播放的時(shí)候不要在此獲取了,減少了請(qǐng)求的次數(shù),節(jié)省了流量。既然是只需要頭信息,不需要響應(yīng)體,所以我們?cè)讷@取的時(shí)候可以直接采用HEAD方法。所以代碼增加了一個(gè)方法openConnectionForHeader如下:
private void fetchContentInfo() throws ProxyCacheException { VideoCacheLog.debug(TAG,"Read content info from " + sourceInfo.url); HttpURLConnection urlConnection = null; InputStream inputStream = null; try { urlConnection = openConnectionForHeader(20000); long length = getContentLength(urlConnection); String mime = urlConnection.getContentType(); inputStream = urlConnection.getInputStream(); this.sourceInfo = new SourceInfo(sourceInfo.url, length, mime); this.sourceInfoStorage.put(sourceInfo.url, sourceInfo); VideoCacheLog.debug(TAG,"Source info fetched: " + sourceInfo); } catch (IOException e) { VideoCacheLog.error(TAG,"Error fetching info from " + sourceInfo.url ,e); } finally { ProxyCacheUtils.close(inputStream); if (urlConnection != null) { urlConnection.disconnect(); } } } // for HEAD private HttpURLConnection openConnectionForHeader(int timeout) throws IOException, ProxyCacheException { HttpURLConnection connection; boolean redirected; int redirectCount = 0; String url = this.sourceInfo.url; do { VideoCacheLog.debug(TAG, "Open connection for header to " + url); connection = (HttpURLConnection) new URL(url).openConnection(); if (timeout > 0) { connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); } //只返回頭部,不需要BODY,既可以提高響應(yīng)速度也可以減少網(wǎng)絡(luò)流量 connection.setRequestMethod("HEAD"); int code = connection.getResponseCode(); redirected = code == HTTP_MOVED_PERM || code == HTTP_MOVED_TEMP || code == HTTP_SEE_OTHER; if (redirected) { url = connection.getHeaderField("Location"); VideoCacheLog.debug(TAG,"Redirect to:" + url); redirectCount++; connection.disconnect(); VideoCacheLog.debug(TAG,"Redirect closed:" + url); } if (redirectCount > MAX_REDIRECTS) { throw new ProxyCacheException("Too many redirects: " + redirectCount); } } while (redirected); return connection; }
3.替換網(wǎng)絡(luò)庫(kù)為okhttp(因?yàn)榇蟛糠值捻?xiàng)目都是以okhttp為網(wǎng)絡(luò)請(qǐng)求庫(kù)的)
為什么我們要換呢?!一是OKHttp是一款高效的HTTP客戶端,支持連接同一地址的鏈接共享同一個(gè)socket,通過(guò)連接池來(lái)減小響應(yīng)延遲,還有透明的GZIP壓縮,請(qǐng)求緩存等優(yōu)勢(shì),其核心主要有路由、連接協(xié)議、攔截器、代理、安全性認(rèn)證、連接池以及網(wǎng)絡(luò)適配,攔截器主要是指添加,移除或者轉(zhuǎn)換請(qǐng)求或者回應(yīng)的頭部信息。得到了android開(kāi)發(fā)的認(rèn)可。二是大部分的app都是采用OKHttp,而且google會(huì)將其納入android 源碼中。三是該作者代碼中用的httpurlconnet在HttpUrlSource有這么一段:
@Override public void close() throws ProxyCacheException { if (connection != null) { try { connection.disconnect(); } catch (NullPointerException | IllegalArgumentException e) { String message = "Wait... but why? WTF!? " + "Really shouldn't happen any more after fixing https://github.com/danikula/AndroidVideoCache/issues/43. " + "If you read it on your device log, please, notify me danikula@gmail.com or create issue here " + "https://github.com/danikula/AndroidVideoCache/issues."; throw new RuntimeException(message, e); } catch (ArrayIndexOutOfBoundsException e) { VideoCacheLog.error(TAG,"Error closing connection correctly. Should happen only on Android L. " + "If anybody know how to fix it, please visit https://github.com/danikula/AndroidVideoCache/issues/88. " + "Until good solution is not know, just ignore this issue :(", e); } } }
在沒(méi)有像okhttp這些優(yōu)秀的網(wǎng)絡(luò)開(kāi)源項(xiàng)目之前,android開(kāi)發(fā)都是采用httpurlconnet或者h(yuǎn)ttpclient,部分手機(jī)可能會(huì)遇到這個(gè)問(wèn)題哈。
這里采用的 compile 'com.squareup.okhttp:okhttp:2.7.5' 版本的來(lái)實(shí)現(xiàn)該類(lèi)的功能。在原作者的架構(gòu)思路上我們只需要增加實(shí)現(xiàn)Source接口的類(lèi)OkHttpUrlSource即可,可見(jiàn)作者的代碼架構(gòu)還是不錯(cuò)的,當(dāng)然我們同樣需要處理上文中提高的優(yōu)化點(diǎn)2中的問(wèn)題。將項(xiàng)目中所有用到HttpUrlSource的地方改為OkHttpUrlSource即可。
源碼如下:
/** * ================================================ * 作 者:顧修忠 * 版 本: * 創(chuàng)建日期:2017/4/13-上午12:03 * 描 述:在一些Android手機(jī)上HttpURLConnection.disconnect()方法仍然耗時(shí)太久, * 進(jìn)行導(dǎo)致MediaPlayer要等待很久才會(huì)開(kāi)始播放,因此決定使用okhttp替換HttpURLConnection */ public class OkHttpUrlSource implements Source { private static final String TAG = OkHttpUrlSource.class.getSimpleName(); private static final int MAX_REDIRECTS = 5; private final SourceInfoStorage sourceInfoStorage; private SourceInfo sourceInfo; private OkHttpClient okHttpClient = new OkHttpClient(); private Call requestCall = null; private InputStream inputStream; public OkHttpUrlSource(String url) { this(url, SourceInfoStorageFactory.newEmptySourceInfoStorage()); } public OkHttpUrlSource(String url, SourceInfoStorage sourceInfoStorage) { this.sourceInfoStorage = checkNotNull(sourceInfoStorage); SourceInfo sourceInfo = sourceInfoStorage.get(url); this.sourceInfo = sourceInfo != null ? sourceInfo : new SourceInfo(url, Integer.MIN_VALUE, ProxyCacheUtils.getSupposablyMime(url)); } public OkHttpUrlSource(OkHttpUrlSource source) { this.sourceInfo = source.sourceInfo; this.sourceInfoStorage = source.sourceInfoStorage; } @Override public synchronized long length() throws ProxyCacheException { if (sourceInfo.length == Integer.MIN_VALUE) { fetchContentInfo(); } return sourceInfo.length; } @Override public void open(long offset) throws ProxyCacheException { try { Response response = openConnection(offset, -1); String mime = response.header("Content-Type"); this.inputStream = new BufferedInputStream(response.body().byteStream(), DEFAULT_BUFFER_SIZE); long length = readSourceAvailableBytes(response, offset, response.code()); this.sourceInfo = new SourceInfo(sourceInfo.url, length, mime); this.sourceInfoStorage.put(sourceInfo.url, sourceInfo); } catch (IOException e) { throw new ProxyCacheException("Error opening okHttpClient for " + sourceInfo.url + " with offset " + offset, e); } } private long readSourceAvailableBytes(Response response, long offset, int responseCode) throws IOException { long contentLength = getContentLength(response); return responseCode == HTTP_OK ? contentLength : responseCode == HTTP_PARTIAL ? contentLength + offset : sourceInfo.length; } private long getContentLength(Response response) { String contentLengthValue = response.header("Content-Length"); return contentLengthValue == null ? -1 : Long.parseLong(contentLengthValue); } @Override public void close() throws ProxyCacheException { if (okHttpClient != null && inputStream != null && requestCall != null) { try { inputStream.close(); requestCall.cancel(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage(), e); } } } @Override public int read(byte[] buffer) throws ProxyCacheException { if (inputStream == null) { throw new ProxyCacheException("Error reading data from " + sourceInfo.url + ": okHttpClient is absent!"); } try { return inputStream.read(buffer, 0, buffer.length); } catch (InterruptedIOException e) { throw new InterruptedProxyCacheException("Reading source " + sourceInfo.url + " is interrupted", e); } catch (IOException e) { throw new ProxyCacheException("Error reading data from " + sourceInfo.url, e); } } private void fetchContentInfo() throws ProxyCacheException { VideoCacheLog.debug(TAG, "Read content info from " + sourceInfo.url); Response response = null; InputStream inputStream = null; try { response = openConnectionForHeader(20000); if (response == null || !response.isSuccessful()) { throw new ProxyCacheException("Fail to fetchContentInfo: " + sourceInfo.url); } long length = getContentLength(response); String mime = response.header("Content-Type", "application/mp4"); inputStream = response.body().byteStream(); this.sourceInfo = new SourceInfo(sourceInfo.url, length, mime); this.sourceInfoStorage.put(sourceInfo.url, sourceInfo); VideoCacheLog.info(TAG, "Content info for `" + sourceInfo.url + "`: mime: " + mime + ", content-length: " + length); } catch (IOException e) { VideoCacheLog.error(TAG, "Error fetching info from " + sourceInfo.url, e); } finally { ProxyCacheUtils.close(inputStream); if (response != null && requestCall != null) { requestCall.cancel(); } } } // for HEAD private Response openConnectionForHeader(int timeout) throws IOException, ProxyCacheException { if (timeout > 0) { // okHttpClient.setConnectTimeout(timeout, TimeUnit.MILLISECONDS); // okHttpClient.setReadTimeout(timeout, TimeUnit.MILLISECONDS); // okHttpClient.setWriteTimeout(timeout, TimeUnit.MILLISECONDS); } Response response; boolean isRedirect = false; String newUrl = this.sourceInfo.url; int redirectCount = 0; do { //只返回頭部,不需要BODY,既可以提高響應(yīng)速度也可以減少網(wǎng)絡(luò)流量 Request request = new Request.Builder() .head() .url(newUrl) .build(); requestCall = okHttpClient.newCall(request); response = requestCall.execute(); if (response.isRedirect()) { newUrl = response.header("Location"); VideoCacheLog.debug(TAG, "Redirect to:" + newUrl); isRedirect = response.isRedirect(); redirectCount++; requestCall.cancel(); VideoCacheLog.debug(TAG, "Redirect closed:" + newUrl); } if (redirectCount > MAX_REDIRECTS) { throw new ProxyCacheException("Too many redirects: " + redirectCount); } } while (isRedirect); return response; } private Response openConnection(long offset, int timeout) throws IOException, ProxyCacheException { if (timeout > 0) { // okHttpClient.setConnectTimeout(timeout, TimeUnit.MILLISECONDS); // okHttpClient.setReadTimeout(timeout, TimeUnit.MILLISECONDS); // okHttpClient.setWriteTimeout(timeout, TimeUnit.MILLISECONDS); } Response response; boolean isRedirect = false; String newUrl = this.sourceInfo.url; int redirectCount = 0; do { VideoCacheLog.debug(TAG, "Open connection" + (offset > 0 ? " with offset " + offset : "") + " to " + sourceInfo.url); Request.Builder requestBuilder = new Request.Builder() .get() .url(newUrl); if (offset > 0) { requestBuilder.addHeader("Range", "bytes=" + offset + "-"); } requestCall = okHttpClient.newCall(requestBuilder.build()); response = requestCall.execute(); if (response.isRedirect()) { newUrl = response.header("Location"); isRedirect = response.isRedirect(); redirectCount++; } if (redirectCount > MAX_REDIRECTS) { throw new ProxyCacheException("Too many redirects: " + redirectCount); } } while (isRedirect); return response; } public synchronized String getMime() throws ProxyCacheException { if (TextUtils.isEmpty(sourceInfo.mime)) { fetchContentInfo(); } return sourceInfo.mime; } public String getUrl() { return sourceInfo.url; } @Override public String toString() { return "OkHttpUrlSource{sourceInfo='" + sourceInfo + "}"; } }
關(guān)于Android應(yīng)用中怎么實(shí)現(xiàn)一個(gè)視頻點(diǎn)播功能就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。
新聞標(biāo)題:Android應(yīng)用中怎么實(shí)現(xiàn)一個(gè)視頻點(diǎn)播功能
文章源于:http://aaarwkj.com/article2/pdpeoc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供手機(jī)網(wǎng)站建設(shè)、網(wǎng)站維護(hù)、外貿(mào)網(wǎng)站建設(shè)、網(wǎng)站制作、微信小程序、小程序開(kāi)發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
全網(wǎng)營(yíng)銷(xiāo)推廣知識(shí)