当我按下按钮时,我需要播放声音(在资产中)。我收到错误:“找不到音频文件” 我上了这门课:
import SwiftUI
import AVFoundation
class AudioPlayerViewModel: ObservableObject {
var audioPlayer: AVAudioPlayer?
@Published var isPlaying = false
init() {
if let sound = Bundle.main.path(forResource: "thesound", ofType: "mp3") {
do {
self.audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound))
} catch {
print("AVAudioPlayer could not be instantiated.")
}
} else {
print("Audio file could not be found.")
}
}
func playOrPause() {
guard let player = audioPlayer else { return }
if player.isPlaying {
player.pause()
isPlaying = false
} else {
player.play()
isPlaying = true
}
}
}
我在 ContentView 中得到了这个按钮:
Button(action: {
audioPlayerViewModel.playOrPause()
}) {
Image(audioPlayerViewModel.isPlaying ? "pause" : "play")
.resizable()
.scaledToFit()
.frame(width: 80, height: 80)
.foregroundColor(.white)
谢谢!
我尝试将
inDirectory: "Assets"
添加到 if let sound = Bundle.main.path(forResource: "thesound", ofType: "mp3", inDirectory: "Assets")
中,但没有帮助
试试这个:
if let sound = Bundle.main.url(forResource: "thesound", withExtension: "mp3")