Swifty Sounds not playing wav file

Viewed 145

I am using the Swifty Sounds cocoa pod and I am unable to play the sound. Here is the function I am calling to play the sound:

    func playSound() {
//        Sound.play(file: "ding.wav")
        
        duckVolume()
        guard let fileUrl = Bundle.main.path(forResource: "ding", ofType: "wav") else {
            print("cannot find file")
            return
        }
        guard let sound = Sound(url: URL(fileURLWithPath: fileUrl)) else {
            print("cant play sound")
            return
        }
        print("playing sound")
        
        Sound.enabled = true
        Sound.category = .playAndRecord
        sound.play()
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
            self.UnduckVolume()
        }
    }

The console prints "playing sound" which indicates that it is finding the correct file, yet the sound is not being played. Interestingly, the first line of the function which is commented out has no problem playing the sound. However, using that function disables me from controlling the volume, and thus I can't use it.

Any help would be appreciated. Thanks!

1 Answers

You need to declare the Sound outside the calling function (I don't know why is that, help me with your comments). The following code should work:

class AnyClass {
    private dogSound : Sound? // declare here
    private catSound : Sound? // declare here

    private func getUrlFromFileName(fileName: String) -> URL {
        let path = Bundle.main.path(forResource: fileName, ofType:nil)!
        return URL(fileURLWithPath: path)
    }
    
    func playDogSound() {
        dogSound = Sound(url: getUrlFromFileName(fileName: "dog.mp3"))
        dogSound?.play()
    }

    func playCatSound() {
        catSound = Sound(url: getUrlFromFileName(fileName: "cat.mp3"))
        catSound?.play()
    }
}
Related