Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preloading asset for faster loading #4

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 79 additions & 16 deletions SwiftAudioEx/Classes/AVPlayerWrapper/AVPlayerWrapper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ class AVPlayerWrapper: AVPlayerWrapperProtocol {
let playerTimeObserver: AVPlayerTimeObserver
let playerItemNotificationObserver: AVPlayerItemNotificationObserver
let playerItemObserver: AVPlayerItemObserver

let additionalAVPlayer: AVPlayer
public var preloadedAssets: [String: AVAsset]

/**
True if the last call to load(from:playWhenReady) had playWhenReady=true.
*/
Expand All @@ -58,6 +60,9 @@ class AVPlayerWrapper: AVPlayerWrapperProtocol {
self.playerItemNotificationObserver = AVPlayerItemNotificationObserver()
self.playerItemObserver = AVPlayerItemObserver()

self.additionalAVPlayer = AVPlayer();
self.preloadedAssets = [String: AVAsset]();

self.playerObserver.delegate = self
self.playerTimeObserver.delegate = self
self.playerItemNotificationObserver.delegate = self
Expand Down Expand Up @@ -186,7 +191,13 @@ class AVPlayerWrapper: AVPlayerWrapperProtocol {
recreateAVPlayer()
}

self._pendingAsset = AVURLAsset(url: url, options: options)
if (self.preloadedAssets[url.absoluteString] != nil){
self._pendingAsset = self.preloadedAssets[url.absoluteString]
self.loadAssetIntoPlayer();
return
} else {
self._pendingAsset = AVURLAsset(url: url, options: options)
}

if let pendingAsset = _pendingAsset {
self._state = .loading
Expand All @@ -203,20 +214,7 @@ class AVPlayerWrapper: AVPlayerWrapperProtocol {
let isPendingAsset = (self._pendingAsset != nil && pendingAsset.isEqual(self._pendingAsset))
switch status {
case .loaded:
if isPendingAsset {
let currentItem = AVPlayerItem(asset: pendingAsset, automaticallyLoadedAssetKeys: [Constants.assetPlayableKey])
currentItem.preferredForwardBufferDuration = self.bufferDuration
self.avPlayer.replaceCurrentItem(with: currentItem)

// Register for events
self.playerTimeObserver.registerForBoundaryTimeEvents()
self.playerObserver.startObserving()
self.playerItemNotificationObserver.startObserving(item: currentItem)
self.playerItemObserver.startObserving(item: currentItem)
for format in pendingAsset.availableMetadataFormats {
self.delegate?.AVWrapper(didReceiveMetadata: pendingAsset.metadata(forFormat: format))
}
}
self.loadAssetIntoPlayer();
break

case .failed:
Expand All @@ -236,6 +234,25 @@ class AVPlayerWrapper: AVPlayerWrapperProtocol {
})
}
}

func loadAssetIntoPlayer() {
if let pendingAsset = _pendingAsset {

let isPendingAsset = (self._pendingAsset != nil && pendingAsset.isEqual(self._pendingAsset))

if isPendingAsset {
let currentItem = AVPlayerItem(asset: pendingAsset, automaticallyLoadedAssetKeys: [Constants.assetPlayableKey])
currentItem.preferredForwardBufferDuration = self.bufferDuration
self.avPlayer.replaceCurrentItem(with: currentItem)

// Register for events
self.playerTimeObserver.registerForBoundaryTimeEvents()
self.playerObserver.startObserving()
self.playerItemNotificationObserver.startObserving(item: currentItem)
self.playerItemObserver.startObserving(item: currentItem)
}
}
}

func load(from url: URL, playWhenReady: Bool, initialTime: TimeInterval? = nil, options: [String : Any]? = nil) {
_initialTime = initialTime
Expand Down Expand Up @@ -319,6 +336,52 @@ extension AVPlayerWrapper: AVPlayerObserverDelegate {
break
}
}

func cancelPreload(item: AudioItem) {
let url = item.getSourceUrl();
self.preloadedAssets[url]?.cancelLoading();
self.preloadedAssets[url] = nil;
}

func cancelAllPreloads() {
for asset in self.preloadedAssets {
if (self.preloadedAssets[asset.key] != nil){
self.preloadedAssets[asset.key]?.cancelLoading();
self.preloadedAssets[asset.key] = nil;
}
}
}

func preload(item: AudioItem) {
let urlString = item.getSourceUrl();
let url = URL(string: urlString);

let options = (item as? AssetOptionsProviding)?.getAssetOptions()
let asset = AVURLAsset(url:url!, options: options)
let keys = ["playable", "tracks", "duration"];

asset.loadValuesAsynchronously(forKeys: keys, completionHandler: {
var _: NSError? = nil

for key in keys {
let status = asset.statusOfValue(forKey: key, error: nil)
if status == AVKeyValueStatus.failed {
return
}
}

if( self.preloadedAssets[urlString] == nil){
let playerItem = AVPlayerItem(asset: asset);
self.additionalAVPlayer.replaceCurrentItem(with: playerItem)

self.additionalAVPlayer.play();
self.additionalAVPlayer.pause();
DispatchQueue.main.async {
self.preloadedAssets[urlString] = asset;
}
}
});
}

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import Foundation
import AVFoundation


protocol AVPlayerWrapperProtocol: class {
protocol AVPlayerWrapperProtocol: AnyObject {

var state: AVPlayerWrapperState { get }

Expand Down Expand Up @@ -52,5 +52,10 @@ protocol AVPlayerWrapperProtocol: class {
func load(from url: URL, playWhenReady: Bool, options: [String: Any]?)

func load(from url: URL, playWhenReady: Bool, initialTime: TimeInterval?, options: [String: Any]?)


func preload(item: AudioItem)

func cancelAllPreloads()

func cancelPreload(item: AudioItem)
}
20 changes: 19 additions & 1 deletion SwiftAudioEx/Classes/AudioPlayer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,25 @@ public class AudioPlayer: AVPlayerWrapperDelegate {
}
enableRemoteCommands(forItem: item)
}


/**
Preload item.
*/
public func preload(item: AudioItem) {
self.wrapper.preload(item: item);
}

/**
cancel preload item.
*/
public func cancelPreload(item: AudioItem) {
self.wrapper.cancelPreload(item: item);
}

public func cancelAllPreloads() {
self.wrapper.cancelAllPreloads();
}

/**
Toggle playback status.
*/
Expand Down
8 changes: 8 additions & 0 deletions SwiftAudioEx/Classes/QueuedAudioPlayer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -231,4 +231,12 @@ public class QueuedAudioPlayer: AudioPlayer, QueueManagerDelegate {
func onReceivedFirstItem() {
self.event.queueIndex.emit(data: (nil, 0))
}

public func preloadNext() {
let nextItems = queueManager.nextItems

if nextItems.count > 0 {
self.preload(item: nextItems[0])
}
}
}