gpt4 book ai didi

ios - swift 2 : Can't find audio file path when I use variables as file names

转载 作者:行者123 更新时间:2023-11-30 13:26:22 26 4
gpt4 key购买 nike

这是我正在努力解决的一个非常奇怪的现象:

我正在尝试根据特定上下文单击按钮来播放音频文件。例如,如果条件“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

最佳答案

您需要声明 soundName

func playSound(Condition: String){

var soundName: 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//如果我输入 'let soundName = "1"或对值进行硬编码' - 它将正常工作

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
}

关于ios - swift 2 : Can't find audio file path when I use variables as file names,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37145110/

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