Iphone AVAudioPlayer在后台播放
根据我们的要求,我们需要播放声音,即使应用程序是在后台。我们使用Iphone AVAudioPlayer在后台播放,iphone,ios,avaudioplayer,background-process,Iphone,Ios,Avaudioplayer,Background Process,根据我们的要求,我们需要播放声音,即使应用程序是在后台。我们使用[AVAudioPlayer Play]播放声音 如果应用程序在前台,它就可以工作。但若应用程序在后台,我们也在音乐播放器中播放歌曲,然后控制转到[AVAudioPlayer Play]语句,则不会发生任何事情 我们已经浏览了很多链接,在plist中添加了后台模式,还添加了[[UIApplication sharedApplication]beginReceivingRemoteControlEvents]但事情没有解决 请建议是否
[AVAudioPlayer Play]
播放声音
如果应用程序在前台,它就可以工作。但若应用程序在后台,我们也在音乐播放器中播放歌曲,然后控制转到[AVAudioPlayer Play]
语句,则不会发生任何事情
我们已经浏览了很多链接,在plist中添加了后台模式,还添加了[[UIApplication sharedApplication]beginReceivingRemoteControlEvents]代码>但事情没有解决
请建议是否还有其他选择。要在后台播放音频,只需添加您的信息。plist制作如下数组
并将其检查到真实设备而不是模拟器中要在后台播放音频,只需添加您的信息。plist制作如下数组
并将其检查到真实设备中,而不是在模拟器中只需在初始化AVAudioPlayer
实例的位置添加以下三行代码:
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"mySong" ofType:@"mp3"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
// These lines need to be added:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[audioPlayer play];
只需在初始化AVAudioPlayer
实例的位置添加以下三行:
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"mySong" ofType:@"mp3"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
// These lines need to be added:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[audioPlayer play];
试试这个
AppDelegate.m
- (void)applicationDidEnterBackground:(UIApplication *)application
{
__block UIBackgroundTaskIdentifier task = 0;
task=[application beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"Expiration handler called %f",[application backgroundTimeRemaining]);
[application endBackgroundTask:task];
task=UIBackgroundTaskInvalid;
}];
}
试试这个
AppDelegate.m
- (void)applicationDidEnterBackground:(UIApplication *)application
{
__block UIBackgroundTaskIdentifier task = 0;
task=[application beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"Expiration handler called %f",[application backgroundTimeRemaining]);
[application endBackgroundTask:task];
task=UIBackgroundTaskInvalid;
}];
}
可能的重复可能的重复