How to Play Audio in background in IPhone?

前端 未结 2 588
一向
一向 2021-01-24 05:29

I\'m trying to play audio file at particular time which i have set.for that I have added audio in \"UIBackgroundModes\" in info.plist and backgroundtaskidentifier in didEnterBac

相关标签:
2条回答
  • 2021-01-24 06:20

    You can check out this reference app with streaming and backgrounding of audio.

    EDIT:

    Example of a local notification w/ attached sound. More detail here.

    - (void)applicationDidEnterBackground:(UIApplication *)application {
        NSLog(@"Application entered background state.");
        // bgTask is instance variable
        NSAssert(self->bgTask == UIInvalidBackgroundTask, nil);
    
        bgTask = [application beginBackgroundTaskWithExpirationHandler: ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [application endBackgroundTask:self->bgTask];
                self->bgTask = UIInvalidBackgroundTask;
            });
        }];
    
        dispatch_async(dispatch_get_main_queue(), ^{
            while ([application backgroundTimeRemaining] > 1.0) {
                NSString *friend = [self checkForIncomingChat];
                if (friend) {
                    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
                    if (localNotif) {
                        localNotif.alertBody = [NSString stringWithFormat:
                            NSLocalizedString(@"%@ has a message for you.", nil), friend];
                        localNotif.alertAction = NSLocalizedString(@"Read Message", nil);
                        localNotif.soundName = @"alarmsound.caf";
                        localNotif.applicationIconBadgeNumber = 1;
                        [application presentLocalNotificationNow:localNotif];
                        [localNotif release];
                        friend = nil;
                        break;
                    }
                }
            }
            [application endBackgroundTask:self->bgTask];
            self->bgTask = UIInvalidBackgroundTask;
        });
    
    }
    
    0 讨论(0)
  • 2021-01-24 06:28

    If I understand you correctly, you want to play a sound at a particular time, no matter if your app is active and foregrounded at that time? Your only (app review-friendly) option is to schedule a local notification, as in slf's answer. UIBackgroundModes won't help you: the audio background mode is for being allowed to execute code while backgrounded only when you start playing audio when you are foregrounded. Example usages are music players and radio apps.

    If you explain your use case more thoroughly, I might have a better answer.

    0 讨论(0)
提交回复
热议问题