想要让这个选项的应用程序在后台模式播放音频,即使按下主页按钮关闭应用程序 .
使用以下代码只能在按两次主页按钮时处理远程控制事件 . 但是,当应用关闭时,无法在后台播放应用音频 . 那么当按下主页按钮关闭应用程序时,如何才能在我的应用程序中显示可听见的内容 play app's audio of type mp3 in background mode .
在Info.plist文件中,我添加了选项
Required background modes App plays audio
- (void) setupAudioSession {
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
// Specify that this object is the delegate of the audio session, so that this object's endInterruption method will be invoked when needed.
[audioSession setDelegate: self];
// Assign the Playback category to the audio session.
NSError *audioSessionError = nil;
//[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[audioSession setCategory: AVAudioSessionCategoryPlayback error: &audioSessionError];
if (audioSessionError != nil) {
NSLog (@"Error setting audio session category.");
return;
}
// Activate the audio session
[audioSession setActive: YES error: &audioSessionError];
if (audioSessionError != nil) {
NSLog (@"Error activating audio session during initial setup.");
return;
}
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
//if it is a remote control event handle it correctly
if (event.type == UIEventTypeRemoteControl) {
if (event.subtype == UIEventSubtypeRemoteControlTogglePlayPause) {
//[player play];
[self playAction];
// } else if (event.subtype == UIEventSubtypeRemoteControlPause) {
// [player pause];
} else if (event.subtype == UIEventSubtypeRemoteControlPreviousTrack) {
[self rewButtonPressed];
} else if (event.subtype == UIEventSubtypeRemoteControlNextTrack)
[self ffwButtonPressed:nil];
}}
在按下主页按钮时,应用程序的音频未在后台播放的代码中缺少的内容 .
感谢任何帮助 .
谢谢
3 回答
您必须使用以下AppDelegate方法设置Audio会话 .
然后请将Audio会话作为Instance对象,以便可以将其称为self.youraudiosession .
只是为了更清楚地向appDelegate.m添加以下方法
将此代码添加到AppDelegate.m
添加配置相同的图片如下: