某些iPhone应用程序(如Pandora)似乎直接操纵硬件卷并响应物理卷按钮。这是怎么做到的?
AudioSessionServices允许您使用kAudioSessionProperty_CurrentHardwareOutputVolume
属性获取当前硬件输出音量,但它(据称)是只读的。
答案 0 :(得分:7)
他们使用MPVolumeView,简单地添加它,当用户触摸它时它会完成剩下的工作。注意:在iPhone模拟器中不起作用。我认为发行说明也提到不要直接在Interface Builder中使用它。
MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(25, 378, 270, 30)];
[self.view addSubview:volumeView];
[volumeView release];
答案 1 :(得分:6)
以下是设置硬件卷的另一个(完整)示例,并在按下硬件键后检索卷:
// AVAudiosession Delegate Method
- (void)endInterruptionWithFlags:(NSUInteger)flags
{
// When interruption ends - set the apps audio session active again
[[AVAudioSession sharedInstance] setActive:YES error:nil];
if( flags == AVAudioSessionInterruptionFlags_ShouldResume ) {
// Resume playback of song here!!!
}
}
// Hardware Button Volume Callback
void audioVolumeChangeListenerCallback (
void *inUserData,
AudioSessionPropertyID inID,
UInt32 inDataSize,
const void *inData)
{
UISlider * volumeSlider = (__bridge UISlider *) inUserData;
Float32 newGain = *(Float32 *)inData;
[volumeSlider setValue:newGain animated:YES];
}
// My UISlider Did Change Callback
- (IBAction)volChanged:(id)sender
{
CGFloat oldVolume = [[MPMusicPlayerController applicationMusicPlayer] volume];
CGFloat newVolume = ((UISlider*)sender).value;
// Don't change the volume EVERYTIME but in discrete steps.
// Performance will say "THANK YOU"
if( fabsf(newVolume - oldVolume) > 0.05 || newVolume == 0 || newVolume == 1 )
[[MPMusicPlayerController applicationMusicPlayer] setVolume:newVolume];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// Set the volume slider to the correct value on appearance of the view
volSlider.value = [[MPMusicPlayerController applicationMusicPlayer] volume];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
// Activate the session and set teh delegate
[[AVAudioSession sharedInstance] setActive:YES error:nil];
[[AVAudioSession sharedInstance] setDelegate:self];
// Create a customizable slider and add it to the view
volSlider = [[UISlider alloc] init];
CGRect sliderRect = volSlider.frame;
sliderRect.origin.y = 50;
sliderRect.size.width = self.view.bounds.size.width;
volSlider.frame = sliderRect;
[volSlider addTarget:self action:@selector(volChanged:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:volSlider];
// Regoister the callback to receive notifications from the hardware buttons
AudioSessionAddPropertyListener (
kAudioSessionProperty_CurrentHardwareOutputVolume ,
audioVolumeChangeListenerCallback,
(__bridge void*)volSlider
);
[...]
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Remove the Hardware-Button-Listener
AudioSessionRemovePropertyListenerWithUserData(
kAudioSessionProperty_CurrentHardwareOutputVolume,
audioVolumeChangeListenerCallback,
(__bridge void*)volSlider);
}