我正在使用AudioKit来设置声音播放器。我的声音引擎设置在具有以下功能的单例中:
override func viewDidLoad() {
super.viewDidLoad()
configureAudioPlayer()
}
func configureAudioPlayer() {
leftPanner = AKPanner(leftOscillator)
rightPanner = AKPanner(rightOscillator)
//Set up rain and rainPlayer
do {
rain = try AKAudioFile(readFileName: "rain.wav")
rainPlayer = try AKAudioPlayer(file: rain, looping: true, deferBuffering: false, completionHandler: nil)
} catch {
print(error)
}
mixer = AKMixer(leftPanner, rightPanner, rainPlayer)
envelope = AKAmplitudeEnvelope(mixer)
AudioKit.output = envelope
AudioKit.start()
}
func startPlaying() {
leftOscillator.start()
rightOscillator.start()
rainPlayer.start() //CRASHES HERE AND SAYS NIL OPTIONAL VALUE
envelope.start()
soundIsPlaying = true
}
在一个单独的视图控制器中,我有一个播放按钮,按下时会调用以下函数:
let player = AudioPlayer.sharedPlayer
@IBAction func playSound(_ sender: Any) {
player.leftOscillator.frequency = 220
player.rightOscillator.frequency = 230
if player.soundIsPlaying == false {
player.startPlaying()
} else {
player.stopPlaying()
}
}
当我按下此按钮时,应用程序崩溃并说rainPlayer 为零。我是不是设置错了什么?当我在 configureAudioPlayer() 函数中配置 rainPlayer 时,为什么它会为零?
更新:将单例移动到它自己的继承自 NSObject 的类中并在其 init() 函数中调用 configureAudioPlayer() 解决了我的问题。viewDidLoad() 方法中的 configureAudioPlayer() 从未被调用过。