【发布时间】:2015-03-10 05:08:13
【问题描述】:
当我的应用程序进入后台模式时,我想在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];
});
}
【问题讨论】:
-
@David Karlsson,感谢您的评论。但恐怕问题和答案都在 SWIFT 中。
-
您是否将“应用播放音频”添加到您的 plist 中?
-
是的,我做到了。当我在我的目标中启用
Background Modes时,它会给我一个选项,我在列表中勾选Audio & AirPlay。然后App plays audio自动添加到plist中的Required background modes中。 -
与论坛网站不同,我们不使用“谢谢”、“感谢任何帮助”或Stack Overflow 上的签名。请参阅“Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?。顺便说一句,这是“提前致谢”,而不是“致谢”。
标签: ios objective-c nstimer avaudioplayer