iphone - 本地文件的 AVPlayerStatus 未准备好

标签 iphone objective-c ios audio avplayer

我在播放本地 .wav 文件时遇到了一些问题。我的 AVPlayerStatus 正在打印 0,我假设这意味着它还没有准备好播放。我似乎无法弄清楚,但话说回来,这是我第一次尝试使用任何与 AVPlayer 相关的东西,所以它可能很简单。我将不胜感激任何帮助。这是代码:

我应该补充一点,我的声音没有播放!

-(void) playWordSound:(UILabel *)label
{
    NSString *path;
    switch (label.tag)
    {
        case 1:
            path = [[NSBundle mainBundle] pathForResource:@"humpty" ofType:@"wav"];
            break;
        case 2:
            path = [[NSBundle mainBundle] pathForResource:@"dumpty" ofType:@"wav"];
            break;
        case 3:
            path = [[NSBundle mainBundle] pathForResource:@"saty" ofType:@"wav"];
            break;
        case 4:
            path = [[NSBundle mainBundle] pathForResource:@"on 2" ofType:@"wav"];
            break;
        case 5:
            path = [[NSBundle mainBundle] pathForResource:@"a 3" ofType:@"wav"];
            break;
        case 6:
            path = [[NSBundle mainBundle] pathForResource:@"wall" ofType:@"wav"];
            break;
    }
    NSURL *url = [NSURL fileURLWithPath:path];
    AVQueuePlayer *player;
    static const NSString *ItemStatusContext;
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
    [playerItem addObserver:self forKeyPath:@"status" options:0 context:&ItemStatusContext];
    player = [AVPlayer playerWithPlayerItem:playerItem];

    NSLog(@"%d",player.status);
    [player play];
}

- (void)playerItemDidReachEnd:(NSNotification *)notification {
    NSLog(@"Sound finished");
}

最佳答案

这是 Apple 在使用 AVPlayItem 时指出的一些重要问题 -initWithURL:方法:

Special Considerations

This method immediately returns the item, but with the status AVPlayerItemStatusUnknown.

If the URL contains valid data that can be used by the player item, the status later changes to AVPlayerItemStatusReadyToPlay.

If the URL contains no valid data or otherwise can't be used by the player item, the status later changes to AVPlayerItemStatusFailed.

我想象正在发生的事情是,因为您在创建 AVPlayerItem 对象后不久发送了一条 -play 消息,它的状态仍然是 AVPlayerItemStatusUnknown (同样适用于AVPlayer 对象),因为它没有收到足够的时间来加载资源并将状态更改为 AVPlayerItemStatusReadyToPlay

我的建议:

  • 检查 AVPlayerItem/AVPlayer 状态变化并在稍后阶段调用 -play

或者,更简单,

  • 加载 AVAssetAVURLAsset来自 NSURL 的对象并使用 AVPlayerItem –initWithAsset: 方法,它应该返回一个准备播放的对象,然后你立即调用调用 -play,如果你愿意的话.

关于iphone - 本地文件的 AVPlayerStatus 未准备好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10617569/

相关文章:

iphone - 向 UITableViewCell 添加 subview

iphone - iOS -- arc 下的 initWith 方法

ios - Core Location 正常工作的超时时间

ios - ShinobiCharts 样式/数据顺序问题

ios - index ScrollTo 不适用于 TableViewCell Swift 中的最后一个 CollectionView

ios - UITableView 按字母划分,如联系人列表

ios - Xcode 7 支持 watch OS1 和 OS2

iphone - 在 Objective C 中有两种声明实例变量的方法吗?

ios - 如何使用已解析的 XML 填充表格 View ?

objective-c - 接口(interface)中的变量声明问题