ios - 音频未在后台模式下播放
<p><p>当我的应用程序进入后台模式时,我想在 <code>5 秒</code> 后播放“音频”。 <code>NSTimer</code> 正确触发。我在 5 秒后收到 <code>NSLog(@"repeat");</code> 。但是,有些音频无法播放。我在我的目标中启用了<strong>背景模式</strong>。我尝试了许多其他解决方案,在 <code>stackoverflow</code> 中找到,但没有运气。任何人都可以为我提供正确的解决方案。 </p>
<p>在我的 <code>appdelegate.h</code> 文件中:</p>
<pre><code>#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
NSTimer* timer;
}
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, strong) NSString *musicName;
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
</code></pre>
<p>在我的 <code>appdelegate.m</code> 文件中:</p>
<pre><code>#import "AppDelegate.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
@synthesize
musicName,
audioPlayer;
-(void) playAlarmSound
{
musicName = @"note3BreakOf.mp3";
// Construct URL to sound file
NSString *path = resourcePath], musicName];
NSURL *soundUrl = ;
// Create audio player object and initialize with URL to sound
audioPlayer = [ initWithContentsOfURL:soundUrl error:nil];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
;
return YES;
}
-(void)methodRunAfterBackground
{
;
;
NSLog(@"repeat");
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UIApplication *app = ;
//create new uiBackgroundTask
__block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
;
bgTask = UIBackgroundTaskInvalid;
}];
//and create new timer with async call:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//run function methodRunAfterBackground
timer = ;
[ addTimer:timer forMode:NSDefaultRunLoopMode];
[ run];
});
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>您需要将“playsAudio”添加到您的 plist 并设置 </p>
<ul>
<li>AVAudioSession sharedInstance 类别为:AVAudioSessionCategoryPlayback </li>
<li>AVAudioSession sharedInstance
setActive:是的</li>
<li>UIApplication sharedApplication
beginReceivingRemoteControlEvents</li>
</ul>
<p>似乎其中一些可能已被弃用,请查看 <a href="https://stackoverflow.com/questions/24393495/playing-a-sound-with-avaudioplayer-swift" rel="noreferrer noopener nofollow">here</a> </p>
<p>在 Objective-C 中:</p>
<pre><code>[ setCategory:AVAudioSessionCategoryPlayback error:nil];
[ setActive: YES error: nil];
[ beginReceivingRemoteControlEvents];
</code></pre></p>
<p style="font-size: 20px;">关于ios - 音频未在后台模式下播放,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/27901899/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/27901899/
</a>
</p>
页:
[1]