How do I start playing audio when in silent mode & locked in iOS 6?
Asked Answered
A

8

47

End-user process

  1. Open app
  2. Switch on 'Silent Mode'.
  3. Press 'Lock-button'
  4. App can still START playing a sound after hours have passed, not playing any audio in the interim.

Apps that do this

A lot of alarm apps have manage to do this & I dont think they are using silent audio to keep the app running as they do not sound if you actually exit the app with home.

  • Alarm Clock Pro
  • My Clock
  • Wave Alarm
  • Alarmed
  • iHome
  • ...

...Are they keeping a loop running after being locked some how or it a notification(which cant play sound in silent) starting the app back up to play the audio, or some other method?

Current Methods Implemented

AVAudioPlayer using:

AudioSessionInitialize(nil, nil, nil, nil);
AudioSessionSetActive(YES);

UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof(sessionCategory),&sessionCategory);

And setting Info.plist to:

Required background modes(UIBackGroundModes) - App plays audio (audio)

At Present

I can play audio even in silent when the app is running and on screen. If the audio is already running the app can be closed with home button and audio will run. BUT if the app is not playing audio, and the screen is locked, all threads are killed and audio is never played. How do theses apps manage to work around this?

Possible approaches Found So Far

A. Use 'beginBackgroundTaskWithExpirationHandler:' with an infinite loop to keep app running indefinitely.

Pros:

  • Looks like you can make this work in a lot of situations, even when the user presses home.

Cons:

  • This goes against apple policies as far as I can tell.
  • will use more resources

Comments:

I've almost got this to work and might with some tweaking. This does not seem to be what all these other alarms are doing as they do not keep on running if you press home BTN. Which suggest that they use some method that gives them permission to run while locked but not in the BG. (Which is what I need)

Also, When you ask how much time you have left running you get aprox 10 min. By dropping an infinite loop in there the numbers will actually run down to 0 and then go into the negatives for hours on end.(tested) Im not sure how this would behave in the real world or in terms of app acceptance.

B. Use a silent audio loop to pose as a continus audio playing media center

Pros:

  • Worked when locked, and will keep up running in most situations.

Cons:

  • Can fail if interrupted by another media center and in some other occasions.
  • Can also go agains apple policy.

Comments:

This can work I a lot of situations but is by far not ideal. And since Like I say again, there has to be another method that is not documented.

Conclussions Thus Far

Testing with the listed APPs suggests that they are not using any of the two methods I just described. Method 'A' seems to be closer but if implemented would not behave how these apps behave.

I used a apple developer ticket to get more info, I'll post any new findings along those means as well.

Thank You

Any insight is appreciated, and for your participation thus far.

Aridatha answered 15/3, 2012 at 17:41 Comment(11)
Try using MPMediaPlayer.Thrift
I confirm Andres observations, I have an alarm clock app, and as soon as iOS 5.1 came out I started getting tons of bug reports about it not working. I'm using AVAudioPlayer for sounding the alarm in the foreground. I will try testing with MPMediaPlayer, but Did any one figure out the problem so far?Splendent
I've managed to make the audio keep running after lock if already started with AudioSessionInitialize(nil, nil, nil, nil); AudioSessionSetActive(YES); but I'm still fighting to start an audio track say 5 hrs after the phone is locked and in silent. (updated question with findings)Aridatha
Try this #2749566 or #2913685Coroneted
@Coroneted The method in first link is out of date. The second is a silent audio track loop that goes against appstore regulations and can be basis for rejection. I silent loop will also keep the app running when you use other apps as long as they are not media centrers that override your "media center". It will also drain your battery at a much higher rate. Apps stated above keep on running on lock but do not when app is exited, suggesting another illusive method.Aridatha
I agree with everything you say, @AndresCanella. I've already tried both the methods, but these apps MUST be doing something different. Any news on this?Mustee
I've opened a bounty on this.. Hope it can help :)Mustee
Hi ! I have the same trouble. I need to launch an audio track after a long delay in background. I've been looking for it in SO, but without any success. Your case is similar to mine. Did you find any solution to resolve it? Thanks in advance!Holmun
None as of yet sorry. But do post if you find one.Aridatha
My app has been in the appstore for a long time, the checked solution is accepted by Apple and worked at the time it was checked. (have not tried on iOS 7)Aridatha
Hi @AndresCanella, can you please clarify how you solved this ?? did you get a notification when the app is locked only ?? or played in the background ?? how again did you manage to do it in your app ??Hoxsie
S
15

You need to make couple of changes in plist file.

i.e. 1) Set Required background mode to App plays audio

2) set Application does not run in background to YES.

 NSError *setCategoryErr = nil;
    NSError *activationErr  = nil;
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
    [[AVAudioSession sharedInstance] setActive:YES error:&activationErr];

Then, you need to write these much code in AppDelege

