首页 文章

如何播放下载的音频文件swift

提问于
浏览
0

我有2个音频文件的变体,第一个嵌入,第二个我从服务器下载 .
第一个varian工作得很好 . 但是当我从服务器获取音频文件时没有播放并获得错误 .

我得到路径:

file:///var/mobile/Containers/Data/Application/24656EA9-6F1F-4C0F-A6FE-5D457908A80D/Documents/Dumont.mp3

并试图发挥

func playMusic(filename: String) {
    let url = NSBundle.mainBundle().URLForResource(filename, withExtension: "mp3")
    guard let newURL = url else {
        print("Could not find file: \(filename)")
        return
    }
    do {
        player = try AVAudioPlayer(contentsOfURL: newURL)
        player!.numberOfLoops = -1
        player!.prepareToPlay()
        player!.play()
    } catch let error as NSError {
        print(error.description)
    }
}

如何在swift 2.3中播放这个音频文件?

Platform iOS >8., Swift 2.3

1 回答

  • 1

    嘿愚蠢的家伙谁为你做出了回答:

    if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
      let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent("Dumont.mp3")
        do {
            player = try AVAudioPlayer(contentsOfURL: path)
            player!.numberOfLoops = -1
            player!.prepareToPlay()
            player!.play()
          } catch let error as NSError {
             print(error.description)
          }
    

    这段代码播放下载歌曲!

相关问题