TurtleKurtze
TurtleKurtze

Reputation: 73

Overcome locked screen + silent mode to play audio

This video is a recording of an app which can

Our team is working on a similar custom iphone alarm clock

I would be so grateful if someone could help. I have been trying to break this for two weeks.

our below method is not called when device is locked. that's why alarm sound is not playing

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    
    if ([GlobalData gSettings].vibration) {
        timer = [NSTimer scheduledTimerWithTimeInterval:(1.0) target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
        isVibration = YES;
    } else {
        isVibration = NO;
    }
    
    self.uinfo = notification.userInfo;
    
    
    
    NSString *soundname = [uinfo objectForKey:@"sound"];
    NSURL *clip = [[NSBundle mainBundle] URLForResource:soundname withExtension:@"caf"];
    if (clip) {
        
        self.avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:clip error:NULL];
        self.avPlayer.delegate = self;
        AudioSessionInitialize (NULL, NULL, NULL, NULL);
        AudioSessionSetActive(true);
        
        // Allow playback even if Ring/Silent switch is on mute
        UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
        AudioSessionSetProperty (kAudioSessionProperty_AudioCategory,
                                 sizeof(sessionCategory),&sessionCategory);
    }
    else
    {
        
        NSURL *clip = [[NSUserDefaults standardUserDefaults]URLForKey:[uinfo objectForKey:@"sound"]];
        self.avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:clip error:NULL];
        self.avPlayer.delegate = self;
        AudioSessionInitialize (NULL, NULL, NULL, NULL);
        AudioSessionSetActive(true);
        
        // Allow playback even if Ring/Silent switch is on mute
        UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
        AudioSessionSetProperty (kAudioSessionProperty_AudioCategory,
                                 sizeof(sessionCategory),&sessionCategory);
    }
    

    [self.avPlayer play];

Upvotes: 1

Views: 1063

Answers (1)

Michał Zygar
Michał Zygar

Reputation: 4092

I dug into the LivingEarth app a little. It seems they are using MMDeepSleepPreventer based -component. And they use some sort of internal alarms system(music being played is NOT triggered by the local notification but probably by NSTimer).

However, I found it to not be reliable in newer iOS versions, so I tweaked it a little. When launched it keeps playing the silent audio file which makes possible for app to run the NSTimers even if user pressed the lock button.

You can find my fork here.

Upvotes: 1

Related Questions