简体   繁体   中英

IOS Play Sound on receiving push notification when app in foreground

How to play sound on receiving a push notification when the app is in the foreground state.

My Code :

- (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);    
}

Instated of AVPLayer , you should try with following code:

Add following framework

#include <AudioToolbox/AudioToolbox.h>

And use this code,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM