Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVAudioPlayer via Speakers

I got the following code:

- (id)init {
    if (self = [super init]) {
        UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
        AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);    

        UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
        AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);

        [[AVAudioSession sharedInstance] setDelegate:self];
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
        [[AVAudioSession sharedInstance] setActive:YES error:nil];
    }
    return self;
}

But somehow the sound does not want to come out of the speakers, can someone see what I am doing wrong?

The code I use for playing is:

AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFilePathURL error:nil];
[player prepareToPlay];
[player setVolume:1.0];
[player play];
like image 852
Mark Avatar asked Apr 18 '10 02:04

Mark


1 Answers

It's picky about how you set it up...

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);

It's very important to use AVAudioSessionCategoryPlayAndRecord or the route will fail to go to the speaker. Once you've set the override route for the audio session, you can use an AVAudioPlayer instance and send some output to the speaker.

Hope that works for others like it did for me. The documentation on this is scattered, but the Skype app proves it's possible. Persevere, my friends! :)

Some Apple documentation here: http://developer.apple.com/library/ios/#documentation/AudioToolbox/Reference/AudioSessionServicesReference/Reference/reference.html

Do a search on the page for kAudioSessionProperty_OverrideAudioRoute

like image 73
jocull Avatar answered Sep 26 '22 00:09

jocull