40

I want to play music even if the app goes in background. I checked all stackoverflow links but none of them worked. Please help need to do it today.

I had used following code:-

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Day At The Beach"  ofType: @"mp3"];

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];

NSError *error;
playerTemp = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
playerTemp.numberOfLoops = 0;
AudioSessionSetActive(true);
[playerTemp play];
iGatiTech
  • 2,306
  • 1
  • 21
  • 45
leena
  • 689
  • 2
  • 7
  • 15

12 Answers12

83

I had solved this question by referring iOS Application Background tasks

and make some changes in .plist file of our application..

Update

write this code in your controller's view did load method like this

- (void)viewDidLoad
{
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"in-the-storm" ofType:@"mp3"]];
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [audioPlayer play];
    [super viewDidLoad];
}
Mehul Mistri
  • 15,037
  • 14
  • 70
  • 94
  • 1
    i did this but when i press home button the music stops playing. – leena Oct 01 '11 at 11:14
  • On which device you are using this testing – Mehul Mistri Oct 01 '11 at 11:15
  • You should test this on those devices which supports background task – Mehul Mistri Oct 01 '11 at 11:15
  • do not test this in simulator. Test it on actual iphone / iPad – Sam B Mar 01 '14 at 20:54
  • Note that the sound can be played somewhere other than the viewDidLoad method, but the three lines for setting up the AVAudioSession must be left in the viewDidLoad method, not bundled with the sound playback code. – Mike Mar 17 '15 at 21:04
  • beginReceivingRemoteControlEvents solves playing sound in background, but what if I would like to hide/disable remote controls. I am playing a beep-sound and I don't want remote controls (play,stop,etc) to flash on the screen when device is locked – Ivan Jun 07 '15 at 20:52
  • In my case,background audio is play but thumnail does't show. – amisha.beladiya Nov 30 '16 at 08:21
33

I just wanted to add a note to Mehul's answer. This line:

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

is actually very important. I used other tutorials to get my AVAudioPlayer up and running. Everything worked fine except my audio would not START if the app was in the background. To clarify, my audio was fine if it was already playing when the app went into the background...but it would not start if the app was already in the background.

Adding the above line of code made it so my audio would start even if the app was in the background.

ghostatron
  • 2,620
  • 23
  • 27
  • Say might either of you (@Anurag) know why that is so important? It worked for me too, after hours of searching. Crazy how it's not mentioned in any of the Audio Programming Guide (AVFoundation, AudioQueue or AudioSession). – ari gold Sep 13 '12 at 23:13
  • +1 Brilliant! I just asked at http://stackoverflow.com/q/13335940/13441 and have no obtain any answers. Just looks ugly for my app that remove control buttons attached to it. – sergtk Nov 12 '12 at 12:18
6

You need to set 'audio' as one of your UIBackgroundModes in Info.plist. Apple has documentation on the issue.

Alastair Stuart
  • 4,165
  • 3
  • 36
  • 33
  • i did this but when i press home button the music stops playing. – leena Oct 01 '11 at 11:15
  • The link has been fixed. – Alastair Stuart Feb 19 '14 at 14:10
  • Link is dead (*"Sorry, that page cannot be found"*). – Pang Jan 15 '16 at 03:42
  • [New link](https://developer.apple.com/library/content/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/AudioSessionBasics/AudioSessionBasics.html#//apple_ref/doc/uid/TP40007875-CH3-SW3) This is what needs to be done essentially. All the "remote" thingy is secondary if you're not using those functions. – funct7 Mar 04 '18 at 13:43
5

Write this line in to plist for background run...

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

Write this code Where you want to use

AVAudioPlayer*  audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:self.urlForConevW error:&error];
audioPlayer.delegate = self;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
audioPlayer.numberOfLoops =  1;       
[audioPlayer play];
P.J.Radadiya
  • 1,493
  • 1
  • 12
  • 21
sankalp
  • 617
  • 5
  • 14
3

Also important here if you are using MPMusicPlayerController: You must use:

[MPMusicPlayerController iPodMusicPlayer] 

And Not

[MPMusicPlayerController applicationMusicPlayer] 

Also if you don't want your app to stop music which was playing when your app is started, look here: AVAudioPlayer turns off iPod - how to work around?

Community
  • 1
  • 1
Andy Weinstein
  • 2,639
  • 3
  • 21
  • 32
3

Step1

Make the following changes in info.plist

  1. Application does not run in background : NO

  2. Required background modes

    item0 :App plays audio or streams audio/video using AirPlay

