【问题标题】:Sound is not playing when using AVFoundation in Swift在 Swift 中使用 AVFoundation 时不播放声音
【发布时间】:2022-01-23 01:18:37
【问题描述】:

我正在尝试为我的游戏播放一些背景音乐。我没有收到错误,但音乐本身根本没有播放。我已经检查了 iOS 模拟器和 MacBook 上的声音,但我什么也听不见,所以我想知道是否有人知道我的代码有什么问题。我什至尝试过声明var musicPlayer: AVAudioPlayer!var musicPlayer: AVAudioPlayer?,但它仍然不起作用。我目前使用的是 Xcode 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 */}
        }
    }

【问题讨论】:

  • 调试。 if let musicPath 成功了吗?

标签: ios swift sprite-kit avfoundation background-music


【解决方案1】:

将您的音频播放器代码移动到SKScene.didMove(to view: SKView) - 即在 MenuScene 中而不是在您的视图控制器中

【讨论】:

  • 我试过了,还是不行,有没有其他方法?
猜你喜欢
  • 2015-12-25
  • 1970-01-01
  • 2014-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-14
  • 1970-01-01
  • 2014-12-26
相关资源
最近更新 更多