1

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

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);

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

声音设置失败,err = -50。

任何解决方案?

4

1 回答 1

1

与其添加到 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 中。

于 2016-02-24T09:13:36.990 回答