2015-11-04 105 views
4

我使用AVPlayer在線播放音頻,並且希望在avplayer完成加載流時將音頻數據/音頻流保存到本地。如何在使用avplayer播放音頻時將音頻緩存到本地

我implementt它爲以下幾點:

let fileUrl = NSURL(string: strUrl)! 
    let asset = AVURLAsset(URL: fileUrl) 
    asset.resourceLoader.setDelegate(self, queue:dispatch_queue_create("AVARLDelegateDemo loader", nil)) 
    self.pendingRequests = [AVAssetResourceLoadingRequest]() 

    asset.loadValuesAsynchronouslyForKeys(["playable"]){ 
     dispatch_async(dispatch_get_main_queue()){ 
      self.prepareToPlayAsset(asset, requestedKeys: ["playable"]) 
     } 
    } 


    func resourceLoader(resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool { 
    ....... 
    return false 
} 

當網址爲HTTP/HTTPS,它不調用資源加載(資源加載:AVAssetResourceLoader,shouldWaitForLoadingOfRequestedResource ... - ,當URL是定製(eg.:'test'),它調用資源加載(資源加載:AVAssetResourceLoader,shouldWaitForLoadingOfRequestedResource ...

誰知道其中的原因,難道沒有資源加載支持http/https?

回答

3

當播放器不知道如何加載文件時,它調用resourceLoader(resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource...方法。因爲它知道如何加載URL,所以不會調用這個方法,所以你必須傳遞自定義URL。

2

這個sample project and tutorial似乎是你要找的細節。

上面的鏈接設置自定義URL方案並設置AVAssetResourceLoaderDelegate以在加載時處理資源。這被初始化爲:

NSURL *url = [NSURL URLWithString:@"customscheme://host/audio.mp3"]; 
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil]; 
[asset.resourceLoader setDelegate:self queue:dispatch_get_main_queue()]; 

AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset]; 
[self addObserversForPlayerItem:item]; 

self.player = [AVPlayer playerWithPlayerItem:playerItem]; 
[self addObserversForPlayer]; 

的委託方法的實施將隨後類似於以下內容:

- (BOOL)resourceLoader:(AVAssetResourceLoader *)resourceLoader shouldWaitForLoadingOfRequestedResource:(AVAssetResourceLoadingRequest*)loadingRequest{ 

    NSURL *resourceURL = [loadingRequest.request URL]; 

    if([resourceURL.scheme isEqualToString:@"customscheme"]){ 
     LSFilePlayerResourceLoader *loader = [self resourceLoaderForRequest:loadingRequest]; 

     if(loader==nil){ 
      loader = [[LSFilePlayerResourceLoader alloc] initWithResourceURL:resourceURL session:self.session]; 
      loader.delegate = self; 
      [self.resourceLoaders setObject:loader forKey:[self keyForResourceLoaderWithURL:resourceURL]]; 
     } 

     [loader addRequest:loadingRequest]; 

     return YES; 
    } 
    return NO; 
} 

- (void)resourceLoader:(AVAssetResourceLoader *)resourceLoader didCancelLoadingRequest:(AVAssetResourceLoadingRequest *)loadingRequest{ 

    LSFilePlayerResourceLoader *loader = [self resourceLoaderForRequest:loadingRequest]; 

    [loader removeRequest:loadingRequest]; 
} 

凡LSFilePlayerResourceLoader和LSFilePlayerResourceLoader是處理接收到的數據自定義對象(在詳細鏈接)。

0

在這裏你可以找到full Swift solution基於本地AVPlayerItem與自定義加載程序。

+1

1.這並沒有真正回答他的問題,他詢問爲什麼AVAssetResourceLoader不能在http/https中工作。 2.當你提出你自己寫的圖書館作爲解決方案時,你應該透露你是這個圖書館的作者的事實...... –