如何在 Swift 中初始化 AVAudioPlayer

How to initialize AVAudioPlayer in Swift

我有这个文件,想在另一个 class 中使用这个文件,但这不起作用。我假设这是因为我没有在这个文件中初始化 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()
}

}

我建议使用这种方式初始化你的管理器,它不必是 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()