Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Foundation
- final class YoutubeDL {
- func downloadVideo(
- url: String,
- format: String,
- completion: @escaping (String) -> Void
- ) {
- let arguments = ["-f", format, url]
- executeCommand(
- "/usr/local/bin/youtube-dl",
- arguments: arguments,
- completion: completion
- )
- }
- func downloadAudio(
- url: String,
- format: String,
- completion: @escaping (String) -> Void
- ) {
- let arguments = [
- "-f", "bestaudio[ext=\(format)]",
- "--extract-audio", "--audio-format",
- format, url
- ]
- executeCommand(
- "/usr/local/bin/youtube-dl",
- arguments: arguments,
- completion: completion
- )
- }
- // MARK: - Private
- private let process = Process()
- private let pipe = Pipe()
- private func executeCommand(
- _ command: String,
- arguments: [String],
- completion: @escaping (String) -> Void
- ) {
- guard let executableURL = URL(string: command) else {
- print("Invalid command URL")
- return
- }
- process.executableURL = executableURL
- process.arguments = arguments
- process.standardOutput = pipe
- do {
- try process.run()
- process.waitUntilExit()
- let data = pipe.fileHandleForReading.readDataToEndOfFile()
- let output = String(data: data, encoding: .utf8)
- DispatchQueue.main.async {
- completion(output ?? "")
- }
- } catch {
- print("Error executing command: \(error.localizedDescription)")
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement