邊播邊下有三套左右實現思路,本文使用AVPlayer + AVURLAsset實現。git
實現邊下邊播,其實就是手動實現AVPlayer的上列播放過程。github
OK,邊播邊下的原理知道了,咱們能夠正式寫代碼了~建議先從文末連接處把Demo下載下來,對着Demo我們慢慢道來~swift
共須要三個類:數組
先從小弟提及緩存
如上文所說,小弟是負責作髒活累活的。 負責和服務器鏈接、向服務器請求數據、把請求回來的數據寫到本地緩存文件、把寫完的緩存文件移到持久化目錄去服務器
private func _initialTmpFile() { do { try NSFileManager.defaultManager().createDirectoryAtPath(StreamAudioConfig.audioDicPath, withIntermediateDirectories: true, attributes: nil) } catch { print("creat dic false -- error:\(error)") } if NSFileManager.defaultManager().fileExistsAtPath(StreamAudioConfig.tempPath) { try! NSFileManager.defaultManager().removeItemAtPath(StreamAudioConfig.tempPath) } NSFileManager.defaultManager().createFileAtPath(StreamAudioConfig.tempPath, contents: nil, attributes: nil) }
/** 鏈接服務器,請求數據(或拼range請求部分數據)(此方法中會將協議頭修改成http) - parameter offset: 請求位置 */ public func set(URL url: NSURL, offset: Int) { func initialTmpFile() { try! NSFileManager.defaultManager().removeItemAtPath(StreamAudioConfig.tempPath) NSFileManager.defaultManager().createFileAtPath(StreamAudioConfig.tempPath, contents: nil, attributes: nil) } _updateFilePath(url) self.url = url self.offset = offset // 若是創建第二次請求,則需初始化緩衝文件 if taskArr.count >= 1 { initialTmpFile() } // 初始化已下載文件長度 downLoadingOffset = 0 // 把stream://xxx的頭換成http://的頭 let actualURLComponents = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) actualURLComponents?.scheme = "http" guard let URL = actualURLComponents?.URL else {return} let request = NSMutableURLRequest(URL: URL, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: 20.0) // 若非從頭下載,且視頻長度已知且大於零,則下載offset到videoLength的範圍(拼request參數) if offset > 0 && videoLength > 0 { request.addValue("bytes=\(offset)-\(videoLength - 1)", forHTTPHeaderField: "Range") } connection?.cancel() connection = NSURLConnection(request: request, delegate: self, startImmediately: false) connection?.setDelegateQueue(NSOperationQueue.mainQueue()) connection?.start() }
public func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) { isFinishLoad = false guard response is NSHTTPURLResponse else {return} // 解析頭部數據 let httpResponse = response as! NSHTTPURLResponse let dic = httpResponse.allHeaderFields let content = dic["Content-Range"] as? String let array = content?.componentsSeparatedByString("/") let length = array?.last // 拿到真實長度 var videoLength = 0 if Int(length ?? "0") == 0 { videoLength = Int(httpResponse.expectedContentLength) } else { videoLength = Int(length!)! } self.videoLength = videoLength //TODO: 此處須要修改成真實數據格式 - 從字典中取 self.mimeType = "video/mp4" // 回調 recieveVideoInfoHandler?(task: self, videoLength: videoLength, mimeType: mimeType!) // 鏈接加入到任務數組中 taskArr.append(connection) // 初始化文件傳輸句柄 fileHandle = NSFileHandle.init(forWritingAtPath: StreamAudioConfig.tempPath) }
public func connection(connection: NSURLConnection, didReceiveData data: NSData) { // 尋址到文件末尾 self.fileHandle?.seekToEndOfFile() self.fileHandle?.writeData(data) self.downLoadingOffset += data.length self.receiveVideoDataHandler?(task: self) // print("線程 - \(NSThread.currentThread())") // 注意,這裏用子線程有問題 let queue = dispatch_queue_create("com.azen.taskConnect", DISPATCH_QUEUE_SERIAL) dispatch_async(queue) { // // 尋址到文件末尾 // self.fileHandle?.seekToEndOfFile() // self.fileHandle?.writeData(data) // self.downLoadingOffset += data.length // self.receiveVideoDataHandler?(task: self) // let thread = NSThread.currentThread() // print("線程 - \(thread)") }
public func connectionDidFinishLoading(connection: NSURLConnection) { func tmpPersistence() { isFinishLoad = true let fileName = url?.lastPathComponent // let movePath = audioDicPath.stringByAppendingPathComponent(fileName ?? "undefine.mp4") let movePath = StreamAudioConfig.audioDicPath + "/\(fileName ?? "undefine.mp4")" _ = try? NSFileManager.defaultManager().removeItemAtPath(movePath) var isSuccessful = true do { try NSFileManager.defaultManager().copyItemAtPath(StreamAudioConfig.tempPath, toPath: movePath) } catch { isSuccessful = false print("tmp文件持久化失敗") } if isSuccessful { print("持久化文件成功!路徑 - \(movePath)") } } if taskArr.count < 2 { tmpPersistence() } receiveVideoFinishHanlder?(task: self) }
其餘方法包括斷線重連以及公開一個cancel方法cancel掉和服務器的鏈接session
祕書要乾的最主要的事情就是響應播放器老大的號令,全部方法都是圍繞着播放器老大來的。祕書須要遵循AVAssetResourceLoaderDelegate協議才能被錄用。app
這個方法實際上是播放器在說:小祕呀,我想要這段音頻文件。你能如今給我仍是等等給我啊?
必定要返回:true,告訴播放器,我等等給你。
而後,立馬找本地緩存文件裏有木有這段數據,有把數據拿給播放器,若是木有,則派祕書的小弟向服務器要。
具體實現代碼有點多,這裏就不所有貼出來了。能夠去看看文末的Demo記得賞顆星喲~async
/** 播放器問:是否應該等這requestResource加載完再說? 這裏會出現不少個loadingRequest請求, 須要爲每一次請求做出處理 - parameter resourceLoader: 資源管理器 - parameter loadingRequest: 每一小塊數據的請求 - returns: <#return value description#> */ public func resourceLoader(resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool { // 添加請求到隊列 pendingRequset.append(loadingRequest) // 處理請求 _dealWithLoadingRequest(loadingRequest) print("----\(loadingRequest)") return true }
/** 播放器關閉了下載請求 播放器關閉一箇舊請求,都會發起一到多個新請求,除非已經播放完畢了 - parameter resourceLoader: 資源管理器 - parameter loadingRequest: 待關請求 */ public func resourceLoader(resourceLoader: AVAssetResourceLoader, didCancelLoadingRequest loadingRequest: AVAssetResourceLoadingRequest) { guard let index = pendingRequset.indexOf(loadingRequest) else {return} pendingRequset.removeAtIndex(index) }
負責調度全部播放器的,負責App中的一切涉及音頻播放的事件
唔。。犯個小懶。。代碼直接貼上來咯~要趕不上樓下的538路公交啦~~謝謝你們體諒哦~ide
public class MusicPlayerManager: NSObject { // public var status public var currentURL: NSURL? { get { guard let currentIndex = currentIndex, musicURLList = musicURLList where currentIndex < musicURLList.count else {return nil} return musicURLList[currentIndex] } } /**播放狀態,用於須要獲取播放器狀態的地方KVO*/ public var status: ManagerStatus = .Non /**播放進度*/ public var progress: CGFloat { get { if playDuration > 0 { let progress = playTime / playDuration return progress } else { return 0 } } } /**已播放時長*/ public var playTime: CGFloat = 0 /**總時長*/ public var playDuration: CGFloat = CGFloat.max /**緩衝時長*/ public var tmpTime: CGFloat = 0 public var playEndConsul: (()->())? /**強引用控制器,防止被銷燬*/ public var currentController: UIViewController? // private status private var currentIndex: Int? private var currentItem: AVPlayerItem? { get { if let currentURL = currentURL { let item = getPlayerItem(withURL: currentURL) return item } else { return nil } } } private var musicURLList: [NSURL]? // basic element public var player: AVPlayer? private var playerStatusObserver: NSObject? private var resourceLoader: RequestLoader = RequestLoader() private var currentAsset: AVURLAsset? private var progressCallBack: ((tmpProgress: Float?, playProgress: Float?)->())? public class var sharedInstance: MusicPlayerManager { struct Singleton { static let instance = MusicPlayerManager() } // 後臺播放 let session = AVAudioSession.sharedInstance() do { try session.setActive(true) } catch { print(error) } do { try session.setCategory(AVAudioSessionCategoryPlayback) } catch { print(error) } return Singleton.instance } public enum ManagerStatus { case Non, LoadSongInfo, ReadyToPlay, Play, Pause, Stop } } // MARK: - basic public funcs extension MusicPlayerManager { /** 開始播放 */ public func play(musicURL: NSURL?) { guard let musicURL = musicURL else {return} if let index = getIndexOfMusic(music: musicURL) { // 歌曲在隊列中,則按順序播放 currentIndex = index } else { putMusicToArray(music: musicURL) currentIndex = 0 } playMusicWithCurrentIndex() } public func play(musicURL: NSURL?, callBack: ((tmpProgress: Float?, playProgress: Float?)->())?) { play(musicURL) progressCallBack = callBack } public func next() { currentIndex = getNextIndex() playMusicWithCurrentIndex() } public func previous() { currentIndex = getPreviousIndex() playMusicWithCurrentIndex() } /** 繼續 */ public func goOn() { player?.rate = 1 } /** 暫停 - 可繼續 */ public func pause() { player?.rate = 0 } /** 中止 - 沒法繼續 */ public func stop() { endPlay() } } // MARK: - private funcs extension MusicPlayerManager { private func putMusicToArray(music URL: NSURL) { if musicURLList == nil { musicURLList = [URL] } else { musicURLList!.insert(URL, atIndex: 0) } } private func getIndexOfMusic(music URL: NSURL) -> Int? { let index = musicURLList?.indexOf(URL) return index } private func getNextIndex() -> Int? { if let musicURLList = musicURLList where musicURLList.count > 0 { if let currentIndex = currentIndex where currentIndex + 1 < musicURLList.count { return currentIndex + 1 } else { return 0 } } else { return nil } } private func getPreviousIndex() -> Int? { if let currentIndex = currentIndex { if currentIndex - 1 >= 0 { return currentIndex - 1 } else { return musicURLList?.count ?? 1 - 1 } } else { return nil } } /** 從頭播放音樂列表 */ private func replayMusicList() { guard let musicURLList = musicURLList where musicURLList.count > 0 else {return} currentIndex = 0 playMusicWithCurrentIndex() } /** 播放當前音樂 */ private func playMusicWithCurrentIndex() { guard let currentURL = currentURL else {return} // 結束上一首 endPlay() player = AVPlayer(playerItem: getPlayerItem(withURL: currentURL)) observePlayingItem() } /** 本地不存在,返回nil,不然返回本地URL */ private func getLocationFilePath(url: NSURL) -> NSURL? { let fileName = url.lastPathComponent