Swift 3:根据字符串变量

时间:2017-03-23 19:43:45

标签: ios swift xcode

所以我看到在Swift 3中播放音频的方式是

do {
    audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "name", ofType: "mp3")!))
    audioPlayer.prepareToPlay()
    audioPlayer.play()
}
catch {
print(error)
}

但是我想要一个名为 string 的变量,而不是设置的“name”字符串,它可能是对应于不同文件名的100个不同字符串之一。 Swift不允许这样做,只需将 string 代替“name”,那么修复是什么?

2 个答案:

答案 0 :(得分:0)

我不明白为什么这不起作用:

var audioPlayer: AVAudioPlayer!
let string = "name"
if let path = Bundle.main.path(forResource: string, ofType: "mp3") {
    let url = URL(fileURLWithPath: path)
    do {
        audioPlayer = try AVAudioPlayer(contentsOf: url)
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    }
    catch {
        print(error)
    }
}

无论如何,调用字符串变量字符串可能不是最好的做法。也许你应该把它称为“资源”,“resourceName”或“fileName”?

答案 1 :(得分:0)

我只想使用这样的函数,并传入声音的名称和类型。

func playSound(name: String, type: String) {
    var Sound: AVAudioPlayer? = {
        let url = URL(fileURLWithPath: Bundle.main.path(forResource: "\(name)", ofType: "\(type)")!)
        do {
            let player = try AVAudioPlayer(contentsOf: url, fileTypeHint: nil)
            return player
        }
        catch {return nil} } ()
}

称之为

playSound(name: "The Sound", type: "mp4")

希望这有助于! :) 如果有,请竖起大拇指:D