Play music in the background using AVAudioplayer
Asked Answered
B

12

41

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];
Blackberry answered 1/10, 2011 at 11:0 Comment(0)
F
84

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];
}
Fico answered 1/10, 2011 at 11:4 Comment(7)
i did this but when i press home button the music stops playing.Blackberry
On which device you are using this testingFico
You should test this on those devices which supports background taskFico
do not test this in simulator. Test it on actual iphone / iPadPiker
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.Charily
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 lockedExpectant
In my case,background audio is play but thumnail does't show.Harpsichord
U
34

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.

Unplaced answered 9/11, 2011 at 21:21 Comment(2)
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).Boswell
+1 Brilliant! I just asked at https://mcmap.net/q/392262/-playing-sequence-of-sounds-in-background-with-avaudioplayer/13441 and have no obtain any answers. Just looks ugly for my app that remove control buttons attached to it.Moira
Y
6

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

Yelenayelich answered 1/10, 2011 at 11:5 Comment(4)
i did this but when i press home button the music stops playing.Blackberry
The link has been fixed.Yelenayelich
Link is dead ("Sorry, that page cannot be found").Cock
New link This is what needs to be done essentially. All the "remote" thingy is secondary if you're not using those functions.Selfoperating
C
6

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];
Combination answered 15/11, 2013 at 10:39 Comment(0)
C
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

Concerning answered 1/10, 2011 at 11:7 Comment(0)
R
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?

Revanche answered 6/6, 2012 at 7:15 Comment(0)
V
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;
Vas answered 7/10, 2014 at 10:14 Comment(0)
H
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];
Hemato answered 1/10, 2011 at 11:19 Comment(1)
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: #1508041Revanche
K
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];
Katiekatina answered 13/5, 2013 at 7:34 Comment(0)
I
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,
Intellectual answered 1/3, 2016 at 19:46 Comment(0)
S
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];
Savour answered 4/1, 2014 at 10:17 Comment(1)
I have a few questions: What is the idea behind "Step 2"? I this line mandatory [[UIApplication sharedApplication] beginReceivingRemoteControlEvents] in "Step 3"?Expectant
C
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);
Computer answered 30/5, 2013 at 9:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.