音频未使用此方法播放。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())
}
})
}
音频文件在那里吗?请选择项目,转到“构建阶段”选项卡,然后在“复制捆绑资源”下,您必须看到音频文件。如果在那里,那么问题就出在此。
我尝试了您的代码,它播放了声音,然后崩溃了。我像这样更改它以使其正常工作
@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: {