Accessing URL from AVPlayer object?

IosAvplayer

Ios Problem Overview


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.example.org/audio"];
self.player = [AVPlayer playerWithURL: url];

Ios Solutions


Solution 1 - Ios

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
}

Solution 2 - Ios

Oneliner swift 4.1 
let url: URL? = (player?.currentItem?.asset as? AVURLAsset)?.url

Solution 3 - Ios

Solution for 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
}

Solution 4 - Ios

AVPlayerItem extension base on @eonist answer.

extension AVPlayerItem {
var url: URL? {
return (asset as? AVURLAsset)?.url
}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionClaudijoView Question on Stackoverflow
Solution 1 - IosNJonesView Answer on Stackoverflow
Solution 2 - IosSentry.coView Answer on Stackoverflow
Solution 3 - IosEric ConnerView Answer on Stackoverflow
Solution 4 - IosВладислав ШматокView Answer on Stackoverflow