2

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;
Luke Irvin
  • 1,179
  • 1
  • 20
  • 39
  • Just as a side note, you can get URLs out of your bundle with `[[NSBundle mainBundle] URLForResource:@"soundOne" withExtension:@"mp3"]` – dreamlax Feb 03 '13 at 22:16
  • Maybe point those error parameters to some NSError to see what is the actual error? You know... instead of guessing. – Terence Yan Feb 03 '13 at 22:51
  • Look here: http://stackoverflow.com/questions/3740528/play-sound-on-iphone-even-in-silent-mode – sridvijay Feb 03 '13 at 22:53

1 Answers1

4

Stick this before you call play:

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

That should do it.

Adam Waite
  • 19,175
  • 22
  • 126
  • 148
  • @Jayesh It does, that's exactly what this AVSession category is for. In most cases, setting the session to active is not needed though. – Jerrot Feb 10 '17 at 14:29