0

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

Caspar B
  • 499
  • 1
  • 6
  • 19
  • 1
    `public class SKTAudio` => `public class SKTAudio: AVAudioPlayerDelegate`? – Larme Oct 10 '18 at 13:33
  • @Larme Throws error: `Type 'SKTAudio' does not conform to protocol ` – Caspar B Oct 10 '18 at 13:36
  • Because you didn't implemented all the necessary delegate methods? Doesn't XCode suggest you a fix for that? A stub for instance? – Larme Oct 10 '18 at 13:38
  • @Larme Thank you. Did some digging and found out I had to have: `public class SKTAudio: NSObject, AVAudioPlayerDelegate` – Caspar B Oct 10 '18 at 13:41
  • If you'd like to write an answer, I could accept it – Caspar B Oct 10 '18 at 13:42
  • Possible duplicate of [Cannot assign a value of type ViewController to a value of type UITextFieldDelegate?](https://stackoverflow.com/questions/29605496/cannot-assign-a-value-of-type-viewcontroller-to-a-value-of-type-uitextfielddeleg) – Larme Oct 10 '18 at 13:42

0 Answers0