我使用以下代码在我的应用中播放声音,但问题是它会降低应用的速度。如何在不减慢动作的情况下使声音异步发生?
SystemSoundID soundID;
NSString *soundFile = [[NSBundle mainBundle] pathForResource: _sound ofType:@ "wav"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef) [NSURL fileURLWithPath:soundFile], &soundID);
AudioServicesPlaySystemSound(soundID);
答案 0 :(得分:1)
在应用程序初始化期间执行AudioServicesCreateSystemSoundID,或者在用户可以预期/接受一点延迟的某个其他时间点执行。它可以在后台执行,但声音无法播放直到它完成。
AudioServicesPlaySystemSound is asynchronous already.
换句话说,为了演示init如何提前,appDidFinishLaunching是最早的机会。使用公共财产将您的声音提供给应用程序的其他部分......
// 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]);