I am trying to trigger a function when a song finishes playing. Here is my audio player class:
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
}
}
However, the code won't compile, and the line player.delegate = self
returns this error:
Cannot assign value of type 'SKTAudio' to type 'AVAudioPlayerDelegate?'
And gives the option to:
Insert ' as! AVAudioPlayerDelegate'
This compiles, but, upon running, crashes and returns the following in console:
Could not cast value of type 'Scene.SKTAudio' (0x102ebf7b0) to 'AVAudioPlayerDelegate'
Where playBackgroundMusic()
is called within Scene. I have no clue what to do at this point, I've tried to follow various other posts but nobody seems to face an issue with the player.delegate = self
line. Thank you