objective-c - 使用 AVAudioplayer 在后台播放音乐

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

最佳答案

我通过引用 iOS Application Background tasks 解决了这个问题

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

更新

在你的 Controller View 中编写这段代码确实像这样加载方法

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

关于objective-c - 使用 AVAudioplayer 在后台播放音乐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7619794/

相关文章:

objective-c - Xcode 构建失败 "Undefined symbols for architecture x86_64"

ios - Xcode 无法启动应用程序。进程启动失败 : 4294967295

iPhone4 UI 元素大小(以像素为单位)?

iphone - 如何创建自动启动 iTunes 的 App Store 链接?

ios - 从行中删除表附件指示器

ios - JayData/Phonegap 适用于 iPad 模拟器但不适用于 iPad 设备

ios - 如何让手机进入增强现实 (iOS)

objective-c - 动画没有通过另一个 View Controller 执行

iPhone - CGBitmapContextCreateImage 泄漏,还有其他人遇到这个问题吗?

iphone - 如何轻松地将 iPhone 应用程序转换为通用应用程序?