我正在尝试在歌曲播放完毕时触发功能。这是我的音频播放器类:
import AVFoundation
public class SKTAudio {
public var backgroundMusicPlayer: AVAudioPlayer?
public func playBackgroundMusic(filename: String) {
let url = Bundle.main.url(forResource: filename, withExtension: nil)
if (url == nil) {
print("Could not find file: \(filename)")
return
}
var error: NSError? = nil
do {
backgroundMusicPlayer = try AVAudioPlayer(contentsOf: url!)
} catch let error1 as NSError {
error = error1
backgroundMusicPlayer = nil
}
if let player = backgroundMusicPlayer {
player.delegate = self
player.prepareToPlay()
player.play()
} else {
print("Could not create audio player: \(error!)")
}
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer,
// Do stuff
}
}
但是,代码将无法编译,并且行player.delegate = self
返回此错误:
无法将类型“ SKTAudio”的值分配给类型 “ AVAudioPlayerDelegate?”
并提供以下选项:
插入'as! AVAudioPlayerDelegate'
这会编译,但是在运行时会崩溃并在控制台中返回以下内容:
无法将类型为'Scene.SKTAudio'(0x102ebf7b0)的值转换为 “ AVAudioPlayerDelegate”
在场景中调用playBackgroundMusic()
的位置。我目前不知道该怎么办,我已经尝试关注其他各种帖子,但是似乎没有人遇到player.delegate = self
行的问题。谢谢