我想在iOS睡眠计时器被调用时停止我的音频应用。
就像潘多拉的应用程序。
http://help.pandora.com/customer/portal/articles/24324-ios-sleep-timer-with-pandora
轻按"时钟"app,轻按"计时器",选择一个时间,轻按"计时器结束时",轻按"停止"玩
这将使你的潘多拉程序休眠,如果它正在运行。
我可以看到inInterruptionState == kAudioSessionBeginInterruption被调用时iOS睡眠计时器结束,但我怎么能检测如果它的睡眠计时器或只是中断像电话呼叫?
这是我的代码。目前,我的应用程序只是在iOS睡眠计时器结束后重新开始播放。
// Audio Interruption Listener
void MyInterruptionListener(void *inClientData, UInt32 inInterruptionState) {
if (inInterruptionState == kAudioSessionBeginInterruption) {
[[DOSpeechManager sharedInstance] audioSessionBeginInterruption];
}
if (inInterruptionState == kAudioSessionEndInterruption) {
[[DOSpeechManager sharedInstance] audioSessionEndInterruption];
}
}
- (void)audioSessionBeginInterruption {
if ([_MyAcaTTS isSpeaking] && [_MyAcaTTS isPaused] == NO) {
[_MyAcaTTS pauseSpeakingAtBoundary:AcapelaSpeechImmediateBoundary];
[self setAudioSettionStatus:NO];
_audioInterruptedWhileSpeaking = YES;
}
}
- (void)audioSessionEndInterruption {
if (_audioInterruptedWhileSpeaking) {
[self setAudioSettionStatus:YES];
[_MyAcaTTS continueSpeaking];
}
}
- (void)setAudioSettionStatus:(BOOL)status {
AudioSessionSetActive(status);
[_MyAcaTTS setActive:status];
//cancel audio interrupted flag
if (status) {
_audioInterruptedWhileSpeaking = NO;
}
}
关键不在于检测中断的来源,而在于知道中断后应用程序是否应该恢复。
AVAudioSession API将在音频会话中断时发送通知。在这个通知中,操作系统给出了一个"提示",关于应用程序是否应该恢复播放。见下文:
//Add notification observer
__weak typeof(self) weakSelf = self;
self.audioSessionInterruptionNotification =
[[NSNotificationCenter defaultCenter] addObserverForName:AVAudioSessionInterruptionNotification
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note) {
NSNumber* interruptionType = note.userInfo[AVAudioSessionInterruptionTypeKey];
NSNumber* interruptionOption = note.userInfo[AVAudioSessionInterruptionOptionKey];
BOOL shouldResume = interruptionOption.integerValue == AVAudioSessionInterruptionOptionShouldResume;
switch (interruptionType.integerValue) {
case AVAudioSessionInterruptionTypeBegan:
[weakSelf beginInterruption];
break;
case AVAudioSessionInterruptionTypeEnded:
[weakSelf endInterruption:shouldResume];
break;
default:
break;
}
}];
}