gpt4 book ai didi

ios - iphone 应用程序中的异步声音

转载 作者:行者123 更新时间:2023-11-29 13:19:22 25 4
gpt4 key购买 nike

我使用以下代码在我的应用程序中播放声音,但问题是它会减慢应用程序的速度。如何在不减慢动作的情况下让声音异步发生?

SystemSoundID soundID;
NSString *soundFile = [[NSBundle mainBundle] pathForResource: _sound ofType:@ "wav"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef) [NSURL fileURLWithPath:soundFile], &soundID);
AudioServicesPlaySystemSound(soundID);

最佳答案

在应用程序初始化期间执行 AudioServicesCreateSystemSoundID,或者在用户可以预期/接受一点延迟的其他时间提前执行。可以在后台执行,但要等到结束后才能播放声音。

AudioServicesPlaySystemSound is asynchronous already.

换句话说,要尽早演示如何进行init,appDidFinishLaunching 是最早的机会。使用公共(public)属性使您的声音可用​​于应用程序的其他部分...

// AppDelegate.h, add this inside the @interface
@property (strong, nonatomic) NSArray *sounds;

// AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

NSMutableArray *tempSounds = [NSMutableArray array];

SystemSoundID soundID0;
// you need to initialize _sound0, _sound1, etc. as your resource names
NSString *soundFile0 = [[NSBundle mainBundle] pathForResource: _sound0 ofType:@ "wav"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef) [NSURL fileURLWithPath:soundFile0], &soundID0);

[tempSounds addObject:[NSNumber numberWithInt:soundID0]];

SystemSoundID soundID1;
NSString *soundFile1 = [[NSBundle mainBundle] pathForResource: _sound1 ofType:@ "wav"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef) [NSURL fileURLWithPath:soundFile1], &soundID1);

// SystemSoundID is an int type, so we wrap it in an NSNumber to keep in the array
[tempSounds addObject:[NSNumber numberWithInt:soundID1]];

self.sounds = [NSArray arrayWithArray:tempSounds];

// do anything else you do for app init here

return YES;
}

然后在 SomeViewController.m ...

#import "AppDelegate.h"

// when you want to play a sound (the first one at index 0 in this e.g.)
NSArray *sounds = ((AppDelegate *)[[UIApplication sharedApplication] delegate]).sounds;

AudioServicesPlaySystemSound([sounds[0] intValue]);

关于ios - iphone 应用程序中的异步声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14764994/

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