Play music in the background using AVAudioplayer

2019-01-02 20:33发布

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];

12条回答
大哥的爱人
2楼-- · 2019-01-02 21:00

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];
查看更多
余欢
3楼-- · 2019-01-02 21:04

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;
查看更多
伤终究还是伤i
4楼-- · 2019-01-02 21:04

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,
查看更多
与君花间醉酒
5楼-- · 2019-01-02 21:04

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];
查看更多
谁念西风独自凉
6楼-- · 2019-01-02 21:08

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];
查看更多
只靠听说
7楼-- · 2019-01-02 21:11

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);
查看更多
登录 后发表回答