如何在swift3中播放和停止AVAudioPlayer?

时间:2016-11-28 18:12:25

标签: swift avaudioplayer

我正在开发一个swift的音频播放器,我需要2个按钮(播放和停止)来控制它。我使用了以下代码:

 override func viewDidLoad() {
    super.viewDidLoad()

 let urlstring = "http://radio.spainmedia.es/wp-content/uploads/2015/12/tailtoddle_lo4.mp3"
    let url = NSURL(string: urlstring)
    print("the url = \(url!)")
    downloadFileFromURL(url: url!)

                             }

  func downloadFileFromURL(url:NSURL) {
    var downloadTask:URLSessionDownloadTask
    downloadTask = URLSession.shared.downloadTask(with: url as URL, completionHandler: { (URL, response, error) -> Void in

        self.play(url: URL! as NSURL)

    })

    downloadTask.resume()

                                      }

 func play(url:NSURL) {
    print("playing \(url)")

    do {
        self.SoundPlayer = try AVAudioPlayer(contentsOf: url as URL)
        SoundPlayer.prepareToPlay()
        SoundPlayer.volume = 1.0
        SoundPlayer.play()
    } catch let error as NSError {
        //self.player = nil
        print(error.localizedDescription)
    } catch {
        print("AVAudioPlayer init failed")
    }

                       }

@IBAction func Play(_ sender: Any) {

    SoundPlayer.play()

}


@IBAction func Stop(_ sender: Any) {

     SoundPlayer.stop()

}

基本上,当用户打开应用程序时,mp3音频文件会自动启动。因此我创建了2个额外的按钮,Start和Stop,我想用它们控制这个音频播放器。你能不能建议我怎么做,因为现在他们没有连接音频播放器,当我点击它们时没有动作。

1 个答案:

答案 0 :(得分:0)

如果您的目标是在播放文件时播放该文件,请从URL获取数据,然后将其传递给AVAudioPlayer

if let theURL = URL(string: "http://radio.spainmedia.es/wp-content/uploads/2015/12/tailtoddle_lo4.mp3") {
    if let data = try? Data(contentsOf: theURL){
        if let audioPlayer = try? AVAudioPlayer(data: data) {
        print("Done")
        audioPlayer.play()
        } else {
        print("Noo")
        }

    }
}

AVAudioPlayer(contentsOf: url as URL)经常无法从远程位置获取数据。

您还可以查看其他选项,例如AVPlayer来播放文件

how can i play remote .mp3 file in my ios application?