gpt4 book ai didi

ios - AudioServicesCreateSystemSoundID 仅在应用程序中创建一次并从任何地方播放声音

转载 作者:行者123 更新时间:2023-11-28 06:48:28 34 4
gpt4 key购买 nike

我正在做以下事情以在点击按钮时播放声音。但是在这里,我猜它会在我每次点击按钮时加载声音文件。

if let soundURL = NSBundle.mainBundle().URLForResource("notification", withExtension: "mp3") {
var mySound: SystemSoundID = 0;
AudioServicesCreateSystemSoundID(soundURL, &mySound);
AudioServicesPlaySystemSound(mySound);
}

我想做的是在 AppDelegate 中加载一次以上代码,然后从任何其他 VC 调用以下代码:

let systemSoundID: SystemSoundID = 0;
AudioServicesPlaySystemSound(systemSoundID);

每次我想要一个声音。但它会导致控制台显示错误

Failure to setup sound, err = -50.

有什么解决办法吗?

最佳答案

与其添加到 AppDelegate,不如添加一个单独的类可能更简洁。这对我有用:

导入音频工具箱

class PlaySound {

static private var mySound:SystemSoundID = {
// Do it like this so mySound is initialised only when it is first used
var aSound:SystemSoundID = 1000 // a default sound in case we forget the sound file
if let soundURL = NSBundle.mainBundle().URLForResource("Detection", withExtension: "wav") {
AudioServicesCreateSystemSoundID(soundURL, &aSound)
print("Initialised aSound:\(aSound)")
} else {
print("You have forgotten to add your sound file to the app.")
}
return aSound // this value is put into mySound when mySound is first used.
}()

static func play() { AudioServicesPlaySystemSound(mySound) } // play the sound

static func prepare() -> SystemSoundID { return mySound } // call this to preload sound to avoid any delay on first use, if you want
}

然后每当我需要声音的时候,我就写

PlaySound.play()

并且只在第一次使用时设置一次声音。上面的 print 显示了初始化的时间和次数。如果你想避免在第一次使用时设置声音有任何延迟的可能性,你可以调用

PlaySound.prepare()

应用启动时在 AppDelegate 中。

关于ios - AudioServicesCreateSystemSoundID 仅在应用程序中创建一次并从任何地方播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35595342/

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