首页 > 解决方案 > 收到通知时播放声音在开发中有效但在生产中无效

问题描述

无论是否打开静音模式,我都想在收到特定通知时播放声音。

我让它在开发模式下使用 AVFoundation 框架工作。所以在 AppDelegatedidFinishLaunchingWithOptions方法中我初始化AVAudioSession

NSError *audioSessionError = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&audioSessionError];
[[AVAudioSession sharedInstance] setActive:YES error:&audioSessionError];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

if(audioSessionError) {
    NSLog(@"[AppDelegate] audioSessionError: %@", audioSessionError);
}

我使用该didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler方法检查应用程序是否在后台,通知是播放声音的通知。

if(application.applicationState == UIApplicationStateBackground) {        
    NSDictionary *aps = [userInfo objectForKey:@"aps"];

    if([[aps valueForKey:@"category"] isEqualToString:@"alarm"]) {
        NSString *path = [NSString stringWithFormat:@"%@/alarm.wav", [[NSBundle mainBundle] resourcePath]];
        NSURL *soundUrl = [NSURL fileURLWithPath:path];

        NSError *audioPlayerError = nil;
        self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:&audioPlayerError];

        if(audioPlayerError) {
            NSLog(@"[AppDelegate] audioPlayerError: %@", audioPlayerError);
        } else {
            NSLog(@"[AppDelegate] audioPlayer play call");
            [self.audioPlayer play];
        }
    }

    completionHandler(UIBackgroundFetchResultNewData);
} else {
    completionHandler(UIBackgroundFetchResultNoData);
}

后台模式的 info.plist 中的键audioremote-notification设置。

一切正常,所以我在没有对 TestFlight 进行任何更改的情况下推送了应用程序。当应用程序现在收到通知时,会显示警报,但打开静音模式时不会播放声音。所以我再次在开发中测试它,我得到了相同的结果。收到通知并显示,但不播放声音。

我不知道为什么它在将其推送到 TestFlight 之前在开发中工作,之后它是在生产中还是在开发中工作。每次都会收到通知,只有声音不再播放。

有人知道这是怎么发生的吗?

标签: iosobjective-cnotificationsavfoundationaudio-player

解决方案


所以,我找到了解决我的问题的方法。

AppDelegate.m初始化文件中,AVAudioSession我将行从

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&audioSessionError]; 

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&audioSessionError];

使用新选项AVAudioSessionCategoryOptionMixWithOthers,它可以在开发和生产中使用。


推荐阅读