Step 2 Don't forget to add the following things in MainViewController.h file

  1. #import <'AVFoundation/AVAudioPlayer.h>
  2. @interface MainViewController:<'AVAudioPlayerDelegate>

  3. AVAudioPlayer *H_audio_player;

Step 3 Add the following code inside the play action of your MainViewController class.

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%d-%d",C_CID, C_SID] ofType:@"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
H_audio_player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
H_audio_player.delegate = self;
H_audio_player.numberOfLoops = -1;
Mihriban Minaz
  • 3,043
  • 2
  • 32
  • 52
Juhi
  • 31
  • 3
3

You can use MPMoviePlayerController even to play solo-audio movies. If you like it, read this detailed Apple Library Technical Q&A:

iOS Developer Library Technical Q&A QA1668

Greg Sadetsky
  • 4,863
  • 1
  • 38
  • 48
viggio24
  • 12,316
  • 5
  • 41
  • 34
2

I use the below code. It work for me, and call on the button click of audio player instance method.

NSError *error; NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"]]; 
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
[[AVAudioSession sharedInstance] setActive:YES error: &error]; 
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self.player prepareToPlay];
Artem Shmatkov
  • 1,434
  • 5
  • 22
  • 41
user2168844
  • 73
  • 1
  • 1
  • 9
2

From all answers is missing this code to control the player when user is waking the device:

- (BOOL)canBecomeFirstResponder {
        return YES;
    }

- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
    switch (event.subtype) {

        case UIEventSubtypeRemoteControlPlay:

            [_audioPlayer play];
            break;

        case UIEventSubtypeRemoteControlPause:

            [_audioPlayer pause];
            break;

        default:
            break;
    }
}

And you have all these options:

UIEventSubtypeRemoteControlPlay                 = 100,
UIEventSubtypeRemoteControlPause                = 101,
UIEventSubtypeRemoteControlStop                 = 102,
UIEventSubtypeRemoteControlTogglePlayPause      = 103,
UIEventSubtypeRemoteControlNextTrack            = 104,
UIEventSubtypeRemoteControlPreviousTrack        = 105,
UIEventSubtypeRemoteControlBeginSeekingBackward = 106,
UIEventSubtypeRemoteControlEndSeekingBackward   = 107,
UIEventSubtypeRemoteControlBeginSeekingForward  = 108,
UIEventSubtypeRemoteControlEndSeekingForward    = 109,
neowinston
  • 7,584
  • 10
  • 52
  • 83
2

If even after setting audio as one of your UIBackgroundModes in the plist the audio stops when going to background, try setting your application's audio session to media playback.

Here's the related reference: https://developer.apple.com/library/ios/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/Introduction/Introduction.html

Here's about what the code's gonna look like:

NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];

NSError*setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError];
P.J.Radadiya
  • 1,493
  • 1
  • 12
  • 21
Zaky German
  • 14,324
  • 4
  • 25
  • 31
  • If you don't want your app to stop whatever audio is playing when your app is started, you need to do one more thing - look here: http://stackoverflow.com/questions/1507541/avaudioplayer-turns-off-ipod-how-to-work-around – Andy Weinstein Jun 06 '12 at 07:18
1

To play your audio in background

Step 1 :Just add in your info.plistmake an array enter image description here

step2 :

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    __block UIBackgroundTaskIdentifier task = 0;
    task=[application beginBackgroundTaskWithExpirationHandler:^{
        NSLog(@"Expiration handler called %f",[application backgroundTimeRemaining]);
        [application endBackgroundTask:task];
        task=UIBackgroundTaskInvalid;
    }];
}

step3 :

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"iNamokar" ofType:@"mp3"];
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];

    AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[player prepareToPlay];
[self.player play];
Kanhaiya Sharma
  • 1,040
  • 8
  • 20
  • I have a few questions: What is the idea behind "Step 2"? I this line mandatory [[UIApplication sharedApplication] beginReceivingRemoteControlEvents] in "Step 3"? – Ivan Jun 08 '15 at 07:51
0

From Apple's sample code: Audio Mixer (MixerHost)

// If using a nonmixable audio session category, as this app does, you must activate reception of 
//    remote-control events to allow reactivation of the audio session when running in the background.
//    Also, to receive remote-control events, the app must be eligible to become the first responder.
- (void) viewDidAppear: (BOOL) animated {

    [super viewDidAppear: animated];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}

I think remote control events are not needed for the following case:

AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryMixWithOthers,
                        sizeof(value), &value);
Pang
  • 9,564
  • 146
  • 81
  • 122
Gamma-Point
  • 1,514
  • 13
  • 14