Why does AVAudioPlayer does not play? - ios

We developed this iOS scenario:
1) iOS App schedules local push notification
2) Push is a trigger to start AVAudioPlayer audio playing - even if the iPhone is locked (app in background)
Now there are two scenarios:
a) Time difference between push scheduling is more than 3 hours:
Audio does start playing after unlocking and starting the app
b) Time difference between push scheduling is less than 3 hours:
Audio does start playing even without unlocking
We want case b as default case. Does iOS stop/freeze our application after some hours? Interesting: On indian devices there does not seem to be case a - even if time difference is more than 12 hours.
Any ideas?
Thanks so much!

Did you integrate background execution? Otherwise the app will be suspended after a while.
https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

Once didReceiveLocalNotification method triggered in appdelegate, then trigger one method in appdelegate or in global then use below code to play audio file using AVAudioPlayer in background or device lock
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#“filename”
ofType:#“type”];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL
error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
player.numberOfLoops = -1; //Infinite
[player prepareToPlay];
[player play];

Related

Simulate phone call on hands-free to play audio files with AVAudioPlayer

Many older cars have no option to play music from external bluetooth devices (A2DP), they are only able to handle phone calls (hands free). But some navigation apps are able to play sounds simulating a phone call. This way, the radio/CD-player gets interrupted as long as the navigation app plays the sound.
Has anyone an idea how to do this with AVAudioPlayer? Or another method? I could not find any infos related.
That's what I have so far, but I guess I'm completely wrong..
NSUInteger optionsFlag = (AVAudioSessionCategoryOptionAllowBluetooth | AVAudioSessionCategoryOptionMixWithOthers | AVAudioSessionCategoryOptionDuckOthers);
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback withOptions:optionsFlag error: nil];
NSURL *soundFileURL = #"/path/to/soundfile.wav";
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
[player play];

AVAudioPlayer cannot play on background when Youtube playing

