[英]Swift - AVAudioPlayer not playing sound
我有一个名为speeding.mp3
的声音,并且我试图通过在类的根目录中执行此操作来创建一个AVAudioPayer实例:
let speedingAudioPlayer = try! AVAudioPlayer(contentsOfURL: NSBundle.mainBundle().URLForResource("speeding", withExtension: "mp3")!)
然后,当我运行该应用程序时,它会引发错误,但我不知道为什么会这样。 speeding.mp3
文件位于“构建阶段”的“捆绑资源”下拉列表中,因此应该可以正常使用。 如果我尝试在模拟器中打印出URL并将其粘贴到Safari中,它将像正常情况一样加载并播放文件。 我将AVFoundation导入类,并将框架导入项目。
使用此代码段调试错误,
if let URL = NSBundle.mainBundle().URLForResource("speeding", withExtension: "mp3") {
do {
let speedingAudioPlayer = try AVAudioPlayer(contentsOfURL: URL)
} catch let error as NSError {
print(error.localizedDescription)
}
} else {
print("No such file exist")
}
我发现了另一个问题,将var放在类之外,因为否则它将通过电话释放。
import UIKit
import AVFoundation
class CustomAudioPlayer {
var audioPlayer : AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
playSound("sound_file_name")
}
func playSound(soundName: String)
{
let alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundName, ofType: "mp3")!)
do{
audioPlayer = try AVAudioPlayer(contentsOfURL:alertSound)
audioPlayer.prepareToPlay()
audioPlayer.play()
}catch {
print("Error getting the audio file")
}
}
}
尝试使用此代码播放声音。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.