[英]Swift - AVAudioPlayer not playing sound
I have a sound called speeding.mp3
and I am trying to make a AVAudioPayer instance with it by doing this in the root of the class: 我有一个名为
speeding.mp3
的声音,并且我试图通过在类的根目录中执行此操作来创建一个AVAudioPayer实例:
let speedingAudioPlayer = try! AVAudioPlayer(contentsOfURL: NSBundle.mainBundle().URLForResource("speeding", withExtension: "mp3")!)
Then when I run the app it throws an error but I don't know why this is happening. 然后,当我运行该应用程序时,它会引发错误,但我不知道为什么会这样。 The
speeding.mp3
file is in the Bundle Resources drop down in Build Phases so it should find it fine. speeding.mp3
文件位于“构建阶段”的“捆绑资源”下拉列表中,因此应该可以正常使用。 If I try to print out the URL in the simulator and paste it into Safari it loads and plays the file like normal. 如果我尝试在模拟器中打印出URL并将其粘贴到Safari中,它将像正常情况一样加载并播放文件。 I am importing AVFoundation into the class and the framework into the project.
我将AVFoundation导入类,并将框架导入项目。
Use this code snippet to debug your error, 使用此代码段调试错误,
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")
}
I found another question where the var is placed outside the class because otherwise it would be deallocated by the phone. 我发现了另一个问题,将var放在类之外,因为否则它将通过电话释放。
AVAudioPlayer Object Sound Not Playing - Swift AVAudioPlayer对象声音未播放-迅捷
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")
}
}
}
Try this code for playing the sound. 尝试使用此代码播放声音。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.