iOS - Unable to play a sound in background - ios

I'm currently trying to implement a system like the alarm one to alert the phone when an event occurred (in my case a bluetooth event). I want this alert to occur even if the phone is in silent and in background.
I create a local notification but i can't get sound played if the phone is in silent mode (which seems to be normal since we put the phone in silent).
So i tried to manage the sound by myself and i'm struggling with playing sound in background. So far i implement the "App plays audio or streams audio/video using AirPlay" key in my plist and i'm using this code.
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *error = nil;
BOOL result = [audioSession setActive:YES error:&error];
if ( ! result && error) {
NSLog(#"Error For AudioSession Activation: %#", error);
}
error = nil;
result = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&error];
if ( ! result && error) {
NSLog(#"Error For AudioSession Category: %#", error);
}
if (player == nil) {
NSString *path = [[NSBundle mainBundle] pathForResource:#"bell" ofType:#"wav"];
NSURL *url = [NSURL fileURLWithPath:path];
NSError *err = nil;
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&err];
if(err)
{
NSLog(#"Error Player == %#", err);
}
else {
NSLog(#"Play ready");
}
}
[player prepareToPlay];
[player setVolume:1.0];
if([player play])
{
NSLog(#"YAY sound");
}
else {
NSLog(#"Error sound");
}
The sound works great in foreground, even in silent mode, but i got no sound at all in background. Any ideas ?
Thanks
EDIT:
Finally i got it working with the above code. The only missing point is that i was trying to play the sound in somewhat appeared to be a different thread, when i play it right in my bluetooth event and not my function call it's working.

An app that plays audio continuously (even while the app is running in the background) can register as a background audio app by including the UIBackgroundModes key (with the value audio) in its Info.plist file. Apps that include this key must play audible content to the user while in the background.
Apple reference "Playing Background Audio"
Ensuring That Audio Continues When the Screen Locks
Found here

I'm not sure if your problem is that you have not configure correctly the audio session output. I had similar problem while playing .wav in my app. I only listened them with earphones. This method helped me:
- (void) configureAVAudioSession {
//get your app's audioSession singleton object
AVAudioSession *session = [AVAudioSession sharedInstance];
//error handling
BOOL success;
NSError* error;
//set the audioSession category.
//Needs to be Record or PlayAndRecord to use audioRouteOverride:
success = [session setCategory:AVAudioSessionCategoryPlayAndRecord
error:&error];
if (!success) NSLog(#"AVAudioSession error setting category:%#",error);
//set the audioSession override
success = [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker
error:&error];
if (!success) NSLog(#"AVAudioSession error overrideOutputAudioPort:%#",error);
//activate the audio session
success = [session setActive:YES error:&error];
if (!success) NSLog(#"AVAudioSession error activating: %#",error);
else NSLog(#"audioSession active"); }
Try it out!

You need to make couple of changes in plist file.
for enabling sound when the app enter's Background.
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 AppDelegate
Now, you can easily run audio while phone screen locks or in background.
It works fine for me. :)
for more please refer to Playing Audio in background mode and Audio Session Programming Guide

Related

Why does the volume of my sound go down?

I have a voip app and for an incoming call I redirect to a separate view where the user can accept or reject the call. I want a sound to be played while in this view, so I load a sound file:
NSString *ringtoneSoundPath = [[NSBundle mainBundle] pathForResource:#"ringtone" ofType:#"wav"];
NSURL *ringtoneSoundUrl = [NSURL fileURLWithPath:ringtoneSoundPath];
ringtone = [[AVAudioPlayer alloc] initWithContentsOfURL:ringtoneSoundUrl error:nil];
ringtone.numberOfLoops = -1;
and then in the viewcontroller where I want the sound to be played I have these methods:
- (void)viewWillAppear:(BOOL)animated {
[ringtone play];
}
- (void)viewWillDisappear:(BOOL)animated {
[ringtone stop];
}
This works, but when the call is finished and I call a second time the volume of the sound is suddenly very low. I checked the device's volume settings, but it's still at max. Why does the volume go down when stopping the sound and then playing it again? It doesn't repeat, so the third time, it's just as low as the second time.
We had the similar issue. If you have voip app it means that you use setCategory: in AVAudioSession.
So, you have the code like:
AVAudioSession *aSession = [AVAudioSession sharedInstance];
if ([aSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil]) {
[aSession setMode:AVAudioSessionModeVoiceChat error:nil];
[aSession setActive: YES error:nil];
}
But when you use AVAudioSessionCategoryPlayAndRecord the volume becomes low.
So, before rington play you should set e.g.:
if ([aSession setCategory:AVAudioSessionCategoryPlayback error:nil]) {
[aSession setMode:AVAudioSessionModeDefault error:nil];
[aSession setActive:YES error:nil];
}
Hope this helps

Play MPMoviePlayerController audio stream in background

So I have this app where I play videos and when you exit the app I would like the user to continue to listen to the audio of the video. I use MPMoviePlayerController to play the video and it works in the app perfectly fine. I also setup AVAudioSession up before I play the video and I get no error.
NSError *audioSessionError;
NSError *activationError;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:&audioSessionError];
[audioSession setActive:YES error:&activationError];
I also set in plist background modes audio. But the video with the audio both stop playing when you close the app. I've also imported the AVFoundation framework.
Simply set Application does not run in background to NO in .plsit file
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 AppDelegate
Now, you can easily run audio while phone screen locks or goes in background.
This code worked for me, first you must to give your app permissions to keep playing music in the background (In your .plis), after that go to the wished class and implement this code, first the imports and the the method to play the music.
#import <MediaPlayer/MPNowPlayingInfoCenter.h>
#import <MediaPlayer/MPMediaItem.h>
#import <AVFoundation/AVFoundation.h>
---- o ----
-(void) playMusic{
[[AVAudioSession sharedInstance] setDelegate: self];
NSError *myErr;
// Initialize the AVAudioSession here.
if (![[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&myErr]) {
// Handle the error here.
NSLog(#"Audio Session error %#, %#", myErr, [myErr userInfo]);
}else{
// Since there were no errors initializing the session, we'll allow begin receiving remote control events
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
//initialize our audio player
audioPlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:#"http://www.cocoanetics.com/files/Cocoanetics_031.mp3"]];
[audioPlayer setShouldAutoplay:NO];
[audioPlayer setControlStyle: MPMovieControlStyleEmbedded];
audioPlayer.view.hidden = YES;
[audioPlayer prepareToPlay];
[audioPlayer play];
}//end playmusic
You need to turn on Background Modes in capabilities.

Can't play sound when app is in background mode

In Info.plist I added:
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
<string>location</string>
</array>
...
I load the sound like this:
NSURL *urlFail = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/criticalSound.wav", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:urlFail error:&error];
[audioPlayer setDelegate:self];
audioPlayer.numberOfLoops = 0;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];
[audioPlayer setVolume:1.0];
if (audioPlayer == nil){
}else{
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
musicPlayer = [MPMusicPlayerController iPodMusicPlayer];
if (musicPlayer.playbackState == MPMusicPlaybackStatePlaying)
{
self.wasMusicAppOn = YES;
[musicPlayer pause];
}else{
self.wasMusicAppOn = NO;
}
[audioPlayer play];
}
This works fine when app is active.
But I have a location update when application is in background and from time to time (like when user pass 500m) I should play this sound.
So I put this code there.
Anyway problem is that sound plays when app is in foreground but doesn't work when it is in background.
What am I doing wrong here?
As far as I've been able to tell, you must actually be playing sound while going into the background to be able to continue playing sound in the background.
Also, the description for AVAudioSessionCategoryAmbient states that "Your audio is silenced by screen locking and by the Silent switch (called the Ring/Silent switch on iPhone)".
You need to make couple of changes in plist file.
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 AppDelegate
Now, you can easily run audio while phone screen locks or in background.
It works fine for me. :)
for more please refer to Playing Audio in background mode and Audio Session Programming Guide

How to play Video-Audio on iOS 6?

I am playing videos and audio in my iOS app using AVAudioPlayer for Audio files (.mp3 files) and MPMoviePlayerViewController for videos files (.mp4 files).
It works fine on iOS 5 and lower versions.
But in my iPad ( iOS 6) it doesn't work. It plays video with no audio. Of course it doesn't play audio at all.
Please help me to resolve this problem.
Thanks in advance ...
Since iOS 6 the mute switch will also mute apps, did you check if the mute swoth is turned off.
To force playback if the device is muted you could do the following:
NSError *error= nil;
if ([[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&error]) {
NSLog(#"Error setting audio session: %#", error);
}
NSError *setCategoryErr = nil;
NSError *activationErr = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&setCategoryErr];
[[AVAudioSession sharedInstance] setActive:YES error:&activationErr];
if(setCategoryErr || activationErr)
{
NSLog(#"%# Error: Could not activate silence mode. %# %#", self, setCategoryErr, activationErr);
}

Starting AVAudioPlayer when application is in background

I have an application with App plays audio and App provides Voice over IP services options configured in the .plist.
The application is receiving socket events (even in background) and regarding the events, plays sound. When the application is in foreground, all is ok. When the app is in background, the app is triggered, the play method of the player is called, but without sound.
I have tried many sample code from Internet but nothing is working. I have tried to start playing sound in foreground and then move my app in background and it's working.
What is the problem to start playing a sound when the app is in background?
Here's my code handling an event when my app is triggered in background:
NSError *error;
NSURL *audioFileLocationURL = [[NSBundle mainBundle] URLForResource:#"HeadspinLong" withExtension:#"caf"];
if (audioPlayer != nil) return;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileLocationURL error:&error];
audioPlayer.delegate=self;
if (error) {
NSLog(#"%#", [error localizedDescription]);
}
audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
[audioSession setActive: YES error: &error];
audioSession.delegate=self;
if (error) {
NSLog(#"");
}
Seems like an obvious question, but are you actually calling the play method on the audioPlayer object in your real-life application? Probably at the end of background event handler?
i.e. [audioPlayer play];
For my understanding it seems not possible to start playing a music when the app is in background... It is only possible to continue playing an existing played music in background

Resources