From 3cb20452c7d14a405f84cb82e4fb704abebc417b Mon Sep 17 00:00:00 2001 From: Arkadiusz Fal Date: Mon, 30 May 2022 17:36:26 +0200 Subject: [PATCH] Load audio and video together with one command with MPV --- Model/Player/Backends/MPVBackend.swift | 38 ++++++++++++++------------ Model/Player/Backends/MPVClient.swift | 12 ++++++-- 2 files changed, 30 insertions(+), 20 deletions(-) diff --git a/Model/Player/Backends/MPVBackend.swift b/Model/Player/Backends/MPVBackend.swift index 630ec1cf..0d726b92 100644 --- a/Model/Player/Backends/MPVBackend.swift +++ b/Model/Player/Backends/MPVBackend.swift @@ -153,28 +153,30 @@ final class MPVBackend: PlayerBackend { self.stop() - if let url = stream.singleAssetURL { - self.onFileLoaded = { - updateCurrentStream() - startPlaying() + DispatchQueue.main.async { [weak self] in + guard let self = self else { + return } - self.client.loadFile(url, time: time) { [weak self] _ in - self?.isLoadingVideo = true - } - } else { - self.onFileLoaded = { [weak self] in - DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { - self?.client.addAudio(stream.audioAsset.url) { _ in - updateCurrentStream() - startPlaying() - } + if let url = stream.singleAssetURL { + self.onFileLoaded = { + updateCurrentStream() + startPlaying() } - } - self.client.loadFile(stream.videoAsset.url, time: time) { [weak self] _ in - self?.isLoadingVideo = true - self?.pause() + self.client.loadFile(url, time: time) { [weak self] _ in + self?.isLoadingVideo = true + } + } else { + self.onFileLoaded = { [weak self] in + updateCurrentStream() + startPlaying() + } + + self.client.loadFile(stream.videoAsset.url, audio: stream.audioAsset.url, time: time) { [weak self] _ in + self?.isLoadingVideo = true + self?.pause() + } } } } diff --git a/Model/Player/Backends/MPVClient.swift b/Model/Player/Backends/MPVClient.swift index 60710d57..2be25d91 100644 --- a/Model/Player/Backends/MPVClient.swift +++ b/Model/Player/Backends/MPVClient.swift @@ -103,13 +103,21 @@ final class MPVClient: ObservableObject { } } - func loadFile(_ url: URL, time: CMTime? = nil, completionHandler: ((Int32) -> Void)? = nil) { + func loadFile(_ url: URL, audio: URL? = nil, time: CMTime? = nil, completionHandler: ((Int32) -> Void)? = nil) { var args = [url.absoluteString] + var options = [String]() + if let time = time { args.append("replace") - args.append("start=\(Int(time.seconds))") + options.append("start=\(Int(time.seconds))") } + if let audioURL = audio?.absoluteString { + options.append("audio-files-append=\"\(audioURL)\"") + } + + args.append(options.joined(separator: ",")) + command("loadfile", args: args, returnValueCallback: completionHandler) }