斯威夫特3:AVAudioPlayer没有播放声音
问题描述:
我在它与我的音频播放器的结构体:斯威夫特3:AVAudioPlayer没有播放声音
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中点击它播放。这在模拟和设备上都会失败。任何帮助,将不胜感激。
答
看起来像你的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)
}
}
}
}
,看一下在Xcode右侧面板中。选择文件时,应检查目标成员资格。如果没有,请检查并重试。 –
我在发帖前检查过。但谢谢你的建议。 – PruitIgoe
_注意_你应该避免在'audioURL!'中包含''隐含的解包可选''。 Bundle.main提供了一个url方法,它返回一个可选的url使用,而不是'if let audioUrl = Bundle.main.url(forResource:fileName,withExtension:fileExtension)' – Lamar