AVQueuePlayer花了很多时间播放第一首歌

时间:2017-02-02 09:47:18

标签: ios swift avqueueplayer

下面是我使用一些网址播放AVQueueplayer的代码,但播放第一首歌需要大约10-20秒。我有10首歌曲,但为了参考并将其缩小,我只留了一首歌。

    arrSongs = ["http://radiotaj.com/music/1/1836.mp3"]
    let index = 0
    let strSong = (arrSongs.object(at: index)) as? String
    playerItem = AVPlayerItem(url: URL(string:strSong!)!
    let playerItems = [playerItem]
    player = AVQueuePlayer(items : playerItems as! [AVPlayerItem])
    player.play()

以下是我已经尝试过的解决方案

  1. 添加CMTime
  2. 让它暂停并再次播放
  3. 如果文件是本地文件,它的工作正常。
  4. 非常感谢任何帮助。

    谢谢!

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码,它适用于我。这是没有Alamofire的版本(用实际链接替换yourURL):

override func viewDidLoad() {
    super.viewDidLoad()
    downloadFileFromURL(url: URL(string: yourURL)!)
}

 func play(url: URL) {
    do {
        let songData = try Data(contentsOf: url, options: NSData.ReadingOptions.mappedIfSafe)
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)
        player = try AVAudioPlayer(data: songData, fileTypeHint: AVFileTypeAppleM4A)
        player!.prepareToPlay()
        player!.play()
    } catch {
        print(error)
    }
}


func downloadFileFromURL(url: URL) {
    var downloadTask = URLSessionDownloadTask()
    downloadTask = URLSession.shared.downloadTask(with: url, completionHandler: {
        customURL, response, error in

        self.play(url: customURL!)
    })
    downloadTask.resume()
}

使用Alamofire更快,它基本上将文件下载到Documents文件夹并从这里播放(不要忘记安装Alamofire并在类import Alamofire之外输入:

func play(url: URL) {
    do {
        let songData = try Data(contentsOf: url, options: NSData.ReadingOptions.mappedIfSafe)
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)
        player = try AVAudioPlayer(data: songData, fileTypeHint: AVFileTypeAppleM4A)
        player!.prepareToPlay()
        player!.play()
    } catch {
        print(error)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    let destination: DownloadRequest.DownloadFileDestination = { _, _ in
        var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        documentsURL.appendPathComponent("song."+"mp3")
        return (documentsURL, [.removePreviousFile])
    }

    Alamofire.download(yourURL, to: destination).response { response in
        if response.destinationURL != nil {
            songURL = response.destinationURL!
            self.play(url: songURL!)
        }
    }
}