2
votes

I want to play music background and for this i made changes in info.plist . I set Applications does not run in background to NO, required background modes to App plays audio.

I added this in AppDelegate :

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [[AVAudioSession sharedInstance] setDelegate:self];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *error = nil;
    NSLog(@"Activating audio session");
    if (![audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDuckOthers error:&error]) {
        NSLog(@"Unable to set audio session category: %@", error);
    }
    BOOL result = [audioSession setActive:YES error:&error];
    if (!result) {
        NSLog(@"Error activating audio session: %@", error);
    }
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

}

but music doesn't play anymore when i press home button. Any ideea please where i'am wrong ?

2

2 Answers

2
votes

enter image description here

and play audio on homeBtn screen on homeBtnEventMethod

1.) in viewController.h #import <AVFoundation/AVAudioPlayer.h>

2.) @property (nonatomic, strong) AVAudioPlayer *theAudio;

3.) in viewController.m in viewDidLoad

 NSError *error = nil;
self.theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];

4.) - (IBAction)homeBtnTpd { [self.theAudio play]; }

2
votes

You should set Applications does not run in background to NO