1
我試圖用一個班級來管理全球AVAudioPlayer
實例,但我無法讓鎖屏控制出現。該類的子類UIResponder,但無論我嘗試鎖定屏幕控件都不會出現。iOS音頻控件不能與單身人士一起工作
客戶端類使用- (void)setUrl:(NSURL *)url withTitle:(NSString *)title
加載音頻和playAudio
播放。我在這裏做錯了什麼?
我有後臺執行權限設置爲音頻&汽車玩,即使在模擬器>重置內容和設置後,這是失敗。
- (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];
}
如果我不得不猜測,在'setupAudioControls'之後還有其他'becomeFirstResponder's。如果這個「UIResponder」不是應用程序發送到後臺時的第一響應者,我覺得這樣做不起作用。 – 2015-02-11 19:22:39
出於好奇,你認爲即使你不播放音頻,這個代碼也能工作嗎?我的理解是,截取遙控器事件只有在你開始播放音頻時纔有效,但我不清楚應該如何與鎖屏遙控器進行交互。 – Palpatim 2015-02-11 20:37:30
@Palpatim你可能是對的。我假設音樂還沒有開始,鎖屏播放按鈕可以啓動音樂。這可能是錯誤的。 – 2015-02-13 03:01:37