Swift 3:从服务器流式传输MP3文件

时间:2017-05-26 12:26:04

标签: swift mp3 avplayer

我正在尝试从网址流式传输示例mp3。这是一个非常小的示例文件。但是,当我按下播放按钮时没有任何反应。好吧,没有声音播放。

我对Swift很新,而且非常像菜鸟,所以这里是完整的View Controller,因为我不确定你可能需要什么。

    import UIKit
    import AVKit
    import AVFoundation
    import Foundation

    class ViewController: UIViewController {

        @IBAction func playButton(_ sender: Any) {

            print("pressed")
            let urlstring = "http://cdn.mos.musicradar.com/audio/samples/80s-heat-demos/AM_Eighties08_85-01.mp3"
            let url = NSURL(string: urlstring)
            print("the url = \(url!)")
            downloadFileFromURL(url: url!)

        }



        override func viewDidLoad() {
            // Do any additional setup after loading the view
        }



        func downloadFileFromURL(url:NSURL){
            weak var weakSelf = self
            var downloadTask:URLSessionDownloadTask
            downloadTask = URLSession.shared.downloadTask(with: url as URL, completionHandler: { (URL, response, error) -> Void in
            print("URL = \(URL)")
            weakSelf!.plays(url: URL! as URL)

            })

            downloadTask.resume()

        }



        func plays(url:URL) {

            print("playing \(url)")

            do {

                var playerItem = AVPlayerItem(url: url as URL)

                player = AVPlayer(url : url)

                player.volume = 1.0

                player.play()

            } catch let error as NSError {



                print(error.localizedDescription)

            } catch {

                print("AVAudioPlayer init failed")

            }

        }

    }

在我的控制台中我得到了这个:

  

     

网址= http://cdn.mos.musicradar.com/audio/samples/80s-heat-demos/AM_Eighties08_85-01.mp3

     

网址=可选(文件:///private/var/mobile/Containers/Data/Application/C255E8F4-DDBA-43BB-BC33-AF71C08BBDFD/tmp/CFNetworkDownload_tm0O8v.tmp)

     

播放文件:///private/var/mobile/Containers/Data/Application/C255E8F4-DDBA-43BB-BC33-AF71C08BBDFD/tmp/CFNetworkDownload_tm0O8v.tmp

     

网址=可选(文件:///private/var/mobile/Containers/Data/Application/C255E8F4-DDBA-43BB-BC33-AF71C08BBDFD/tmp/CFNetworkDownload_J1f2LF.tmp)

     

播放文件:///private/var/mobile/Containers/Data/Application/C255E8F4-DDBA-43BB-BC33-AF71C08BBDFD/tmp/CFNetworkDownload_J1f2LF.tmp

任何人都可以帮我解决这个问题吗?我只是希望能够在服务器上点击按钮而不是在本地播放此声音。

1 个答案:

答案 0 :(得分:1)

请尝试将此代码用于播放器功能。

func plays(url:URL) {

        print("playing \(url)")

        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)

            player = try AVAudioPlayer(contentsOf: url)
            guard let player = player else { return }

            player.play()
        } catch let error as NSError {



            print(error.localizedDescription)

        } catch {

            print("AVAudioPlayer init failed")

        }

    }