adamcichy / SwiftySound

SwiftySound is a simple library that lets you play sounds with a single line of code.
MIT License
1.24k stars 98 forks source link

volume control hassles #43

Closed artangco closed 5 years ago

artangco commented 5 years ago

Trying to do volume control when playing but the only way to do that is through creating a new instance that I then have to keep track of since if it goes out of scope it doesn't play. Perhaps I'm doing it wrong. Ideally I would like to do something like Sound.play(url: url, withVolume:0.3 ....

Is this possible?

adamcichy commented 5 years ago

Creating an instance is currently the only option to control the volume. However, you could overcome this with a simple wrapper for your sounds, like the following:

struct Sounds {

    static var globalVolume: Float = 0.5 {
        didSet {
            mySound1?.volume = globalVolume
            //add other sounds here
        }
    }

    static var mySound1: Sound? = {
        if let url = Bundle.main.url(forResource: "myFile", withExtension: "wav") {
            let sound = Sound(url: url)
            sound?.volume = Sounds.globalVolume
            return sound
        }
        return nil
    }()

    //add more sounds here
}

Then the usage is as simple as this:

    Sounds.mySound1?.play()

And to change the volume:

   Sounds.globalVolume = 0.6
artangco commented 5 years ago

Thank you. I made a wrapper.