I'm trying to write some very simple code to play an audio file. The code works fine on the iPad2 simulator. On my iPad2 device however, [audooPlayer play] returns false and no audio is to be heard.
I've tried both a .caf and .wav file. I've rebooted my iPad2 and made sure the mute switch is off. Any tips on how to debug are greatly appreciated.
Sample code:
- (void)playAudio {
    NSString *file = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"wav"];
    url = [NSURL fileURLWithPath:file];
    NSError *error = nil;
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    if (error != nil) {
        NSLog(@"Error creating audio player: %@", [error localizedDescription]);
        return;
    }
    [audioPlayer setDelegate:self];
    if (![audioPlayer prepareToPlay]) {
        NSLog(@"Error preparing audio");
        return;
    }
    // Everything works fine up to this point
    if (![audioPlayer play]) {
        // I hit this on hardware.  Works perfect on the simulator.
        NSLog(@"Error playing audio");
        return;
    }
After way too much debugging, I finally found the culprit. I was following the guide at http://developer.apple.com/library/ios/#documentation/AudioVideo/Conceptual/MultimediaPG/UsingAudio/UsingAudio.html#//apple_ref/doc/uid/TP40009767-CH2, and earlier in my app before playing audio, I record some audio. Based on that guide I was calling
[[AVAudioSession sharedInstance] setActive: NO error: nil];
when done recording. This apparently causes AVAudioPlayer to fail playing audio. Changing the call to
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
instead fixes things. It is very odd that this isn't a problem in the simulator, but causes issues on hardware.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With