【发布时间】:2016-05-10 17:22:45
【问题描述】:
这是我正在努力解决的一个非常奇怪的现象:
我正在尝试根据特定上下文在单击按钮时播放音频文件。例如,如果条件“A”我会播放某种声音(点击按钮),如果它是“B”我会播放另一种声音。我使用 switch 语句来决定在什么条件下播放什么声音。
问题:即使我得到了正常工作的条件,AVAudioPlayer 总是返回 nil。但是当我对要播放的文件进行硬编码时,它工作得很好。只有当我使用变量来决定“在 switch 语句中”播放哪个声音时,才会播放声音,否则当我使用静态变量而不更改其值时,它可以正常工作。
这是我的代码:
func playSound(Condition: String){
switch Condition {
case "1":
soundName = "1"
case "2":
soundName = "2"
case "3":
soundName = "3"
case "4":
soundName = "4"
case "5":
soundName = "5"
default:
soundName = "default"
}
let pathString = NSBundle.mainBundle().URLForResource(soundName, withExtension: "m4a")?.path //if I type 'let soundName = "1" or Hard code the value' - it will work fine
if let soundFilePath = pathString {
let sound = NSURL.fileURLWithPath(soundFilePath)
do{
audioPlayer = try AVAudioPlayer(contentsOfURL:sound)
audioPlayer.prepareToPlay()
audioPlayer.play()
}catch {
print("Error getting the audio file")
}
} else {
print("Error: Can't find file. Path is nil") // - This is always printed when I use the variable result from the switch
}
}
谁能帮我弄清楚为什么?切换时间是否太长?我怀疑是因为我可以在播放声音之前打印条件的值。提前致谢。
在此处添加更多信息:https://forums.developer.apple.com/message/137380#137380
【问题讨论】:
-
请提供更多代码上下文,例如调用
playSound(condition:)的位置。 -
点击按钮时调用。条件是根据今天几点、几点等因素提供的。
-
好的,等等,你粘贴的两个部分都是
playSound(condition:)函数的一部分吗? -
是的,这是一个功能。所以.. UI 上有一个按钮,当按下这个函数时,它会根据时间播放声音。
-
好了,我更正了格式。它现在显示为单个代码块 - 一个函数。
标签: ios swift audio avaudioplayer nsurl