Accessing URL from AVPlayer object?

后端 未结 4 1601
独厮守ぢ
独厮守ぢ 2020-12-28 11:49

Is there a way to access the URL from an AVPlayer object that has been initialized with a URL, as in:

NSURL *url = [NSURL URLWithString: @\"http://www.exampl         


        
4条回答
  •  [愿得一人]
    2020-12-28 12:36

    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
    }
    

提交回复
热议问题