AVAudioPlayer cannot play music using NSTimer in the background

I want to play music using AVAudioPlayer using NSTimer, but [player prepareToPlay] returns NO and does not play in the background.

Can someone give me some idea?

Here is my code:

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(playMusic:) userInfo:nil repeats:NO]; [self.window makeKeyAndVisible]; return YES; } - (void)playMusic:(NSTimer *)timer{ [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; NSString *fileName = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Apologize.mp3"]; NSURL *fileUrl = [NSURL fileURLWithPath:fileName]; NSError *error; AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error]; if ([player prepareToPlay]) { [player play]; NSLog(@"start!"); }else{ NSLog(@"error msg ๏ผš%@",error); } } - (void)applicationDidEnterBackground:(UIApplication *)application { if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){ [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; } UIBackgroundTaskIdentifier backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ // /* just fail if this happens. */ [[UIApplication sharedApplication] endBackgroundTask:backgroundTask]; }]; } 
0
source share
4 answers

You need to do this init in viewDidLoad :

 NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"mp3"]; NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath]; self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil]; [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; [[AVAudioSession sharedInstance] setActive: YES error: nil]; 

This is to initialize the audio. Here, with an MP3 test with a name imported into the project. Note that the beginReceivingRemoteControlEvents part is very important. Without it, you canโ€™t start playing from the stage, just keep listening to music already playing from the foreground.

Now you need to listen to the didEnterInBackGround event (you can go with the applicationDidEnterBackground of your application delegate, but in this way you can put the code in the it belongs class):

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterBG:) name:UIApplicationDidEnterBackgroundNotification object:nil]; 

And now in this didEnterBG :

 self.backgroundTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(backgroundWork) userInfo:nil repeats:YES]; [self.backgroundTimer fire]; 

Here I repeat this sound every 10 seconds for personal reasons, but I do everything you need. Finally, the backgroundWork method:

 - (void)backgroundWork{ [self.audioPlayer prepareToPlay]; [self.audioPlayer play]; } 

Now your background file is playing in the background :-)

It should also be noted that your application must have certain rights to perform tasks in the background. You must check the box under "YourTarget" โ†’ Features โ†’ Background Modes: Audio and AirPlay. Otherwise, the OS will terminate your application after a few minutes in real conditions (without a debugger or tool).

+1
source

before going into code. you need to tell the OS that you want the resolution to play music in the background. you can do this by setting the key in your info.plist application

 <key>UIBackgroundModes</key> <array> <string>audio</string> </array> 

By doing this, you can play audio when the application moves to the background.

0
source

Continuing with sffisher, see the apple documentation . Also go through the previous message if there is any problem.

0
source

I have the same problem, but I found a solution from this post: http://developer.apple.com/library/ios/#qa/qa1668/_index.html

 #import <AVFoundation/AVFoundation.h> #import <AudioToolbox/AudioToolbox.h> AVAudioSession *audioSession = [AVAudioSession sharedInstance]; NSError *setCategoryError = nil; [audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError]; if (setCategoryError) { /* handle the error condition */ } NSError *activationError = nil; [audioSession setActive:YES error:&activationError]; if (activationError) { /* handle the error condition */ } 
0
source

Source: https://habr.com/ru/post/959466/


All Articles