当应用程序处于前台时,接收到推送通知后,在iOS上播放声音。

4

如何在应用程序处于前台状态时接收到推送通知时播放声音。

我的代码:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    if (application.applicationState == UIApplicationStateActive)
    {
        //create an audio player and play the sound

        NSString *path = [[NSBundle mainBundle] pathForResource:@"whistle" ofType:@"caf"];
        NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path];
        AVAudioPlayer *theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:NULL];
        theAudio.volume = 1.0;
        [theAudio prepareToPlay];    
        [theAudio play];
    }

    NSLog(@"didReceiveRemoteNotification %@",userInfo);    
}
1个回答

11
< p > 不要使用 < code > AVPlayer ,而应该尝试以下代码: < p > 添加以下框架。
#include <AudioToolbox/AudioToolbox.h>

并使用这个代码:

    SystemSoundID soundID;
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef ref = CFBundleCopyResourceURL(mainBundle, (CFStringRef)@"mySoundName.wav", NULL, NULL);
    AudioServicesCreateSystemSoundID(ref, &soundID);
    AudioServicesPlaySystemSound(soundID);

4
使用AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); 可以触发震动。 - Laszlo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接