当我的应用进入后台模式时,我想在5 seconds
之后播放“音频”。 NSTimer
正确触发。 5秒后我收到了NSLog(@"repeat");
。但是,有些声音无法播放。我在目标中启用了背景模式。我尝试了许多其他解决方案,可以在stackoverflow
中找到,但是没有运气。任何人都可以为我提供正确的解决方案。
在我的appdelegate.h
文件中:
#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;
在我的
appdelegate.m
文件中:#import "AppDelegate.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
@synthesize
musicName,
audioPlayer;
-(void) playAlarmSound
{
musicName = @"note3BreakOf.mp3";
// Construct URL to sound file
NSString *path = [NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath], musicName];
NSURL *soundUrl = [NSURL fileURLWithPath:path];
// Create audio player object and initialize with URL to sound
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self playAlarmSound];
return YES;
}
-(void)methodRunAfterBackground
{
[audioPlayer play];
[timer invalidate];
NSLog(@"repeat");
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UIApplication *app = [UIApplication sharedApplication];
//create new uiBackgroundTask
__block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
//and create new timer with async call:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//run function methodRunAfterBackground
timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(methodRunAfterBackground) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
});
}
最佳答案
您需要将“playsAudio”添加到您的plist并进行设置
setActive:是
beginReceivingRemoteControlEvents
似乎其中一些可能已被弃用,请检查here
在Objective-C中:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
关于ios - 音频不在背景模式下播放,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27901899/