Now, you can easily run audio while phone screen locks or in background.

Singlebreasted answered 1/2, 2013 at 7:13 Comment(12)
This does directly solve the problem to the question. For my scenario this is not a solution as I require to run audio in background. I was provided with this information a few months back but was sworn into secrecy.Aridatha
Apple swore you to secrecy?Meristic
I don't understand if this solved the problem or not? The answer says it will work to play in the background, yet you say that it is still not a solution because you "require to run audio in background". Clarification please :).Forswear
OK, to clarify. I was sworn into secrecy by the developer that gave me the solution. This solution. and yes this DOES SOLVE the question. But my app also plays music so I cant live without the app also being a media player. So in my case I can not use this solution but it does solve the question(or did at the time I accepted it, cant say for iOS 7)Aridatha
so, how exactly do you start playing the sound from background? I can't achieve that with AVAudioPlayer... It works only when player started in the foreground.Volva
HOW? Where is the magic??? My app stops playing even if it started playing in foreground.Alkalize
@AndresCanella You're getting so much knowledge from SO and swore not to help others? Why not ask that developer to help us out and you can still be true to your promise...Jarboe
@IslamQ. This is the solution which directly solves the stated problem. The reason it did not solve my problem, in my specific case is because I also need to play audio as a media player, step 2 of this solution makes this not possible. There is no undisclosed solution, this IS the solution. (I can't confirm if this works on latest iOS.)Aridatha
@AndresCanella I'm planning to add a feature where the app plays audio when receives silent push notification and none of the things I find online works.Jarboe
It is very possible that the process which is being started by iOS does not have those permissions. Thus not making that possible.Aridatha
@IslamQ. I have also same functionality that you have. So, can you please tell me that how you achieve it?Lashelllasher
@HardikShekhat as far as I remember I wasn't able to achieve that after a few tries; it was a dummy project so I got busy with other things and haven't tried it again.Jarboe
S
5

Had you previously been doing this in your app:

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

I had a user tell me that the audio wasn't working on an app (well before iOS5!). Turned out their ring/silent switch was set to "silent". So I added this code, and it causes the "silent" setting to be overridden. This is useful if you have a music app, for example, and you want to music to continue playing.

Septuagenarian answered 15/3, 2012 at 20:13 Comment(5)
What Andreas is referring to above isn't related to not choosing kAudioSessionCategory_MediaPlayback. It has to do with iOS 5.1 update. I already have kAudioSessionCategory_MediaPlayback set in my app and it was working even when the ringer is on silent, until 5.1 came out and it stopped working. Could this be related to the audio problems mentioned here: iphone5gfeatures.com/…Splendent
Hey mark, sorry if I did not make the question 100% clear initially and checked it off. but I also need to start audio after locked and in silent. I've updated the question to make it clearer. I'm testing out these alarms if the app is still launching alarms after a long period of time, which would sugest more than just a 10 min window with beginBackgroundTaskWithExpirationHandler. If they are able this would sugest: 1.some sort of local notification that can reawake app and launch AVAudio. 2.app is still running in backgound when locked. 3.some sort of silent loop. 4.some other way. Ideas?Aridatha
@MarkGranoff Do you have any idea how to start the process when locked as per updated description? Im baffled how these alarms are managing to do this... Thanks.Aridatha
@AndresCanella You may be out of luck. There are precious few ways for an app to get ANY cycles in the background (music playback and location updates among them). And unless you're doing those things it isn't good practice to request those services. I can only think of Local Notifications to have anything happen outside your app. From a local notification the user can launch your app, but they have to hear or see it and act for that to happen. Fwiw, there are a lot of alarm clock apps that sate clearly that they have to be running in the foreground to work as expected.Septuagenarian
@markgranoff local notifications do no play in silent. Correct me if I'm wrong, but the only way to play audio in silent is using AVAudioPlayer? Yet the apps listed can be screen locked and will still play in silent. Even adjust system volume for a volume fad-in. This would suggest some method of bringing the app processing back, or keep running when locked. Also if tested, the are not running when homebutton is pressed, which of silent audio or keep alive loop hack were used would keep that apps running in the BG. So the has to be some third method.Aridatha
A
2

The long seeked solution to this could be a location based justification. Basically use the location background service to justify periodic updates to your app and thus trigger an alarm. This could be justified to apple by including a feature like Weather updates, which requires location services.

I'll look into this a bit into the future. Please if you have the time to look into it now, or if you have insight, dont hesitate to post.

Happy hunting.

Aridatha answered 26/11, 2012 at 4:57 Comment(0)
S
1

Just a check, is your code missing this line:

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
Splendent answered 16/3, 2012 at 22:4 Comment(1)
As far as I know this is to get input from external devices no? Could I use this in any way to continue a loop or awaken the app at a predetermined time? (without user interaction)Aridatha
W
1

Have you registered your app as needing to use audio in the background?

From the docs:

A: I am using MPMoviePlayerController to play audio-only movies and other audio files on the iPhone in iOS 4. How do I ensure my audio will continue playing when my application is switched into the background or the screen is locked?

First, you must declare that your application supports background execution. An application does this by including the UIBackgroundModes key in its Info.plist file. This key identifies which background tasks your application supports. Its value is an array that contains one or more strings. Specify the string value audio to indicate the application plays audible content to the user while in the background.

Next, If you want to ensure that your movie audio continues when the screen locks, you need to assign an appropriate category to your audio session. You cannot rely on the default audio session, whose category (starting in iPhone OS 2.2) is AVAudioSessionCategorySoloAmbient (or equivalently, kAudioSessionCategory_SoloAmbientSound).

For playback to continue when the screen locks, or when the Ring/Silent switch is in the “silent” position, use the AVAudioSessionCategoryPlayback (or the equivalent kAudioSessionCategory_MediaPlayback) category. Listing 1 demonstrates how to initialize your application's audio session with the AVAudioSessionCategoryPlayback category.

Whooper answered 26/3, 2012 at 0:25 Comment(1)
Yes I have, declaring the BG modes in Info.plist and the code snippet I included will ensure that any audio that your app is currently playing will continue playing if locked or leaving the app. This only works if the audio is playing when you close the app or lock the iphone. If you are not playing audio when the screen is locked, you will go into the BG and all your loops will terminate. The silent audio hack plays a silent track continuously to exploit this fact. What I need is a means to start the audio when locked cleanly, Which plenty of alarm apps are currently doing. Thanks sosborn.Aridatha
C
0

Look into SystemSoundID; their audio plays at the volume of the "Ringer and Alerts" slider in Settings>Sounds despite the volume set by volume buttons and silent mode.

Ci answered 15/3, 2012 at 19:51 Comment(0)
I
0

I notice that these apps are very clear about their requirements. They won't work unless (1) the user permits local notification alerts for this app, in Settings > Notifications, and (2) the app is frontmost when the user locks the screen (e.g., they won't work if the user clicks the Home button to quit the app and then locks the screen).

