Advertisement
Rudigus

Untitled

Mar 31st, 2020
410
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 8.99 KB | None | 0 0
  1. #!/usr/bin/swift
  2. //
  3. //  main.swift
  4. //  Terminal Music Player
  5. //
  6. //  Created by Rodrigo Matos Aguiar on 10/03/20.
  7. //  Copyright © 2020 Rodrigo Matos Aguiar. All rights reserved.
  8. //
  9.  
  10. import AVFoundation
  11. import Foundation
  12.  
  13. let bye = "Tchau pessoa!"
  14. let musicFilesURL: URL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent("Music Files", isDirectory: true)
  15.  
  16. class Music: Codable {
  17.     var url: URL
  18.     var title: String = "Desconhecido"
  19.     var artist: String = "Desconhecido"
  20.     var type: String = "Desconhecido"
  21.    
  22.     init(url: URL) {
  23.         self.url = url
  24.         setMetadata()
  25.     }
  26.    
  27.     private func setMetadata() {
  28.        
  29.         let playerItem = AVPlayerItem(url: self.url)
  30.         let metadataList = playerItem.asset.metadata
  31.        
  32.         for item in metadataList {
  33.             if let itemKey = item.commonKey {
  34.                 switch itemKey.rawValue {
  35.                 case "title":
  36.                     self.title = item.stringValue ?? "Desconhecido"
  37.                 case "artist":
  38.                     self.artist = item.stringValue ?? "Desconhecido"
  39.                 case "type":
  40.                     self.type = item.stringValue ?? "Desconhecido"
  41.                 default:
  42.                     continue
  43.                 }
  44.             } else {
  45.                 continue
  46.             }
  47.         }
  48.     }
  49.    
  50.     public func play() {
  51.         do {
  52.             let musicData = try Data(contentsOf: self.url)
  53.             let musicPlayer = try AVAudioPlayer(data: musicData)
  54.             musicPlayer.play()
  55.             if musicPlayer.isPlaying{
  56.                 print("Reproduzindo \(self.artist) - \(self.title)")
  57.                 print("Digite \"stop\" para parar")
  58.                 if let command = readLine(), command == "stop" {
  59.                     print(bye)
  60.                 } else {
  61.                     print("erro")
  62.                 }
  63.             }
  64.         } catch {
  65.             print("\(error)")
  66.         }
  67.     }
  68. }
  69.  
  70. /* https://files.freemusicarchive.org/storage-freemusicarchive-org/music/ccCommunity/Chad_Crouch/Arps/Chad_Crouch_-_Shipping_Lanes.mp3
  71.     https://files.freemusicarchive.org/storage-freemusicarchive-org/music/West_Cortez_Records/David_Hilowitz/Gradual_Sunrise/David_Hilowitz_-_Gradual_Sunrise.mp3
  72.  */
  73.  
  74. func main()
  75. {
  76.      
  77.      
  78.     let menu = """
  79.  
  80.    --- Comandos do Player ---
  81.  
  82.    Reproduzir música online - play
  83.    Reproduzir música local - local
  84.    Reproduzir música salva -
  85.    Salvar música - save
  86.    Procurar músicas - search
  87.    Listas de Reprodução - playlists
  88.    Lista de comandos - commands
  89.    Sair do Player - exit
  90.  
  91.    """
  92.     print(menu)
  93.     while let command = readLine() {
  94.         switch command {
  95.         case "play", "play local":
  96.             let musicOpt: Music?
  97.             if command == "play"{
  98.                 musicOpt = loadMusic()
  99.             } else {
  100.                 musicOpt = loadMusicLocal()
  101.             }
  102.            
  103.             if let music = musicOpt {
  104.                 music.play()
  105.             } else {
  106.                 print("erro")
  107.             }
  108.             print(menu)
  109.         case "save":
  110.             let musicOpt = loadMusic()
  111.             if let music = musicOpt {
  112.                 saveMusic(music: music, fileURL: musicFilesURL.appendingPathComponent("Musics.json"))
  113.             } else {
  114.                 print("erro")
  115.             }
  116.             print(menu)
  117.         case "search":
  118.             let musicOpt = searchMusicJson()
  119.             if let music = musicOpt {
  120.                 print(music.url)
  121.             } else {
  122.                 print("Música não encontrada.")
  123.             }
  124.         case "exit":
  125.             print(bye)
  126.             return
  127.         case "commands":
  128.             print(menu)
  129.         default:
  130.             print("\nComando inválido. Informe um comando válido (commands):\n")
  131.         }
  132.     }
  133. }
  134.  
  135. func loadMusic() -> Music? {
  136.     print("Informe a URL da música: ")
  137.     guard let musicUrl = readLine() else {
  138.         return nil
  139.     }
  140.     let urlOpt = URL(string: musicUrl)
  141.     if let url = urlOpt {
  142.         let music = Music(url: url)
  143.         return music
  144.     } else {
  145.         return nil
  146.     }
  147. }
  148.  
  149. func loadMusicLocal() -> Music? {
  150.     print("Informe o nome junto da extensão da música: ")
  151.     guard let musicFile = readLine() else {
  152.         return nil
  153.     }
  154.     let musicUrl: URL = musicFilesURL.appendingPathComponent(musicFile)
  155.     let music = Music(url: musicUrl)
  156.     return music
  157. }
  158.  
  159. func searchMusicJson() -> Music? {
  160.     print("Informe o nome da música: ")
  161.     guard let musicName = readLine() else {
  162.         return nil
  163.     }
  164.     let dictMusicOpt = getDictFromFile()
  165.     guard let dictMusic = dictMusicOpt else {
  166.         print("erro")
  167.         return nil
  168.     }
  169.     return dictMusic[musicName]
  170. }
  171.  
  172. // Pegar o que tá no arquivo e criar um dicionario com isso
  173.  
  174. func saveMusic(music: Music, fileURL: URL) {
  175.     let fileManager = FileManager.default
  176.     if fileManager.fileExists(atPath: fileURL.path) {
  177.         let dictMusicOpt = getDictFromFile()
  178.         if var dictMusic = dictMusicOpt {
  179.             dictMusic[music.title] = music
  180.             do {
  181.                 let jsonDataOpt = musicsToJsonData(musics: dictMusic)
  182.                 if let jsonData = jsonDataOpt {
  183.                     let fileHandle = try FileHandle(forWritingTo: musicFilesURL.appendingPathComponent("musics.json"))
  184.                     fileHandle.write(jsonData)
  185.                 } else {
  186.                     print("erro")
  187.                 }
  188.             } catch {
  189.                 print("Error appending to file \(error)")
  190.             }
  191.         } else {
  192.             print("erro")
  193.         }
  194.     } else {
  195.         createInitialFile(initialMusic: [music.title: music], fileURL: fileURL)
  196.     }
  197.    
  198. }
  199.  
  200. func getDictFromFile() -> [String: Music]? {
  201.     do {
  202.         let fileHandle = try FileHandle(forReadingFrom: musicFilesURL.appendingPathComponent("musics.json"))
  203.         let jsonData = fileHandle.readDataToEndOfFile()
  204.         let dict = jsonDataToMusics(jsonData: jsonData)
  205.         return dict
  206.     } catch {
  207.         print("Error reading file \(error)")
  208.         return nil
  209.     }
  210. }
  211.  
  212. func createInitialFile(initialMusic: [String: Music], fileURL: URL) {
  213.     // Create file and write json
  214.     let jsonEncoder = JSONEncoder()
  215.     let fileManager = FileManager.default
  216.     do {
  217.         let jsonData = try jsonEncoder.encode(initialMusic)
  218.         fileManager.createFile(atPath: fileURL.path, contents: jsonData, attributes: [:])
  219.     } catch {
  220.         print("\(error)")
  221.     }
  222.     //print("arquivo criado")
  223. }
  224.  
  225. func jsonDataToMusics(jsonData: Data) -> [String: Music]? {
  226.     do {
  227.         let jsonDecoder = JSONDecoder()
  228.         let musics = try jsonDecoder.decode([String: Music].self, from: jsonData)
  229.         return musics
  230.     } catch {
  231.         return nil
  232.     }
  233. }
  234.  
  235. func musicsToJsonData(musics: [String: Music]) -> Data? {
  236.     do {
  237.         let jsonEncoder = JSONEncoder()
  238.         let jsonData = try jsonEncoder.encode(musics)
  239.         return jsonData
  240.     } catch {
  241.         print("\(error)")
  242.         return nil
  243.     }
  244. }
  245.  
  246. main()
  247.  
  248. /*func playLocalMusic(resourceUrl: String, fileExtension: String)
  249. {
  250.     print("\(resourceUrl) \(fileExtension)")
  251.     //let urlOpt = Bundle.main.url(forResource: resourceUrl, withExtension: fileExtension)
  252.     //print(Bundle.main.bundleURL.relativePath)
  253.    
  254.     let root = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
  255.     let musicURL: URL = root.appendingPathComponent("Music Files", isDirectory: true).appendingPathComponent("music.mp3")
  256.    
  257.     print(musicURL)
  258.     do {
  259.         let musicPlayer = try AVAudioPlayer(contentsOf: musicURL)
  260.         musicPlayer.prepareToPlay()
  261.         musicPlayer.play()
  262.         if let command = readLine(), command == "stop" {
  263.             print("flws")
  264.         } else {
  265.             print("erro")
  266.         }
  267.         print("Eita: \(musicPlayer.isPlaying)\(musicURL)")
  268.     } catch {
  269.         print("🔴 \(error)")
  270.     }
  271.    
  272.     RunLoop.main.run()
  273. }*/
  274.  
  275. //func musicToJsonData(music: Music) -> Data? {
  276. //    do {
  277. //        let jsonEncoder = JSONEncoder()
  278. //        let jsonData = try jsonEncoder.encode(music)
  279. //        return jsonData
  280. //    } catch {
  281. //        print("\(error)")
  282. //        return nil
  283. //    }
  284. //}
  285.  
  286. //func musicToJson(music: Music) -> String? {
  287. //    do {
  288. //        let jsonEncoder = JSONEncoder()
  289. //        let jsonData = try jsonEncoder.encode(music)
  290. //        let json = String(data: jsonData, encoding: String.Encoding.utf8)
  291. //        return json
  292. //    } catch {
  293. //        print("\(error)")
  294. //        return nil
  295. //    }
  296. //}
  297.  
  298. //func jsonToMusic(json: String) -> Music? {
  299. //    do {
  300. //        let jsonDecoder = JSONDecoder()
  301. //        if let jsonData = json.data(using: .utf8) {
  302. //            let music = try jsonDecoder.decode(Music.self, from: jsonData)
  303. //            return music
  304. //        } else {
  305. //            return nil
  306. //        }
  307. //    } catch {
  308. //        print("\(error)")
  309. //        return nil
  310. //    }
  311. //}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement