Hasib Samad
Hasib Samad

Reputation: 1081

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?

Upvotes: 1

Views: 3692

Answers (1)

user529758
user529758

Reputation:

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 */
        }
    }
}

Upvotes: 8

Related Questions