7

我尝试播放一些“媒体”,但在 AVPlayer 启动时我不知道它是音频还是视频。

我连接了播放器层,它工作正常。

self.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:[[PCPlayerManager sharedManager] audioPlayer]];
avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
avPlayerLayer.frame = CGRectMake(0, 0, videoView.frame.size.width, videoView.frame.size.height);
[videoView.layer addSublayer:avPlayerLayer];

但是如何检查是否有视频,以便添加/删除一些选项?

4

6 回答 6

9

来自 Apple 的示例代码项目 AVSimplePlayer:

// Set up an AVPlayerLayer according to whether the asset contains video.
if ([[(AVAsset *)asset tracksWithMediaType:AVMediaTypeVideo] count] != 0)
于 2014-07-25T10:04:55.197 回答
4

对于 Swift 4.2,您可以执行以下操作:

func isAudioAvailable() -> Bool? {
   return self.player?._asset?.tracks.filter({$0.mediaType == AVMediaType.audio}).count != 0   
}

func isVideoAvailable() -> Bool? {
   return self.player?._asset?.tracks.filter({$0.mediaType == AVMediaType.video}).count != 0   
}

或作为扩展

extension AVPlayer {
    var isAudioAvailable: Bool? {
        return self._asset?.tracks.filter({$0.mediaType == AVMediaType.audio}).count != 0
    }

    var isVideoAvailable: Bool? {
        return self._asset?.tracks.filter({$0.mediaType == AVMediaType.video}).count != 0
    }
}
于 2019-04-08T20:23:18.587 回答
3

我不确定但AVPlayerItem有以下数组[mPlayerItem.asset.tracks]它包含两个对象,一个用于视频,另一个用于音频。按如下方式访问它以[mPlayerItem.asset.tracks objectAtIndex:0]获取视频和[mPlayerItem.asset.tracks objectAtIndex:1]音频。

于 2012-10-18T13:05:18.120 回答
0

更新: sean-stayns 在 Swift 5.5 中的回答

extension AVPlayer {
    var isAudioAvailable: Bool? {
        return self.currentItem?.asset.tracks.filter({$0.mediaType == .audio}).count != 0
    }

    var isVideoAvailable: Bool? {
        return self.currentItem?.asset.tracks.filter({$0.mediaType == .video}).count != 0
    }
}
于 2022-02-28T07:09:28.757 回答
0

我发现了这个更好的解决方案

func isVideoAvailable(item: AVPlayerItem) -> Bool {
        for video in item.tracks {
            if video.assetTrack?.mediaType == .video {
                return true
            }
        }
        return false
}

和这个

  if currentItem.tracks.contains(where: { track in
     track.assetTrack?.mediaType == .video
  }) {

     // This Code goes Here!
  }
于 2022-02-06T21:34:44.307 回答
0

这帮助了我:

    // source from https://stackoverflow.com/a/55581216 Changed for last release AVFoundation
    func isAudioAvailable() -> Bool? {
        return self.player.currentItem?.tracks.filter({$0.assetTrack!.mediaType == AVMediaType.audio}).count != 0
    }
    
    func isVideoAvailable() -> Bool? {
        return self.player.currentItem?.tracks.filter({$0.assetTrack!.mediaType == AVMediaType.video}).count != 0
    }
于 2020-11-14T23:11:25.277 回答