Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVAudioPlayer play returns false on hardware

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;
    }
like image 802
Brad Avatar asked Dec 12 '22 20:12

Brad


1 Answers

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.

like image 110
Brad Avatar answered Jan 06 '23 10:01

Brad