ryohei ryohei - 7 months ago 19
Swift Question

How to initialize AVAudioPlayer in Swift

I have this file and want to use this file in another class, but this does not work. I assume that this is because I have not initialized the

AVAudioPlayer
in this file, so I tackled with this, but a message appeared, saying
"Call can throw, but it is not marked with 'try' and the error is not handled"
My implementation was unsuccessful. I have no idea how to deal with this. Could you point out what is wrong with the initialization and provide me with some code that works. Thanks in advance.

class SoundManager: AVAudioPlayer {
var _Sound: AVAudioPlayer!

override init() {
let url = NSBundle.mainBundle().URLForResource("rain", withExtension: "wav")
super.init(contentsOfURL: url!)
}

func playSound() {


if (url == nil) {
print("Could not find the file \(_Sound)")
}

do {
_Sound = try AVAudioPlayer(contentsOfURL: url!, fileTypeHint: nil)

}
catch let error as NSError { print(error.debugDescription)

}
if _Sound == nil {
print("Could not create audio player")
}
_Sound.prepareToPlay()
_Sound.numberOfLoops = -1
_Sound.play()
}

}

Answer

I recommend to use this way init you manager, It does not have to be subclass of AVAudioPlayer.

class SoundManager {
    var _Sound: AVAudioPlayer!
    var url: NSURL?

    /**
     init with file name

     - parameter fileName: fileName

     - returns: SoundManager
     */
    init(fileName: String) {
        url = NSBundle.mainBundle().URLForResource(fileName, withExtension: "wav")
    }

    func playSound() {
        if (url == nil) {
            print("Could not find the file \(_Sound)")
        }

        do {
            _Sound = try AVAudioPlayer(contentsOfURL: url!, fileTypeHint: nil)

        }
        catch let error as NSError { print(error.debugDescription)

        }
        if _Sound == nil {
            print("Could not create audio player")
        }
        _Sound.prepareToPlay()
        _Sound.numberOfLoops = -1
        _Sound.play()
    }
}

Use let manager = SoundManager(fileName: "hello") manager.playSound()

Comments