我有这个文件,并希望在另一个类中使用此文件,但这不起作用。我假设这是因为我没有初始化此文件中的AVAudioPlayer
,所以我解决了这个问题,但是出现了一条消息,说"Call can throw, but it is not marked with 'try' and the error is not handled"
我的实现不成功。我不知道如何处理这个问题。你能指出初始化有什么问题,并为我提供一些有效的代码。提前谢谢。
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()
}
}
答案 0 :(得分:2)
我建议使用这种方式初始化你的经理,它不必是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() } }
使用
let manager = SoundManager(fileName: "hello")
manager.playSound()