gpt4 book ai didi

ios - 在后台运行声音并播放音乐

转载 作者:行者123 更新时间:2023-12-02 23:53:45 24 4
gpt4 key购买 nike

我正在构建一个正在运行的应用程序,它通过音频通知用户他们需要每隔几分钟开始运行或开始步行。即使使用 AVAudioPlayer 锁定屏幕,我也能够让声音在后台运行。

这是我所拥有的片段:

View Controller .h

@property (nonatomic, strong) AVAudioPlayer *audioWalk;

View Controller .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];

}

我试图弄清楚如何在不中断后台播放的音乐的情况下播放我的音频。此外,声音需要在后台和屏幕锁定时播放。任何帮助将非常感激!

最佳答案

我能够修复它。这是我在下面所做的。此解决方案允许音频文件在后台运行,即使在锁定屏幕的情况下,也不会中断或暂停来自其他应用程序(尤其是音乐)的音频。

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

}

关于ios - 在后台运行声音并播放音乐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20170799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com