This is what I have in my singleton:
import AVFoundation
import Foundation
class SharingMusicPlayer {
static let sharingMusicPlayer = SharingMusicPlayer(backgroundMusicPlayer: AVAudioPlayer)
let backgroundMusicPlayer : AVAudioPlayer
private init(backgroundMusicPlayer: AVAudioPlayer) {
self.backgroundMusicPlayer = backgroundMusicPlayer
}
func playMusic() {
// open and play an mp3 file...
}
}
But I am getting this error:
SharingMusicPlayer.swift:12:79: Cannot convert value of type 'AVAudioPlayer.Type' to expected argument type 'AVAudioPlayer'
Here is another post I have investigated but the solution does not appear to apply here:
"Cannot convert value of type 'AVAudioPlayer.Type' to expected argument type"
BTW, I based my singleton pattern on this article:
https://cocoacasts.com/what-is-a-singleton-and-how-to-create-one-in-swift
Does anyone have any suggestions?
UPDATE:
Please note that I realize that I can play a sound in my app using this code:
run(SKAction.playSoundFileNamed("MySound.mp3", waitForCompletion: false))
But I want to play background music in this case so the above doesn’t work.
2
Answers
This is what I came up with, though I am still not sure if this is the right way to do a singleton in swift:
Then this is how I would call the functions to start and stop the music:
Please note that the above buttons are in
SpriteKit
so they are different than the usualUIButton
objects inMain.storyboard
.You are passing it the
type
AVAudioPlayer when you need to pass aninstance
ofAVAudioPlayer
. This should work I guess:Change
to
Update
This is the full code that compiles at my end