本文主要是介绍ios监听音量按键,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
这个很简单,KVO监听AVAudioSession单例的outputVolume属性值就可以了
[[AVAudioSession sharedInstance] addObserver: self forKeyPath:@ "outputVolume" options: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:( void *)[AVAudioSession sharedInstance]];
- ( void )observeValueForKeyPath:( NSString *)keyPath ofObject:( id )object change:( NSDictionary *)change context:( void *)context{
if (context == (__bridge void *)[AVAudioSession sharedInstance]){
float newValue = [[change objectForKey:@ "new" ] floatValue];
float oldValue = [[change objectForKey:@ "old" ] floatValue];
// TODO: 这里实现你的逻辑代码
}
}
设置按键音效
- (IBAction)DO:(id)sender{
soundFile = [NSString stringWithFormat:@"/001.mp3"];
[self playSound: soundFile];
}
-(void)playSound:(NSString*)soundKey{
NSString *path = [NSString stringWithFormat:@"%@%@",[[NSBundle mainBundle] resourcePath],soundKey];
//NSLog(@"%@\n", path);
SystemSoundID soundID;
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
AudioServicesPlaySystemSound(soundID);
}
这篇关于ios监听音量按键的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!