未使用此方法播放音频。 play()函数正在执行,没有任何错误。 请帮助
var audioPlayer = AVAudioPlayer()
let path = Bundle.main.path(forResource: "a", ofType: "mp3")
@State var isPlaying : Bool = false
var body: some View {
Button(action: {
self.isPlaying.toggle()
let url = URL(fileURLWithPath: self.path!)
do {
self.audioPlayer = try AVAudioPlayer(contentsOf: url)
self.audioPlayer.prepareToPlay()
self.audioPlayer.play()
}catch {
print("Eror")
}
}, label: {
if isPlaying {
Image(systemName: "pause")
.font(Font.system(.largeTitle).bold())
}else {
Image(systemName: "play.fill")
.font(Font.system(.largeTitle).bold())
}
})
}
答案 0 :(得分:1)
音频文件在吗?请选择项目,转到“构建阶段”选项卡,然后在“复制捆绑资源”下,您必须看到音频文件。如果在那里,那么问题就出在这里。
我尝试了您的代码,它播放了声音,然后崩溃了。我这样更改它以使其正常工作
@State var audioPlayer:AVAudioPlayer?
@State var isPlaying : Bool = false
var body: some View {
Button(action: {
if let path = Bundle.main.path(forResource: "a", ofType: ".mp3") {
self.audioPlayer = AVAudioPlayer()
self.isPlaying.toggle()
let url = URL(fileURLWithPath: path)
do {
self.audioPlayer = try AVAudioPlayer(contentsOf: url)
self.audioPlayer?.prepareToPlay()
self.audioPlayer?.play()
}catch {
print("Error")
}
}
}, label: {
您是否考虑过将音频模型与用户界面分离?如果将其放入单独的Swift文件
,它将使您的代码更加清晰import AVFoundation
class Sounds {
static var audioPlayer:AVAudioPlayer?
static func playSounds(soundfile: String) {
if let path = Bundle.main.path(forResource: soundfile, ofType: nil){
do{
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
audioPlayer?.prepareToPlay()
audioPlayer?.play()
}catch {
print("Error")
}
}
}
}
只有一行可以在用户界面中使用
var body: some View {
Button(action: {
self.isPlaying.toggle()
Sounds.playSounds(soundfile: "0.wav")
}, label: {