我尝试使用类来管理全局AVAudioPlayer
实例,但我无法显示锁定屏幕控件。该类是UIResponder的子类,但无论我尝试锁定屏幕控件都不会出现。
客户端类使用- (void)setUrl:(NSURL *)url withTitle:(NSString *)title
加载音频,playAudio
播放。我在这里做错了什么?
我将后台执行权限设置为audio&汽车游戏,这甚至在模拟器之后失败了>重置内容和设置。
- (void)playAudio {
[self.audioPlayer play];
[self updateNowPlayingInfo];
}
- (void)stopAudio {
[self.audioPlayer stop];
[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:nil];
}
- (void)pauseAudio {
[self.audioPlayer pause];
[self updateNowPlayingInfo];
}
- (void)setupAudioSession {
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
[audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
NSError *activationError = nil;
[audioSession setActive:YES error:&activationError];
}
- (void)setupAudioControls {
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
[self updateNowPlayingInfo];
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent {
if (receivedEvent.type == UIEventTypeRemoteControl) {
switch (receivedEvent.subtype) {
case UIEventSubtypeRemoteControlTogglePlayPause:
NSLog(@"Play pause");
if (self.audioPlayer.isPlaying) {
[self.audioPlayer pause];
}
else {
[self.audioPlayer play];
}
break;
case UIEventSubtypeRemoteControlPreviousTrack:
break;
case UIEventSubtypeRemoteControlNextTrack:
break;
default:
break;
}
[self updateNowPlayingInfo];
}
}
- (void)updateNowPlayingInfo {
NSMutableDictionary *albumInfo = [[NSMutableDictionary alloc] init];
albumInfo[MPMediaItemPropertyTitle] = self.title;
albumInfo[MPMediaItemPropertyArtist] = @"Fidelity";
albumInfo[MPMediaItemPropertyAlbumTitle] = self.title;
albumInfo[MPMediaItemPropertyPlaybackDuration] = @(self.audioPlayer.duration);
albumInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = @(self.audioPlayer.currentTime);
[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:albumInfo];
}
- (void)setUrl:(NSURL *)url withTitle:(NSString *)title {
self.title = title;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[self setupAudioSession];
[self setupAudioControls];
}
答案 0 :(得分:1)
在转到后台后,您的-(void)setupAudioControls
应该被称为。在我的应用中:
...
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(appDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
...
- (void)appDidEnterBackground:(NSNotification *)notification {
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
[self updateMediaInfo];
}