音频不在 SwiftUI 中播放

Audio not playing in SwiftUI

我在调用函数时无法播放音频文件。

我正在使用 AVAudioPlayer 尝试按照此处的说明播放文件: https://www.hackingwithswift.com/example-code/media/how-to-play-sounds-using-avaudioplayer 在视图中按下按钮后,它会调用一个函数来播放声音,但据我所知,什么也没有播放。没有抛出任何错误,并且找到了文件。该应用程序还会在按下按钮时使用语音合成器,并且播放效果很好。

我查看了堆栈溢出并按照此处的说明进行操作:

但是按下按钮时仍然没有播放音频。

这是函数:

    func playSound() {
        var sound = AVAudioPlayer()

        if let path = Bundle.main.path(forResource: "TryAgain", ofType: "wav") {
            do {
                sound = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
                print("Playing sound")
                sound.play()
            } catch {
                print( "Could not find file")
            }
        }

这里是 class:

class Player: BindableObject {

    let willChange = PassthroughSubject<Player, Never>()

    var isPlaying: Bool = false {
        willSet {
            willChange.send(self)
        }
    }

    func playSound() {
        var sound = AVAudioPlayer()

        if let path = Bundle.main.path(forResource: "TryAgainWav", ofType: "wav") {
            do {
                sound = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
                print("Playing sound")
                sound.play()
            } catch {
                print( "Could not find file")
            }
        }
    }
}

更新:不确定这是否有帮助,但我使用 IB 而不是 SwiftUI 构建了它,并注意到当我单击按钮播放音频文件时,控制台中打印了相同的消息:

2019-07-22 11:29:41.075568-0700 PlaySoundPrac[13952:46549155] [插件] AddInstanceForFactory: 没有工厂注册 id F8BB1C28-BAE8-11D6-9C31-00039315CD46

如有任何帮助,我们将不胜感激

我自己还很新,但我会尽力而为。如果将 AVAudioPlayer 的声明移到函数外会发生什么?例如:

import Combine

class Player: ObservableObject {

    var sound: AVAudioPlayer! 

    let willChange = PassthroughSubject<Player, Never>()

    var isPlaying: Bool = false {
        willSet {
            willChange.send(self)
        }
    }

    func playSound() {

        if let path = Bundle.main.path(forResource: "TryAgainWav", ofType: "wav") {
            do {
                sound = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
                print("Playing sound")
                sound.play()
            } catch {
                print( "Could not find file")
            }
        }
    }
}

试试这个,让我知道它是否有效!谢谢

我遇到了一个问题,音频无法在 iOS 13 Simulator in Xcode 11.5 中播放,而在 Xcode SwiftUI 预览和物理设备中没问题。