gpt4 book ai didi

ios - 音频不在后台模式下播放

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:02:03 27 4
gpt4 key购买 nike

当我的应用进入后台模式时,我想在 5 秒 后播放“音频”。 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 并设置

  • AVAudioSession sharedInstance 类别为:AVAudioSessionCategoryPlayback
  • AVAudioSession 共享实例设置事件:是
  • UIApplication sharedApplicationbeginReceivingRemoteControlEvents

似乎其中一些可能已被弃用,请查看 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/

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