I make an alarm feature for my app, at the time I setup for alarm fire I can play a music track with AVAudioPlayer, it worked well on background mode. But if at this time I opening Youtube app and playing a video then the AVAudioPlayer not work.
Please tell me why this happen and how to resolve this issue, how to play both at the same time
This is code I implement:
NSURL *soundURL = [[NSBundle mainBundle] URLForResource:#"remind2"
withExtension:#"mp3"];
avSound = [[AVAudioPlayer alloc]
initWithContentsOfURL:soundURL error:nil];
[avSound setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[avSound prepareToPlay];
[avSound setNumberOfLoops:10];
[avSound setVolume:1.0];
[avSound play];
Thanks!
This is happened because of Youtube app also set property "UIBackgroundMode" property in plist. And even if you check any of other Music app like gaana, savan, etc. this will happened in all of the music app.
Replace this line
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
by this:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
and I resolved my problem
It takes me two days to put the right questions to this problem, I only find the solution when i ask Google why Youtube stop my audio stream and this result search help me
AVAudioPlayer turns off iPod - how to work around?

Audio playing while app in background iOS

I have an app mostly based around Core Bluetooth.
When something specific happens, the app is woken up using Core Bluetooth background modes and it fires off an alarm, however I can't get the alarm working when the app is not in the foreground.
I have an Alarm Singleton class which initialises AVAudioPlayer like this:
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:soundName
ofType:#"caf"]];
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[self.player prepareToPlay];
self.player.numberOfLoops = -1;
[self.player setVolume:1.0];
NSLog(#"%#", self.player);
This is the method that is called when my alarm code is called:
-(void)startAlert
{
NSLog(#"%s", __FUNCTION__);
playing = YES;
[self.player play];
NSLog(#"%i", self.player.playing);
if (vibrate) {
[self vibratePattern];
}
}
Now when the app is in the foreground, self.player.playing returns 1 however when the app is in the background self.player.playing returns 0. Why would this be?
All the code is being called, so the app is awake and functioning.
The vibrate works perfectly which uses AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
Any idea why this sound won't play?
Thanks
Apple has a nice Technical Q&A article about this in its documentation (see also Playing and Recording Background Audio).
I think one big thing missing is that you haven't activated the Audio Background Mode in the Xcode settings:
Maybe also adding [self.player prepareToPlay] in your alert method is helpful.
I have an App than also needs background audio but my App works with the App background mode "Voice over IP" as it needs to record sometimes. I play background audio telling the App singleton I need to play audio in background:
UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
if([thePlayer play]){
newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
}
EDIT: You must call [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL]; before your app goes to background. In my app, it is at the same time you start playing, in yours, if the player might be started in background, you should do:
- (void)applicationDidEnterBackground:(UIApplication *)application{
// You should retain newTaskId to check for background tasks and finish them
newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
}
Apple docs
Either enable audio support from the Background modes section of the Capabilities tab
Or enable this support by including the UIBackgroundModes key with the audio value in your app’s Info.plist file
I take it you have the audio background mode specified for the app. Even so, I'm not sure you can set an audio session to be active while in the background. You need to have activated it before going into the background. You may also need to play some silent audio to keep this active, but this is seems like bad practice (it may drain the battery). Looking at the docs for notifications there seems to be a way to have a local notification play an audio sample that's included in your bundle, which seems to be what you want to do, so maybe that's the way to go.
Try this :
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];
link
Try this http://www.sagorin.org/ios-playing-audio-in-background-audio/
You need to enable your app to handle audiosession interruptions (and ended interruptions) while in the background. Apps handle audio interruptions through notification center:
First, register your app with the notification center:
- (void) registerForMediaPlayerNotifications {
[notificationCenter addObserver : self
selector: #selector (handle_iPodLibraryChanged:)
name: MPMediaLibraryDidChangeNotification
object: musicPlayer];
[[MPMediaLibrary defaultMediaLibrary] beginGeneratingLibraryChangeNotifications];
}
Now save player state when interruption begins:
- (void) audioPlayerBeginInterruption: player {
NSLog (#"Interrupted. The system has paused audio playback.");
if (playing) {
playing = NO;
interruptedOnPlayback = YES;
}
}
And reactivate audio session and resume playback when interruption ends:
-(void) audioPlayerEndInterruption: player {
NSLog (#"Interruption ended. Resuming audio playback.");
[[AVAudioSession sharedInstance] setActive: YES error: nil];
if (interruptedOnPlayback) {
[appSoundPlayer prepareToPlay];
[appSoundPlayer play];
playing = YES;
interruptedOnPlayback = NO;
}
}
Here's Apple's sample code with full implementation of what you're trying to achieve:
https://developer.apple.com/library/ios/samplecode/AddMusic/Introduction/Intro.html#//apple_ref/doc/uid/DTS40008845
I was also facing the same problem, but i was only facing it only during initial time when i was trying to play a sound while app was in background, once the app comes in foreground and i play the sound once than it works in background also.
So as soon as app is launched/ login is successful in my case, i was running this code:
[self startRingcall];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self stopRingcall];
});
- (void)startRingcall
{
if( self.audioPlayer )
[self.audioPlayer stop];
NSURL* musicFile = [NSURL fileURLWithPath:[[[UILayer sharedInstance] getResourceBundle] pathForResource:#"meetcalling" ofType:#"caf"]];
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:&error];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
if (error != nil) {
NSLog(#"meetringer sound error -> %#",error.localizedDescription);
}
self.audioPlayer.volume = 0;
[self.audioPlayer play];
self.audioPlayer.numberOfLoops = 1;
}
- (void)stopRingcall
{
if( self.audioPlayer )
[self.audioPlayer stop];
self.audioPlayer = nil;
}

Audio playing in background not working in iOS Simulator

I've seen lots of questions about playing audio in the background. These questions often ask why the audio plays in the background of the simulator, yet the device simply wouldn't.
In my case, it's reversed.
When I tested my sample app in my iPad, it worked perfectly. However, when I began testing in the simulator, it simply wouldn't continue playing in the background.
Here are the codes I used:
NSURL *url = [NSURL URLWithString:firstSong];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[audioPlayer setNumberOfLoops:-1];
[audioPlayer setCurrentTime:0];
[[AVAudioSession sharedInstance]setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance]setDelegate:self];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
[audioPlayer play];
Can anyone tell me why this won't work? Is it a bug or something?
Background audio is not supported in iOS Simulator afaik.

AVPlayer streaming audio in background

I have a problem with the AVPlayer playing in background mode, like a lot of people here and everywhere on the web. I've done what I think is supposed to work, but is still doesn't... I think my problem might be where I set and use my AudioSession and AVPlayer.
1) The "audio" key is in UIBackgroundModes of my Info.plist
2) AudioSession set like this in AppDelegate (initialised in didFinishLaunchingWithOptions):
AVAudioSession *audio = [[AVAudioSession alloc]init];
[audio setCategory:AVAudioSessionCategoryPlayback error:nil];
[audio setActive:YES error:nil];
3) I use an AVPlayer (not AVAudioPlayer) also implemented in AppDelegate. (initialised in didFinishLaunchingWithOptions, after the AudioSession), right after the AudioSession
// Load the array with the sample file
NSString *urlAddress = #"http://mystreamadress.mp3";
//Create a URL object.
self.urlStream = [NSURL URLWithString:urlAddress];
self.player = [AVPlayer playerWithURL:urlStream];
//Starts playback
[player play];
And still, the audio is suspended everytime the app goes in background (when I press the "Home" button).
By the way, the problem was just with the simulator. Works fine on the iOS devices

Resources