我在调用该函数时遇到了播放音频文件的问题。
我正在使用 AVAudioPlayer 尝试按照此处的说明播放文件:https : //www.hackingwithswift.com/example-code/media/how-to-play-sounds-using-avaudioplayer 按下按钮后视图,它调用 func 来播放声音,但据我所知,没有播放任何内容。没有抛出错误,并且找到了文件。当按下按钮时,该应用程序还使用语音合成器,播放效果很好。
我环顾了堆栈溢出并按照此处的说明进行操作: 在 SwiftUI 应用程序中放置音频播放代码的位置
但是当按下按钮时仍然没有播放音频。
这是函数:
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")
}
}
Run Code Online (Sandbox Code Playgroud)
这是课程:
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")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
更新:不确定这是否有帮助,但我使用 IB 而不是 SwiftUI 构建了它,并注意到当我单击按钮播放音频文件时,控制台中会打印相同的消息:
2019-07-22 11:29:41.075568-0700 PlaySoundPrac[13952:46549155] [插件] AddInstanceForFactory:没有为 ID F8BB1C28-BAE8-11D6-9C31-000369315 注册的工厂
任何帮助将不胜感激
小智 10
我自己也很新,但我会尽力而为。如果将 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")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
试试这个,让我知道它是否有效!谢谢。
| 归档时间: |
|
| 查看次数: |
4065 次 |
| 最近记录: |