音频无法在SwiftUI中播放

时间:2019-07-22 21:07:13

标签: swift swiftui

调用该函数时,播放音频文件时遇到问题。

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

我环顾了堆栈溢出,并按照此处的说明进行操作: Where to place code for audio playback in a SwiftUI app

但是当按下按钮时仍无法播放音频。

这是功能:

    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 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] [plugin] AddInstanceForFactory:没有为id F8BB1C28-BAE8-11D6-9C31-00039315CD46注册的工厂

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

我遇到一个问题,即Xcode 11.5的iOS 13 Simulator上的音频无法在Xcode SwiftUI预览版和物理设备中正常播放。

答案 1 :(得分:-1)

我本人还很新,但我会尽力而为。如果将AVAudioPlayer的声明移到函数之外会怎样?例如:

class Player: BindableObject {

    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")
            }
        }
    }
}

尝试一下,让我知道它是否有效!谢谢。