[英]Sound is not playing when using AVFoundation in Swift
導入 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 */}
}
}
我正在嘗試為我的游戲播放一些背景音樂。 我沒有收到錯誤,但音樂本身根本沒有播放。 我檢查了 IOS 模擬器和我的 MacBook 上的聲音,但我什么也聽不見,所以我想知道是否有人知道我的代碼有什么問題。 我什至嘗試過聲明
var musicPlayer: AVAudioPlayer!
和var musicPlayer: AVAudioPlayer?
但它仍然不起作用。 我目前正在使用 Xcode 版本 13.1
將您的音頻播放器代碼移動到SKScene.didMove(to view: SKView)
- 即在 MenuScene 中不在您的視圖中 controller
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.