Reputation: 43
I am trying to play some background music for my game. I am not getting an error, but the music itself is not playing at all. I have checked the sound on the iOS Simulator and on my MacBook but I cannot hear anything, so I was wondering if anyone knew what is wrong with my code. I have even tried declaring var musicPlayer: AVAudioPlayer!
and var musicPlayer: AVAudioPlayer?
but it still does not work. I am currently using Xcode version 13.1.
import AVFoundation
class GameViewController: UIViewController {
var musicPlayer = AVAudioPlayer()
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
// Build the menu scene
let menuScene = MenuScene()
let skView = self.view as? SKView
// Ignore drawing order of child nodes in order to increase performance
skView?.ignoresSiblingOrder = true
// Size the scene to fit the view exactly
menuScene.size = view.bounds.size
// Show the menu
skView?.presentScene(menuScene)
// Start background music
if let musicPath = Bundle.main.path(forResource: "backgroundMusic.m4a", ofType: nil) {
let url = URL(fileURLWithPath: musicPath)
do {
musicPlayer = try AVAudioPlayer(contentsOf: url)
musicPlayer.numberOfLoops = -1
musicPlayer.prepareToPlay()
musicPlayer.play()
}
catch {/* Couldn't load music file */}
}
}
Upvotes: 0
Views: 345
Reputation: 1294
move your audio player code into SKScene.didMove(to view: SKView)
- i.e. in MenuScene not in your view controller
Upvotes: 0