Therefore it's probably a combination of a local notification and a silent sound playing in the background. The silent sound means that when the screen is locked, if the app was frontmost, it is not suspended. The local notification is thus sent to the app itself and the app is able to respond by producing the alarm sound. Or perhaps there's no silent sound and the alarm sound you're hearing is just the custom sound attached to the local notification (but if so, then it isn't clear to me why the app would require to be frontmost when the screen is locked).

Also, though I haven't tested this, behaviour of the silent switch on the iPhone may have changed in 5.1 in response to the Mahler incident (http://www.nytimes.com/2012/01/13/nyregion/ringing-finally-stopped-but-concertgoers-alarm-persists.html). This would explain why developers are commenting that they could do this until 5.1.

Iago answered 27/3, 2012 at 3:4 Comment(5)
Alarm clocks want as many fail as possible so will prefer proper notification configuration in case for the app is "home-button" closed but not in silent scenario. You can take iHandy's clock and configure all notifications to be disabled and the alarm will still sound if you leave it open and lock the screen. So we can rule out local notification having a hand in this. Also I find no documentation or in practice how to have a notification bring the app to the foreground without the user frist pressing OK on the popup.Aridatha
..And like you mentioned, Why would the app need to be in the foreground before you lock if this were a keep alive hack. I've tested these apps and in fact, they do not work if home is pressed. In contrast using the silent hack, they do work when home is pressed. Is there an undocumented way to keep the app running when locked but not indefinitely?Aridatha
A local notification goes to the app directly (it doesn't put up a dialog or anything) if the app is frontmost. Thus the app needs to be frontmost to receive it. It is frontmost as long as the user doesn't click Home.Iago
The app is no longer frontmost if you hit lock ether as far as I can tell. Or I am doing something wrong because mine is not.Aridatha
Is the app front most if you press power button as stated? I cant seem to get any calls to my app when a notification fires, I might be doing something wrong? As far as what I find on apple docs, my app will not be given the opportunity to run unless the user presses affirmative on the notification.Aridatha
D
0

My be these links will help you :

http://developer.apple.com/library/ios/#documentation/Audio/Conceptual/AudioSessionProgrammingGuide/HandlingRouteChanges/HandlingRouteChanges.html#//apple_ref/doc/uid/TP40007875-CH12-SW6

http://developer.apple.com/library/ios/#documentation/AudioToolbox/Reference/AudioSessionServicesReference/Reference/reference.html

Disputant answered 29/3, 2012 at 13:42 Comment(1)
I've gone through all these and have not found the answer so far in there. It not being possible is even stated, despite all the apps that are listed above prove the opposite.Aridatha

© 2022 - 2024 — McMap. All rights reserved.