使用AVAudioplayer在后台播放音乐

lee*_*ena 38 iphone objective-c avaudioplayer ipad

即使应用程序进入后台,我也想播放音乐.我检查了所有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];
Run Code Online (Sandbox Code Playgroud)

Meh*_*tri 79

我通过引用iOS应用程序后台任务解决了这个问题

并对.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];
}
Run Code Online (Sandbox Code Playgroud)

  • OBS:后台播放在模拟器中不起作用:) (8认同)

gho*_*ron 32

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

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
Run Code Online (Sandbox Code Playgroud)

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

添加上面的代码就这样,即使应用程序在后台,我的音频也会启动.


Ala*_*art 6

您需要将'audio'设置为Info.plist中的UIBackgroundModes之一.Apple有关于该问题的文档.


san*_*alp 5

将此行写入 plist 以进行后台运行...

<key>UIBackgroundModes</key>
      <array>
              <string>audio</string>
      </array>
Run Code Online (Sandbox Code Playgroud)

在你想使用的地方写下这段代码

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];
Run Code Online (Sandbox Code Playgroud)