1
votes

I have tried everything I can find to try and get my app to play an mp3. I have a few 2-3 second mp3s that play as sound effects that work, but I am trying to play a 15s mp3 without any luck.

    NSError *error;
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSBundle mainBundle] URLForResource: @"test" withExtension: @"mp3"] error:&error];
    if (error)  {
        NSLog(@"Error creating audio player: %@", [error userInfo]);
    } else {
        if([audioPlayer play] == FALSE) {
            NSLog(@"Fail %@", error);
        }
    }
    NSTimer* myTimer = [NSTimer scheduledTimerWithTimeInterval: 15.0 target: self
                                                      selector: @selector(stopMusic) userInfo: nil repeats: NO];

I doubt the timer has anything to do with it but thought I would include it just in case. Basically my error checks are not getting triggered at all. It "should" be playing properly but no sound is coming out, and no errors are being displayed.

I have tried a few other things to try and get this working, and I have tried without the timer. I can't find a decent guide. I don't need a full blown media player, just some background music for an UIScreenViewController.

I have also tried the following code, which works good with short MP3s, not with the longer MP3 I want to play.

NSString *path  = [[NSBundle mainBundle] pathForResource:@"bgmusic" ofType:@"mp3"];
NSURL *pathURL = [NSURL fileURLWithPath : path];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)pathURL, &audioEffect);
AudioServicesPlaySystemSound(audioEffect);

Please help, I have spent hours trying to sort this. It seems apple re-jig their audio every time they release an OS.

1
Does your player think it's playing? Call and log [audioPlayer playing] after the if block. Maybe something with the mp3-file? Your code looks right to me.Jörg Kirchhof
it prints true, so it thinks it is playing.ddoor

1 Answers

2
votes

I did a little testing for you: It turned out that music files aren't added to target by default in Xcode 5. Therefore URLForResource:error: likely returns nil.

Try removing the mp3 from your project. Then add it again and this time make shure you add it to your target:

Xcode Screenshot

The other thing is: It seems like you're defining the AVAudioPlayer inside a method. You normally set up a @property for your audio player because otherwise its life is limited to the method - and the music stops playing after you reach the end of the method.