52

有没有办法从已使用 URL 初始化的 AVPlayer 对象访问 URL,如:

NSURL *url = [NSURL URLWithString: @"http://www.example.org/audio"];
self.player = [AVPlayer playerWithURL: url];
4

4 回答 4

94

An AVPlayer plays an AVPlayerItem. AVPlayerItems are backed by objects of the class AVAsset. When you use the playerWithURL: method of AVPlayer it automatically creates the AVPlayerItem backed by an asset that is a subclass of AVAsset named AVURLAsset. AVURLAsset has a URL property.

So, yes, in the case you provided you can get the NSURL of the currently playing item fairly easily. Here's an example function of how to do this:

-(NSURL *)urlOfCurrentlyPlayingInPlayer:(AVPlayer *)player{
    // get current asset
    AVAsset *currentPlayerAsset = player.currentItem.asset;
    // make sure the current asset is an AVURLAsset
    if (![currentPlayerAsset isKindOfClass:AVURLAsset.class]) return nil;
    // return the NSURL
    return [(AVURLAsset *)currentPlayerAsset URL];
}

Not a swift expert, but it seems it can be done in swift more briefly.

func urlOfCurrentlyPlayingInPlayer(player : AVPlayer) -> URL? {
    return ((player.currentItem?.asset) as? AVURLAsset)?.url
}
于 2012-12-26T05:08:36.820 回答
15

Oneliner Swift 4.1

let url: URL? = (player?.currentItem?.asset as? AVURLAsset)?.url
于 2018-05-19T19:41:07.673 回答
13

Swift 3 的解决方案

func getVideoUrl() -> URL? {
    let asset = self.player?.currentItem?.asset
    if asset == nil {
        return nil
    }
    if let urlAsset = asset as? AVURLAsset {
        return urlAsset.url
    }
    return nil
}
于 2016-12-14T00:18:24.897 回答
4

AVPlayerItem 扩展基于@eonist答案。

扩展 AVPlayerItem {
    变量网址:网址?{
        返回(资产为?AVURLAsset)?.url
    }
}
于 2020-10-07T10:16:24.387 回答