gpt4 book ai didi

swift 3 : AVAudioPlayer not playing sound

转载 作者:行者123 更新时间:2023-11-28 12:15:50 24 4
gpt4 key购买 nike

我有一个结构,里面有我的音频播放器:

struct MT_Audio {

func playAudio(_ fileName:String, _ fileExtension:String, _ atVolume:Float) {
var audioPlayer = AVAudioPlayer()
if let audioPath = Bundle.main.path(forResource: fileName, ofType: fileExtension) {
let audioURL = URL(string:audioPath)
do {
audioPlayer = try AVAudioPlayer(contentsOf: audioURL!)
audioPlayer.volume = atVolume
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch {
print(error)
}
}
}
}

//I'm calling it in viewDidLoad like this:

guard let fileURL = Bundle.main.url(forResource:"heartbeat-01a", withExtension: "mp3")
else {
print("can't find file")
return
}

let myAudioPlayer = MT_Audio() //<--RESOLVED THE ISSUE BY MAKING THIS A PROPERTY OF THE VIEWCONTROLLER
myAudioPlayer.playAudio("heartbeat-01a", "mp3", 1.0)

因为它不会在守卫上崩溃和烧毁,所以我知道文件就在那里。尝试后我也设置了一个断点,我正在播放音频播放器。当我转到实际文件并在 Xcode 中单击它时,它会播放。这在 sim 卡和设备上都失败了。任何帮助,将不胜感激。

最佳答案

看起来您的 audioPlayer 仅存储在您的 playAudio 函数中。

尝试将 audioPlayer 作为类中的变量,如下所示:

struct MT_Audio {

var audioPlayer: AVAudioPlayer?

mutating func playAudio(_ fileName:String, _ fileExtension:String, _ atVolume:Float) {

// is now member of your struct -> var audioPlayer = AVAudioPlayer()
if let audioPath = Bundle.main.path(forResource: fileName, ofType: fileExtension) {
let audioURL = URL(string:audioPath)
do {
let audioPlayer = try AVAudioPlayer(contentsOf: audioURL!)
audioPlayer.volume = atVolume
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch {
print(error)
}
}
}
}

关于 swift 3 : AVAudioPlayer not playing sound,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46645151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com