iOS AVAudioPlayer Volume Control

4.6k views Asked by At

I've read quite a few posts on the subject but the answers are not 100% clear. I'm looking for clarity here.

My app plays a short AVAudioPlayer sound periodically. The problem is, I can only set the volume after the first sound is played.

After reading stackoverflow, everyone seems to suggest that I play a dummy (silent) AVAudioPlayer sound at the start of the app to "link" the device's volume buttons to the "app volume".

Said another way, when the app starts, it's the "Ringer" volume that is controlled by default and only after the first sound is played will the device's volume buttons finally control the "app volume" (AVAudioPlayer volume) (it's the image without any label). Unfortunately by the time this happens, the user doesn't hear the first sound and now sees the app as broken.

My question is, is this the answer? Do I simply play a short dummy sound once at the start of the app to "link" the device's volume buttons to the app?

Reference Image

2

There are 2 answers

0
pgkelley On BEST ANSWER

You don't have to play a dummy sound. Using the AudioToolbox framework you can set the AudioSessionActive as follows:

AudioSessionInitialize (NULL, NULL, NULL, NULL);
UInt32 sessionCategory = kAudioSessionCategory_AmbientSound;
AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (sessionCategory), &sessionCategory);
AudioSessionSetActive (true);

This will allow the volume buttons to control the app volume.

See this question: Cannot Control Volume of AVAudioPlayer via Hardware Buttons when AudioSessionActive is NO for more information on this approach.

0
L_Sonic On

Hey for future answer searchers, Since AudioSessionInitialize and AudioSessionSetActive are deprecated in iOS7 the recommended way of handling hardware audio and getting call backs is by using an AVAudioSession object. Set the session as active for your app and KVO on the @"outputVolume" property of the session.

- (id)init
{
    self = [super init];
    if (self)
    {

       self.audioSession = [AVAudioSession sharedInstance];
       [_audioSession setActive:YES error:nil];
       [_audioSession addObserver:self forKeyPath:@"outputVolume" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew  context:NULL];
    }
    return self;   
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"outputVolume"])
    {
        [self setVolume:[change[@"new"] floatValue]];
    }
}

- (void)dealloc
{
    [_audioSession removeObserver:self forKeyPath:@"outputVolume"];
    [_audioSession setActive:NO error:nil];
}