Luke Irvin
Luke Irvin

Reputation: 1249

How to play audio, even when mute button is on?

I'm trying to play an audio file when a button is tapped.

If I step through my code it works, but if I just tap on the button no sound is played.

Here is my code:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
AVAudioPlayer * player;
NSString * path = [[NSBundle mainBundle] pathForResource:@"soundOne" ofType:@"mp3"];
NSURL * url = [NSURL fileURLWithPath:path];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[player play];

Is this the appropriate way to play audio? Nothing is being flagged as being deprecated.

I also see this message in the debugger:

AudioQueue: request to trim 0 + 2690 = 2690 frames from buffer containing 1152 frames

EDIT:

This code works.

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"soundOne"
                                                     ofType:@"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
self.audioPlayer = [[AVAudioPlayer alloc]
                    initWithContentsOfURL:fileURL error:nil];
[self.audioPlayer prepareToPlay];
self.audioPlayer.currentTime = 0;
[self.audioPlayer play];

How can I play audio with the mute button on?

Here is the code I have tried for this:

CFStringRef state;
UInt32 propertySize = sizeof(CFStringRef);
OSStatus audioStatus = AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);
if (audioStatus == kAudioSessionNoError) {
    //NSLog(@"audio route: %@", state);
    return (CFStringGetLength(state) <+ 0);
}
return NO;

Upvotes: 2

Views: 1518

Answers (1)

Adam Waite
Adam Waite

Reputation: 18845

Stick this before you call play:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
[[AVAudioSession sharedInstance] setActive:YES error:&error];

That should do it.

Upvotes: 4

Related Questions