使用NSURLProtocol在iOS上为AVPlayer下载时实现播放 [英] Using NSURLProtocol to implement play while downloading for AVPlayer on iOS

查看:112
本文介绍了使用NSURLProtocol在iOS上为AVPlayer下载时实现播放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在服务器上播放mp4视频,我想同时将此视频缓存到磁盘上.

I'm trying to play a mp4 video on my server and I'd like to cache this video to disk simultaneously.

我知道我只能使用2个请求来执行此操作,一个请求下载另一个,由AVPlayer创建,以播放视频,但这会浪费网络带宽.

I know that I can just use 2 requests to do this, one for download another one created by AVPlayer to play the video, but this will waste the network bandwidth.

因此,我只需要使用一个外部请求来下载数据,并从MyNSURLProtocol中的AVPlayer捕获所有NSURLRequest并为它们手动创建NSHTTPURLResponse.

So I need to use just one outer request to download the data and capture all NSURLRequest from AVPlayer in MyNSURLProtocol and manually create NSHTTPURLResponse for them.

工作流程如下:

AVPlayer <-->  MyNSURLProtocol <--> mp4 over network.

通过使用Charles,我可以看到AVPlayer只需两个步骤就可以在Internet上播放视频. 第一步是下载前2个字节,以便了解整个视频文件的大小. 以下请求将同时下载文件的不同部分.

By using Charles I can see that AVPlayer takes 2 steps to play a video on the Internet. The 1st step is to download the first 2 bytes in order to know the whole video file size. The following requests will download different parts of the file concurrently.

所以MyNSURLProtocol所做的只是下载带有外部请求的整个mp4文件,并且当有足够的数据时,它将创建发送到AVPlayer的响应(也包含数据).

So what MyNSURLProtocol does is just downloading for the whole mp4 file with an outer request and when there's enough data, it will create responses that are sent to AVPlayer (also the data).

这是创建和发送2字节请求的响应的方式.

This is how it creates and sends the response.. for the 2-bytes request.

NSMutableDictionary* headers = ... // Config the headers like this:

{
    "Accept-Ranges" = bytes;
    "Cache-Control" = public;
    "Content-Length" = 2;
    "Content-Range" = "bytes 0-1/6581417";
    "Content-Type" = "video/3gpp";
    Date = "Thu, 18 Apr 2013 08:34:35 GMT";
    Expires = "Wed, 12 Feb 2014 08:34:35 GMT";
    "Last-Modified" = "Tue, 16 Apr 2013 09:03:35 GMT";
    "Connection" = Close;
    Server = "gvs 1.0";
    "X-Content-Type-Options" = nosniff;
}


NSHTTPURLResponse* response = [[NSHTTPURLResponse alloc] initWithURL:
self.request.URL statusCode:206 HTTPVersion:@"HTTP/1.1" headerFields:headers];

[self.client URLProtocol:self didReceiveResponse:response 
cacheStoragePolicy:NSURLCacheStorageAllowed];

问题是 AVPlayer不会发送以下请求以获取实际数据,嗯... 有任何线索吗?

The problem is AVPlayer doesn't send following requests to fetch the actual data, hm... Any clue?

推荐答案

好的,最后我发现了这一点: 如何使用使用自定义NSURLProtocol的URL?

OK, finally I found this: How to play movie with a URL using a custom NSURLProtocol?

似乎自定义NSURLProtocol不能与AVPlayer一起使用.所以我放弃了.

It seems that custom NSURLProtocol can not work with AVPlayer. So I give up.

这篇关于使用NSURLProtocol在iOS上为AVPlayer下载时实现播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