Search code examples
iosobjective-caudioavplayernsbundle

AVPlayer doesn't play anything


I am doing something incredibly simple, just play an audio. but it doesn't play anything. not on the simulator or device.

audio file is in bundle and preview can play the audio, I have also tried different audios nothing plays.

What could be the problem?, do I have to add delegate methods for avplayer?(if so that doesn't make sense to me)

I have also tried without avplayer item and different nsurl methods too...

#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>

- (void)viewDidLoad {
    [super viewDidLoad];


    NSString *path = [[NSBundle mainBundle] pathForResource:@"JohnsPizza" ofType:@"aiff"];
    //NSURL *assetURL = [[NSBundle mainBundle] URLForResource:@"JohnsPizza" withExtension:@"aiff"];
    NSURL *url = [NSURL fileURLWithPath:path];
    AVPlayer *player = [[AVPlayer alloc] init];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
    player = [AVPlayer playerWithPlayerItem:playerItem];
    [player play];
}

enter image description here

I have also tried but no luck

//    SystemSoundID sound1;
//    AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &sound1);
//    AudioServicesPlaySystemSound(sound1);
//    AudioServicesRemoveSystemSoundCompletion(sound1);
//    AudioServicesDisposeSystemSoundID(sound1);

Solution

  • you gotta retain AVPlayer object as it may set to nil automatically

    @property (strong, nonatomic) AVPlayer *player;