ios 从 AVPlayer 对象访问 URL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14035501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:37:11  来源:igfitidea点击:

Accessing URL from AVPlayer object?

iosavplayer

提问by Claudijo

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

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

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

回答by NJones

An AVPlayerplays an AVPlayerItem. AVPlayerItems are backed by objects of the class AVAsset. When you use the playerWithURL:method of AVPlayerit automatically creates the AVPlayerItembacked by an asset that is a subclass of AVAssetnamed AVURLAsset. AVURLAssethas a URLproperty.

AnAVPlayer播放AVPlayerItem. AVPlayerItems 由类的对象支持AVAsset。当您使用它的playerWithURL:方法时,AVPlayer它会自动创建AVPlayerItem由作为AVAssetnamed的子类的资产支持AVURLAssetAVURLAsset有一个URL属性。

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

所以,是的,在您提供的情况下,您可以NSURL很容易地获得当前播放的项目。这是如何执行此操作的示例函数:

-(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.

不是 swift 专家,但似乎可以更简短地在 swift 中完成。

func urlOfCurrentlyPlayingInPlayer(player : AVPlayer) -> URL? {
    return ((player.currentItem?.asset) as? AVURLAsset)?.url
}

回答by Eric Conner

Solution for Swift 3

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
}

回答by eonist

Oneliner swift 4.1

Oneliner Swift 4.1

let url: URL? = (player?.currentItem?.asset as? AVURLAsset)?.url