手机振动时播放提示音

时间:2014-10-22 19:44:45

标签: ios objective-c core-audio audiotoolbox

我的应用程序在后台运行,轮询电子邮件服务器并在发生更改时发送本地通知。我可以从背景状态开始播放警报,但如果手机处于振动状态,则音频将无法播放。有没有办法覆盖那种,当振动打开时,时钟应用程序的警报仍然响起的方式?

在发布时我的app delegate中,我将下面的alert的类方法设置为在后台播放:

+ (void)initializeAudioSettings
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];

    NSError *setCategoryError = nil;
    BOOL success = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
    if (!success) {
        NSLog(@"Error setting up Audio session: %@", setCategoryError.description);
    }

    NSError *activationError = nil;
    success = [audioSession setActive:YES error:&activationError];
    if (!success) {
        NSLog(@"Error setting audio session active: %@", activationError.description);
    }

}

接下来我加载提醒:

- (void)loadAlertSoundID
{
    NSLog(@"Loading alert sound");
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"alert" ofType:@"mp3"];
    NSURL *soundURL = [NSURL URLWithString:soundPath];

    CFURLRef url = (__bridge CFURLRef)soundURL;

    AudioServicesCreateSystemSoundID(url, &_alertSoundID);
}

然后,当我收到新消息的通知时,我会调用我的警报方法:

- (void)playAlert
{
    NSLog(@"Playing alert");
    AudioServicesPlaySystemSound(_alertSoundID);

    _alertShouldBePlaying =  YES;
    _alertIsPlaying = YES;

    AudioServicesAddSystemSoundCompletion(_alertSoundID, nil, nil, playSoundFinished, (__bridge void*)self);

    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(vibrate:) userInfo:nil repeats:YES];
}

完成后,我的完成块。:

void playSoundFinished (SystemSoundID sound, void *data)
{
    Alert *alert = [Alert sharedAlert];
    if (sound == alert.alertSoundID)
    {
        alert.alertIsPlaying = NO;

        // Repeat until alert is disabled
        if (alert.alertShouldBePlaying && !alert.alertIsPlaying)
        {
            [alert playAlert];
        }
    }

}

1 个答案:

答案 0 :(得分:0)

有一种方法可以做到这一点,但如果我是你的应用程序的用户,我不会很感激。

看看AVAudioSessionCategory。您可以将AVAudioSession.category设置为AVAudioSessionCategoryPlaybackAVAudioSessionCategoryPlayAndRecord,这将绕过手机上的静音开关以及任何警报声音设置。它可能仍然由音量按钮控制。

编辑:您还需要使用AVAudioPlayerAudioUnit播放声音,而不是AudioServicesPlaySystemSound才能绕过静音模式。