繁体   English   中英

在 Swift 中使用 AVFoundation 时不播放声音

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM