Play some sound in background, some sound only in foreground - ios

I want to play sound in background for a feature but I want to play sound only in foreground for another feature.
Also, I want to play sound even when the silent switch is turned on.
To play sound in background, the following 2 code is needed:
[Info.plist] UIBackgroundModes = audio
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: [])
To play sound only in foreground, I think I have to set UIBackgroundModes to empty in the Info.plist.
But it is not possible while the app is running.
How can I play sound only in foreground for a feature and sound in background for another feature?
* playing sound in foreground means that sound is paused when the user push the home button of the iPhone and it is resumed when the user open the app again.

How can I play sound only in foreground for a feature and sound in background for another feature
Detect when the app goes into the background, and stop playing the foreground sound and switch to the background sound.

Related

How are some alarm apps such as Alarmy able to play a sound on iPhone when the app is in the background and the phone is on vibrate

I am working on app that can alert users for some critical things. I use local notifications to alert the user. On iOS, I find that the notifications will not ring if the phone is on vibrate. This is a deal-breaker for many users of the app but I have been putting that question off till now since I thought that iOS doesn't allow an app to play a sound if the app is in the background.
Music apps are able to play songs even when the phone is on vibrate by enabling the audio background mode but it doesn't allow you to schedule a song to be played at a certain time.
Lately I have seen that some apps are able to play a sound at a certain time even though the app is in the background. One such app is Alarmy alarm app. I don't think that they are playing the music via the local notification when the alarm expires because the music continues to play even after I clear the notification. From the local notification documentation, I understood that I am can't run any code when local notification fires till the user clicks on the notification. So, I can't start an audio player which may be able to play the sound in vibrate.
How are such apps able to play a sound even though the phone is on vibate and the app is in background in iOS?
There are few methods to implement this kind of functionality.For reference I recommend this link.
For actually playing the sound while the device’s ringer switch is set to vibrate
First off make sure to include the audio background mode in the capabilities, in order to play audio in the background.
Then,
Swift 4
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, with: [.duckOthers, .defaultToSpeaker])
try AVAudioSession.sharedInstance().setActive(true)
UIApplication.shared.beginReceivingRemoteControlEvents()
} catch {
NSLog("Audio Session error: \(error)")
}
Here we set the shared audio session’s category to AVAudioSessionCategoryPlayAndRecord, so that we can play sound, while the device’s ringer switch is set to vibrate.
The .duckOthers is specified to make other audio quieter, if there’s any mixable audio playing, so that our alarm can be heard. You can leave that out or use another option, if you prefer a different behavior.
The .defaultToSpeaker is specified, so that the volume would go to the speaker, where it’ll be much louder and should wake up our user with ease.
beginReceivingRemoteControlEvents makes it so that the app handles the remote control options, like the play/pause buttons on the lock screen, in order to make it easier for our user to mute their alarm, once they wake up.
The way this can be done (I have implemented this in my app) is by starting an AVAudioPlayer and specifying a specific time to play. So:
Enable background audio in the app capabilities.
Start and audio session with .playback mode, and start a player at the time you like it to play:
do {
//set up audio session
try AVAudioSession.sharedInstance().setCategory(.playback, options: [.defaultToSpeaker, .duckOthers])
try AVAudioSession.sharedInstance().setActive(true)
//Start AVAudioPlayer
player.play(at: time) //time is a TimeInterval after which the audio will start
}
catch {
...
}
This does not play silence in the background, which violates Apple's rules. It actually starts the player, but the audio will only start at the right time. I think this is probably how Alarmy implemented their alarm, given that it's not a remote notification that triggers the audio nor is the audio played by a local notification (as its not limited to 30 seconds or silenced by the ringer switch).

How to play longer music as Notification alert?

I want to set a music which is longer than 30sec as notification soound. But after searching about this I came to know that it is not possible to add these type of music as notification sound. notification sound must be in 30sec longer otherwise it will not play music. Now how can I add more than 30sec longer music as notification sound?
I had a similar issue for my alarm app as well. What I did was a workaround when your app is in background. You play a music file in your code in background and increase the volume of the device to maximum. You can play as much longer music file as you want. Stop playing the music when someone clicks on the notification.
The only problem with this is that your app should not be killed or terminated.

AVAudio Recorder is not recording after comes from background

I have used AVAudioRecorder. The recorder is not recording when i come from background.
My Scenario is
Start recording press home button (Recording stopped)
Open my app the recorder is still recording (Checked by recorder.isRecording is YES)
Stop the recording and playing the recorded audio plays only what recorded before my app goes background.
I am recoding 5sec -> app goes background -> comes fore foreground -> record another 5 secs -> play the audio the audio plays only the first 5 secs.
While recording I am checking the size of the file path given to the audio recorder(By NSTimer) the file size is not increased after come from background but still the recorder status is recording
Can any one point out what is the mistake. Thanks
Note: in ios6 there is no problem it plays entire audio that is entire 10 sec it comes only in ios7
So if you dont want to record in the background and you only want to append your recording before and after going to background, pause your recorder in applicationWillEnterBackground (or applicationWillResignAcive) and when you come back form background, continue your recording and you'd be fine. (You can have notifications letting your class which is recording know about those life cycle delegate methods.)
But if you want to record in the background you need to turn on Background Mode: Audio and Airplay in your app settings -> Capabilities. But thats another story.
You should check AVAudioSessionDelegate delegate method. Audio recording will stop during phone call
- (void)beginInterruption{
}
-(void)endInterruption{
}
You can continue background recording. Add the background modes as seen in image

AVAudioRecorder doesn't append the recording after comes from background

I am using AVAudioRecorder for recording while I am recording I press home button and comes to fore ground and checked the status of the AVAudioRecorder (isRecording) is still YES. But when i play the audio it plays only what i recorded before goes to background.
Note: This problem comes only in ios7. It works well in ios6
Have you set the app to allow background recording? Under the Project Capabilities, turn on Background Modes and select Audio and AirPlay.
Be warned, in iOS7, when background recording through AVAudioRecorder is interrupted, the recorded file is closed instead of paused. If a user get a phone call while recording in the background, the audio file will stop recording and cannot be resumed. You will need to start a new audio file and merge them, or use Audio Queues and manage the interruptions yourself.
See this answer for more info: Audio interruption when iOS application is recording in background

Start playing MPMusicPlayerController when app is in background

Is it possible to start playing 'MPMusicPlayerController' when the app is in a background state? I have an alarm clock app and I would like to start playing music when the alarm goes off and the app isn't in the foreground.
Go to project properties -> Capabilities and switch on the Application Background Modes
Then in your plist file add the following key:
Now just play the music in when your timer sets off.

Resources