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

时间:2016-02-24 06:59:49

标签: ios swift audio playsound

我正在按照按钮点击播放声音。但是在这里,我想每次点击按钮都会加载声音文件。

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

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

  

无法设置声音,错误= -50。

任何解决方案?

1 个答案:

答案 0 :(得分:0)

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

导入AudioToolbox

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中