1

I use the following code to play the sounds in my app, but the problem is that it slows down the app. How can I make the sounds happen asynchronously without slowing down the actions?

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

1 回答 1

1

在应用程序初始化期间执行 AudioServicesCreateSystemSoundID,或者在用户可以预期/接受一点延迟的某个时间点提前执行。它可以在后台执行,但在完成之前无法播放声音。

AudioServicesPlaySystemSound 已经是异步的。

换句话说,为了演示如何尽早进行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]);
于 2013-02-08T03:14:46.757 回答