在我的iPhone应用程序中,我使用AVAudioPlayer播放歌曲...但是当我在歌曲播放期间插入或插入耳机时,它会自动停止AVAudioPlayer ...我需要运行音频播放器,即使这些更改发生..任何我们将不胜感激.谢谢.
首先,您必须告诉AVAudioSession您应用的音频行为.Apple将此命名为音频会话类别,可以设置为
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
Run Code Online (Sandbox Code Playgroud)
例如,AVAudioSessionCategoryPlayback:
使用此类别时,您的应用程序音频会继续将静音开关设置为静音或屏幕锁定时.(该开关在iPhone上称为Ring/Silent开关.)
此类别通常会阻止来自其他应用的音频与您应用的音频混合.要允许混合此类别,请使用kAudioSessionProperty_OverrideCategoryMixWithOthers属性.
然后,一旦音频会话设置,应用程序将响应一些音频通知,如AVAudioSessionInterruptionNotification或AVAudioSessionRouteChangeNotification
要回答,最初的问题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];
}
}
Run Code Online (Sandbox Code Playgroud)
最后,还要考虑一个用户,在一个无聊的会议中,谁不小心插上他的耳机.他不会有这种行为,这会让设备突然在房间里尖叫!
Pal*_*cob -1
我找到了答案。
我们只需导入以下内容
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVAudioPlayer.h>
Run Code Online (Sandbox Code Playgroud)
并写下这段代码
//Play the Event in Background
NSError *setCategoryErr = nil;
NSError *activationErr = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryErr];
[[AVAudioSession sharedInstance] setActive: YES error: &activationErr];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
Run Code Online (Sandbox Code Playgroud)
现在,即使我插入和拔出耳机,它也会持续播放。
| 归档时间: |
|
| 查看次数: |
3779 次 |
| 最近记录: |