gpt4 book ai didi

iOS 在执行其他操作之前播放声音

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

在 iOS 应用程序中执行其他操作之前,我需要播放 3 秒左右的简短声音(如倒计时蜂鸣声)。

用例如下:

用户单击一个按钮...发出哔哔声(使用 AudioServicesPlaySystemSound 发出简单的哔哔声...然后运行该方法的其余部分。

我似乎找不到在播放音调时阻止我的方法的方法。

我试过以下方法:

[self performSelector:@selector(playConfirmationBeep) onThread:[NSThread currentThread] withObject:nil waitUntilDone:YES];

但是在执行该方法的其余部分时,音调会同步播放。

我在上面的调用中遗漏了什么?

最佳答案

AudioServicesPlaySystemSound 是异步的,因此您不能阻塞它。您要做的是让音频服务在播放结束时通知您。您可以通过 AudioServicesAddSystemSoundCompletion 实现。

这是一个 C 级 API,所以有点难看,但你可能想要这样的东西:

// somewhere, a C function like...
void audioServicesSystemSoundCompleted(SystemSoundID ssID, void *clientData)
{
[(MyClass *)clientData systemSoundCompleted:ssID];
}

// meanwhile, in your class' init, probably...
AudioServicesAddSystemSoundCompletion(
soundIDAsYoullPassToAudioServicesPlaySystemSound,
NULL, // i.e. [NSRunloop mainRunLoop]
NULL, // i.e. NSDefaultRunLoopMode
audioServicesSystemSoundCompleted,
self);

// in your dealloc, to avoid a dangling pointer:
AudioServicesRemoveSystemSoundCompletion(
soundIDAsYoullPassToAudioServicesPlaySystemSound);

// somewhere in your class:
- (void)systemSoundCompleted:(SystemSoundID)sound
{
if(sound == soundIDAsYoullPassToAudioServicesPlaySystemSound)
{
NSLog(@"time to do the next thing!");
}
}

如果您真的想在播放声音时阻止 UI,并且假设您的类是一个 View Controller ,您可能应该在相关期间禁用 self.view.userInteractionDisable。您绝对不想做的是阻塞主运行循环;这将阻止重要的系统事件,如低内存警告通过,因此可能导致您的应用程序被强制退出。您可能还想遵守设备旋转之类的规则。

关于iOS 在执行其他操作之前播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11978524/

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