ios - AVURLAsset trackWithMediaType 在模拟器中不返回 AVMediaTypeAudio 的 audioTracks

标签 ios objective-c avasset

我正在执行以下操作

    AVURLAsset              *audioAsset  = [[AVURLAsset alloc] initWithURL:audioUrl options:nil];
    NSArray<AVAssetTrack *> *audioTracks = [audioAsset tracksWithMediaType:AVMediaTypeAudio];

在真实设备上运行良好。

问题只是发生在模拟器中。我在 bundle 中有一个静态添加的 mp3,因此 audioAsset 已正确启动。但数组 audioTracks 在模拟器上为空(即使 audioUrl 中的路径和 audioAsset 变量是正确且存在的。

有什么建议吗?

最佳答案

我在真实设备上也遇到了同样的问题。该问题是由于初始化 Assets 后尚未准备就绪而引起的。

请查看documentation :

You can initialize a player item with an existing asset, or you can initialize a player item directly from a URL so that you can play a resource at a particular location (AVPlayerItem will then create and configure an asset for the resource). As with AVAsset, though, simply initializing a player item doesn’t necessarily mean it’s ready for immediate playback. You can observe (using key-value observing) an item’s status property to determine if and when it’s ready to play.

要解决此问题,您可以尝试执行以下操作:

AVURLAsset *audioAsset = [[AVURLAsset alloc] initWithURL:audioUrl options:nil];
NSString *tracksKey = @"tracks";
[audioAsset loadValuesAsynchronouslyForKeys:@[tracksKey] completionHandler:
 ^{
    NSError *error;
    AVKeyValueStatus status = [asset statusOfValueForKey:tracksKey error:&error];
    if (status == AVKeyValueStatusLoaded) { 
        // The asset is ready at this point
        NSArray<AVAssetTrack *> *audioTracks = [audioAsset tracksWithMediaType:AVMediaTypeAudio];
     }
 }];

还值得注意的是,如果audioAsset 不可播放,AVKeyValueStatus 状态可能为 AVKeyValueStatusFailed:

BOOL result = [audioAsset isPlayable];

关于ios - AVURLAsset trackWithMediaType 在模拟器中不返回 AVMediaTypeAudio 的 audioTracks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38169589/

相关文章:

ios - 注销 Firebase 时,下一个用户登录时会保留用户的数据

ios - Swift IOS 在弹出后保持 View Controller 在后台运行

ios - 保留文件夹结构 Cocoa Pods

iphone - 如何在数组中包含 UITableViewCell 引用对象?

objective-c - NSURLConnection 返回错误而不是 401 的响应

ios - AVPlayer/AVPlayerItem 如何通知我的应用程序无法访问的网络故障?

ios - 在不关闭键盘的情况下平滑地调整大小和移动 UITableViewCell

ios - 我怎样才能避免重新加载整个表格,扰乱滚动

ios - Swift Merge AVasset-Videos 数组

ios - 等待 Xcode 方法完成