Wednesday, June 5, 2013

AVAudioPlayer volume example in Objective C (iOS).


AVAudioPlayer volume

The playback gain for the audio player, ranging from 0.0 through 1.0.

@property float volume

AVAudioPlayer volume example.
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: url error: nil];
self.appSoundPlayer = newPlayer;
[newPlayer release];
[appSoundPlayer prepareToPlay];
[appSoundPlayer setVolume: 0.8];
[appSoundPlayer setDelegate: self];
    [appSoundPlayer play];

Example of [AVAudioPlayer volume].
//set up audio session
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:NULL];

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

NSURL* soundUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"HsTR_soundEFX_2-1" ofType:@"mp3"]];
audioAlert= [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
audioAlert.delegate = self;
[audioAlert prepareToPlay];//audioAlert is an AVAudioPLayer declared in header

//and whereever you want to play the sound, call the lines below
float currentVolume=[MPMusicPlayerController applicationMusicPlayer].volume; //grab current User volume
[[MPMusicPlayerController applicationMusicPlayer] setVolume:1.0];//set system vol to max
[audioAlert play];
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(setVolumeBackToNormal)userInfo:nil repeats:NO];

//and the setVolumeBackToNormal function calls this line below
[[MPMusicPlayerController applicationMusicPlayer]setVolume:currentVolume];//returns volume to original setting

AVAudioPlayer volume example.
- (void)sliderValueChanged:(UISlider *)slider {
  myPlayer.volume = slider.value / 100.0;
}

End of AVAudioPlayer volume example article.