Advertisement
marcusziade

youtube-dl swift manager

May 5th, 2023
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.79 KB | None | 0 0
  1. import Foundation
  2.  
  3. final class YoutubeDL {
  4.  
  5.     func downloadVideo(
  6.         url: String,
  7.         format: String,
  8.         completion: @escaping (String) -> Void
  9.     ) {
  10.         let arguments = ["-f", format, url]
  11.         executeCommand(
  12.             "/usr/local/bin/youtube-dl",
  13.             arguments: arguments,
  14.             completion: completion
  15.         )
  16.     }
  17.    
  18.     func downloadAudio(
  19.         url: String,
  20.         format: String,
  21.         completion: @escaping (String) -> Void
  22.     ) {
  23.         let arguments = [
  24.             "-f", "bestaudio[ext=\(format)]",
  25.             "--extract-audio", "--audio-format",
  26.             format, url
  27.         ]
  28.         executeCommand(
  29.             "/usr/local/bin/youtube-dl",
  30.             arguments: arguments,
  31.             completion: completion
  32.         )
  33.     }
  34.    
  35.     // MARK: - Private
  36.    
  37.     private let process = Process()
  38.     private let pipe = Pipe()
  39.    
  40.     private func executeCommand(
  41.         _ command: String,
  42.         arguments: [String],
  43.         completion: @escaping (String) -> Void
  44.     ) {
  45.         guard let executableURL = URL(string: command) else {
  46.             print("Invalid command URL")
  47.             return
  48.         }
  49.        
  50.         process.executableURL = executableURL
  51.         process.arguments = arguments
  52.         process.standardOutput = pipe
  53.  
  54.         do {
  55.             try process.run()
  56.             process.waitUntilExit()
  57.            
  58.             let data = pipe.fileHandleForReading.readDataToEndOfFile()
  59.             let output = String(data: data, encoding: .utf8)
  60.            
  61.             DispatchQueue.main.async {
  62.                 completion(output ?? "")
  63.             }
  64.         } catch {
  65.             print("Error executing command: \(error.localizedDescription)")
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement