简体   繁体   中英

iOS AVAudioPlayer not playing

This code:

NSString *urlPath = [[NSBundle mainBundle] pathForResource:@"snd" ofType:@"mp3"];
NSURL *url = [NSURL fileURLWithPath:urlPath];

NSError *err;

AVAudioPlayer* audioPlayerMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&err];

[audioPlayerMusic play];

Works just fine.

While this one:

NSString *urlPath = [[NSBundle mainBundle] pathForResource:@"snd" ofType:@"mp3"];
NSURL *url = [NSURL fileURLWithPath:urlPath];

AVPlayer* audioPlayerMusic = [AVPlayer playerWithURL:url];

[audioPlayerMusic play];

Plays nothing!

What's going wrong?

When playing/streaming a remote file, AVPlayer isn't ready to play it - you must wait for it to buffer enough data to start paying, while this is not necessary when using AVAudioPlayer. So, either use AVAudioPlayer, or make AVPlayer notify your class using key-value observing when it's ready to begin playback:

[player addObserver:self forKeyPath:@"status" options:0 context:NULL];

And in your class ( self refers to its instance in the above line):

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"status"]) {
        if (player.status == AVPlayerStatusReadyToPlay) {
            [player play];
        } else if (player.status == AVPlayerStatusFailed) {
            /* An error was encountered */
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM