我想播放音乐,即使应用程序在后台运行.我判断了所有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个文件中做一些更改..

Update

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

- (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相关问答推荐

当我们只能使用 NSObject 时,为什么还要使用 id?

Objective-C,如何获取 UTC 时区的当前日期?

在 iOS 中检测 PAN 手势的方向

Xcode 中架构的重复符号

在 ARC 之后,我应该为调度队列使用什么属性?

pathForResource 返回 null

检测 NSString 的语言

碰撞技术如何运作?

设置数据后调整 UICollectionView 单元格的大小

我应该在 ARC 的 init 方法中引用 self.property 吗?

在 Objective C 中,你能判断一个对象是否具有特定的属性或消息吗?

如何从设置屏幕打开位置服务屏幕?

如何在 UIAlertController 中添加 textField?

遍历 NSString 中所有字符的最有效方法

使用 CocoaPods 时如何向 Xcode 添加自定义项目配置?

writeToFile:atomically: atomically 是什么意思?

通过点击状态栏滚动到 UITableView 的顶部

如何设置字体大小以填充 UILabel 高度?

Facebook SDK 登录永远不会在 iOS 9 上回调我的应用程序

UICollectionView:如何检测滚动何时停止