使用AVAudioplayer在后台播放音乐

时间:2011-10-01 11:00:42

标签: objective-c iphone ipad avaudioplayer

即使应用程序进入后台,我也想播放音乐。我检查了所有stackoverflow链接,但没有一个工作。今天请帮忙完成。

我使用了以下代码: -

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 个答案:

答案 0 :(得分:79)

我通过引用iOS Application Background tasks

解决了这个问题

并在我们的应用程序的.plist文件中进行一些更改..

<强>更新

在你的控制器视图中写下这段代码,像这样加载方法

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

答案 1 :(得分:32)

我只是想给Mehul的回答添加一个注释。这一行:

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

实际上非常重要。我使用其他教程来启动和运行我的AVAudioPlayer。一切都运行正常,但如果应用程序在后台,我的音频将无法启动。为了澄清,我的音频很好,如果应用程序进入后台时已播放...但如果应用程序已经在后台,则无法启动。

添加上面的代码行使得即使应用程序在后台,我的音频也会启动。

答案 2 :(得分:6)

您需要将'audio'设置为Info.plist中的UIBackgroundModes之一。 Apple有documentation on the issue

答案 3 :(得分:4)

将此行写入plist for background run ...

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

将此代码写入您想要使用的位置

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

答案 4 :(得分:3)

您甚至可以使用MPMoviePlayerController播放独奏音频电影。如果您喜欢,请阅读详细的Apple Library Technical Q&amp; A:

iOS Developer Library Technical Q&A QA1668

答案 5 :(得分:3)

如果您使用MPMusicPlayerController,此处也很重要: 你必须使用:

[MPMusicPlayerController iPodMusicPlayer] 

而不是

[MPMusicPlayerController applicationMusicPlayer] 

此外,如果您不希望自己的应用启动stop music,那么请在此处查看: AVAudioPlayer turns off iPod - how to work around?

答案 6 :(得分:3)

<强>步骤1

在info.plist中进行以下更改

  1. 应用程序不在后台运行:否

  2. 所需的背景模式

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

  3. 第2步 不要忘记在MainViewController.h文件

    中添加以下内容
    1. #import <'AVFoundation/AVAudioPlayer.h>
    2. @interface MainViewController:<'AVAudioPlayerDelegate>

    3. AVAudioPlayer *H_audio_player;

    4. 第3步MainViewController类的播放操作中添加以下代码。

      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;
      

答案 7 :(得分:2)

如果即使将音频设置为plist中的UIBackgroundModes之一,音频会在转到后台时停止,请尝试setting application's audio sessionmedia playback

以下是相关参考: https://developer.apple.com/library/ios/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/Introduction/Introduction.html

以下是关于代码的样子:

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

NSError*setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError];

答案 8 :(得分:2)

我使用下面的代码。它适用于我,并按下音频播放器实例方法的按钮单击。

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

答案 9 :(得分:2)

从所有答案中都缺少此代码来控制用户唤醒设备时的播放器:

- (BOOL)canBecomeFirstResponder {
        return YES;
    }

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

        case UIEventSubtypeRemoteControlPlay:

            [_audioPlayer play];
            break;

        case UIEventSubtypeRemoteControlPause:

            [_audioPlayer pause];
            break;

        default:
            break;
    }
}

你有以下所有选择:

UIEventSubtypeRemoteControlPlay                 = 100,
UIEventSubtypeRemoteControlPause                = 101,
UIEventSubtypeRemoteControlStop                 = 102,
UIEventSubtypeRemoteControlTogglePlayPause      = 103,
UIEventSubtypeRemoteControlNextTrack            = 104,
UIEventSubtypeRemoteControlPreviousTrack        = 105,
UIEventSubtypeRemoteControlBeginSeekingBackward = 106,
UIEventSubtypeRemoteControlEndSeekingBackward   = 107,
UIEventSubtypeRemoteControlBeginSeekingForward  = 108,
UIEventSubtypeRemoteControlEndSeekingForward    = 109,

答案 10 :(得分:1)

在后台播放音频

第1步:只需添加 info.plist 制作一个数组 enter image description here

第二步:

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

第3步:

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

答案 11 :(得分:0)

来自Apple的示例代码: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];
}

我认为以下情况不需要远程控制事件:

AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryMixWithOthers,
                        sizeof(value), &value);