iphone - 避免耳机插头在 iOS 中停止 AVAudioPlayer

标签 iphone xcode4.5

在我的 iPhone 应用程序中,我使用 AVAudioPlayer 来播放歌曲...但是当我在播放歌曲期间拔出或插入耳机时,它会自动停止 AVAudioPlayer...即使发生这些更改,我也需要运行音频播放器..任何想法将不胜感激。提前致谢。

最佳答案

首先,您必须告诉 AVAudioSession 您的应用的音频行为。 Apple 将其命名为 Audio Session 类别,可以通过以下方式设置

[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];

例如,AVAudioSessionCategoryPlayback:

When using this category, your app audio continues with the Silent switch set to silent or when the screen locks. (The switch is called the Ring/Silent switch on iPhone.)

This category normally prevents audio from other apps from mixing with your app's audio. To allow mixing for this category, use the kAudioSessionProperty_OverrideCategoryMixWithOthers property.

然后,一旦 Audio Session 设置,应用程序将响应一些音频通知,例如 AVAudioSessionInterruptionNotificationAVAudioSessionRouteChangeNotification

为了回答原来的问题,当音频路由更改时会调用 AVAudioSessionRouteChangeNotification (例如:耳机插入/插入,而且蓝牙设备关闭,...) 。通过一些代码,我们可以找到路由更改的原因。并且,在我们的例子中,如果耳机已拔出,请重新启动播放器。

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSError *setCategoryErr;
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
    
    // Detects when the audio route changes (ex: jack unplugged)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioHardwareRouteChanged:) name:AVAudioSessionRouteChangeNotification object:nil];
    // Don't forget to remove notification in dealloc method!!
}

- (void)audioHardwareRouteChanged:(NSNotification *)notification {
    NSInteger routeChangeReason = [notification.userInfo[AVAudioSessionRouteChangeReasonKey] integerValue];
    if (routeChangeReason == AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {
        // if we're here, the player has been stopped, so play again!
        [self.player play];
    }
}

总而言之,还要考虑一下用户在一次无聊的 session 中不小心拔掉了耳机的情况。他不会有这种会让房间里的设备突然尖叫的行为!

关于iphone - 避免耳机插头在 iOS 中停止 AVAudioPlayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17103148/

相关文章:

objective-c - 在 Xcode 中使用 git 时,UserInterfaceState.xcuserstate 未提交

ios - 使用 Facebook 登录时出错

iphone - 改变 super View 的不透明度奇怪的效果导致 subview 奇怪的不透明度变化

iphone - 自动将生成的源文件添加到 xcode 项目

Xcode 4.4 : how to disable quick help in code completion window?

ios - 记住我使用 UISwitch 和 NSUserDefaults ios 的功能

ios - 找不到 -lsqlite3.0 的库

iphone - 越狱 - 添加图标到状态栏

iphone - UIImagePickerController 媒体类型 kUTTypeMovie 运行时异常

iphone - “设置字体:”已弃用:首先在ios3中弃用(警告)