当我的应用程序进入后台模式时,我想在5 seconds之后播放一个“音频”。NSTimer正确触发。我得到的NSLog(@"repeat");在5秒后。但是,有些声音是怎么不播放的。我在目标中启用了背景模式。我尝试了许多其他的解决方案,在这里发现在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];
});
}发布于 2015-01-12 12:29:39
您需要将"playsAudio“添加到您的plist中并设置
似乎其中一些可能被否决了,请检查here
在目标C中:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];发布于 2015-01-17 06:02:16
当我的应用程序进入后台模式时,我想在5秒后播放一个“音频”。
好吧,你不能。如果你的应用程序在进入后台时没有积极播放音频,那么当它进入后台时,它就会被挂起--不管你的背景设置如何。你的计时器停止了,应用程序就睡着了。
(许多人通过在应用程序进入后台时播放“静音”轨道来解决这个问题,这样应用程序就可以在后台运行。)
发布于 2015-04-10 05:35:32
您可以通过使应用程序活动的背景来实现这一点。我正在我的应用程序中做这个。我使用位置管理器api使应用程序在后台活动。然后用定时器在后台播放音频。您可以使用此链接https://github.com/voyage11/Location使应用程序在background.Hope中活动,这将有所帮助。
https://stackoverflow.com/questions/27901899
复制相似问题