ios - 快速创建和播放声音

所以我想做的是在 swift 中创建并播放一个声音,当我按下一个按钮时就会播放,我知道如何在 Objective-C 中做到这一点,但是有人知道如何在 Swift 中做到这一点吗?

Objective-C 应该是这样的:

NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"mysoundname" ofType:@"wav"]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &mySound);

然后我会玩它:

AudioServicesPlaySystemSound(Explosion);

有人知道我该怎么做吗?

最佳答案

这与其他一些答案类似,但可能更“Swifty”:

// Load "mysoundname.wav"
if let soundURL = Bundle.main.url(forResource: "mysoundname", withExtension: "wav") {
    var mySound: SystemSoundID = 0
    AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
    // Play
    AudioServicesPlaySystemSound(mySound);
}

请注意,这是一个重现问题中代码效果的简单示例。您需要确保 import AudioToolbox,此外,此类代码的一般模式是在您的应用启动时加载您的声音,并将它们保存在 SystemSoundID某个地方的实例变量,在整个应用程序中使用它们,然后在使用完它们后调用 AudioServicesDisposeSystemSoundID

https://stackoverflow.com/questions/24043904/

相关文章:

iphone - 我在 iPhone 上的日期字符串中使用什么格式的字符串来表示毫秒?

ios - 正确使用 beginBackgroundTaskWithExpirationHandle

objective-c - libxml/tree.h 没有这样的文件或目录

objective-c - NSString 带\n 或换行符

ios - 如何检查 View Controller 是否以模态方式呈现或推送到导航堆栈上?

iphone - 即使图像较小,如何使 UITableViewCell 的 ImageView 成为

objective-c - iOS 6 中用于完成 block 的 dispatch_get_cur

iphone - 为 UIView 子类加载 Nib 的正确方法

objective-c - 如何将 int 转换为 NSString?

ios - 键盘出现时如何滚动 UIScrollView?