Search code examples
iosavaudioplayernsdata

AVAudioPlayer initWithData returning nil


I have used the following code to initialise an AVAudioPlayer object with NSData, which in turn has the data of an mp3 in my main bundle.

NSError *error;
NSString *filePathForBgAudio = [[NSBundle mainBundle] pathForResource:@"beebuzz10" ofType:@"mp3"];
NSData *bgAudioData = [NSData dataWithContentsOfFile:filePathForBgAudio];
bgAudioPlayer = [[AVAudioPlayer alloc] initWithData:bgAudioData error:&error];
bgAudioPlayer.delegate = self;

I have declared bgAudioPlayer in the .h file. But when I checked by setting breakpoint, I found that after this line bgAudioPlayer = [[AVAudioPlayer alloc] initWithData:bgAudioData error:&error]; the bgAudioPlayer is still shown to be nil. But the filePathForBgAudio and bgAudioData are initialised correctly and has data. just the bgAudioPlayer is nil. What is the problem in the above code? How to rectify this?


Solution

  • - (void)viewDidLoad
    {
        [super viewDidLoad];
    
    
        NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                             pathForResource:@"bubble"
                                             ofType:@"mp3"]];
    
        NSError *error;
        _audioPlayer = [[AVAudioPlayer alloc]
                        initWithContentsOfURL:url
                        error:&error];
        if (error)
        {
            NSLog(@"Error in audioPlayer: %@",
                  [error localizedDescription]);
        } else
        {
            _audioPlayer.delegate = self;
            [_audioPlayer prepareToPlay];
    
        }
    }
    
    
    - (IBAction)playsound:(id)sender
    {
    
        [_audioPlayer play];
    
      }