我正在构建一个正在运行的应用程序,通过音频通知用户他们需要开始运行或每隔几分钟开始步行。即使使用AVAudioPlayer上的锁定屏幕,我也可以让声音在后台运行。
以下是我所拥有的片段:
ViewController.h
@property (nonatomic, strong) AVAudioPlayer *audioWalk;
ViewController.m
- (void)viewDidLoad{
[super viewDidLoad];
// Walk Audio File
NSString *soundFile2 = [[NSBundle mainBundle] pathForResource:@"Walk" ofType:@"wav"];
audioWalk = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:soundFile2] error:nil];
// Load the audio into memory
[audioWalk prepareToPlay];
// Permit the timer to run in the background
bgTask = 0;
UIApplication *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
}];
// Prevent the application from going to sleep while it is running
[UIApplication sharedApplication].idleTimerDisabled = YES;
// Starts recieving remote control events and is the first responder
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
// Plays audio
[audioWarmup play];
}
我正在试图弄清楚如何播放我的音频而不会中断在后台播放的音乐。此外,声音需要在后台和屏幕锁定时播放。任何帮助将不胜感激!
答案 0 :(得分:0)
我能够解决它。这是我在下面做的。此解决方案允许音频文件在后台运行,即使使用锁定屏幕,也不会中断或暂停来自其他应用程序(特别是音乐)的音频。
- (void)viewDidLoad{
[super viewDidLoad];
// Play audio even if lock screen is on, the with options allows audio from other applications to play without interruption
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error: nil];
[[AVAudioSession sharedInstance] setActive: YES error:nil];
// Walk Audio File
NSString *soundFile2 = [[NSBundle mainBundle] pathForResource:@"Walk" ofType:@"wav"];
audioWalk = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:soundFile2] error:nil];
// Load the audio into memory
[audioWalk prepareToPlay];
// Permit the timer to run in the background
bgTask = 0;
UIApplication *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
}];
// Prevent the application from going to sleep while it is running
[UIApplication sharedApplication].idleTimerDisabled = YES;
// Starts receiving remote control events and is the first responder
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
// Plays audio
[audioWarmup play];
}