即使应用程序在后台运行,我也想播放音乐。我检查了所有 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/