download youtube video in mp3 format in iOS Swift

会有一股神秘感。 提交于 2019-12-31 06:25:26

问题


Is there any way to get .mp3 links for youtube video's? I tried multiple online youtube to mp3 converter sites but it all just downloads the file in system and doesn't give any mp3 link.

Or

Is there any way i can download files from a link, so lets say there is some link like www.somesongdownloader.com, on load of this link in browser mp3 file is getting downloaded. but if i try to download the same from my ios code its just downloading the php file not mp3 file. below is my code -

Below code works fine for mp3 links which i am not able to get for youtube videos but this code is not working for any url which gives mp3 file to download on browser -

class func loadFileAsync(url: NSURL, completion:(path:String, error:NSError!) -> Void) {
    print("Inside loadFileAsync")
    let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
    let destinationUrl = documentsUrl.URLByAppendingPathComponent(url.lastPathComponent!)
    if NSFileManager().fileExistsAtPath(destinationUrl.path!) {
        print("file already exists [\(destinationUrl.path!)]")
        completion(path: destinationUrl.path!, error:nil)
    } else {
        let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "GET"

        let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
            if (error == nil) {
                if let response = response as? NSHTTPURLResponse {
                    print("response=\(response)")
                    if response.statusCode == 200 {
                        if data!.writeToURL(destinationUrl, atomically: true) {
                            print("file saved [\(destinationUrl.path!)]")
                            completion(path: destinationUrl.path!, error:error)
                        } else {
                            print("error saving file")
                            let error = NSError(domain:"Error saving file", code:1001, userInfo:nil)
                            completion(path: destinationUrl.path!, error:error)
                        }
                    }
                }
            }
            else {
                print("Failure: \(error!.localizedDescription)");
                completion(path: destinationUrl.path!, error:error)
            }
        })
        task.resume()
    }
}

回答1:


As suggested in my comments, using http://www.youtubeinmp3.com/api/ you can do this.

    let videoURL = "http://www.youtube.com/watch?v=KMU0tzLwhbE"
    let url = NSURL(string: "http://www.youtubeinmp3.com/fetch/?format=JSON&video=\(videoURL)")
    let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
    let request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = "GET"

    let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
        if (error == nil) {
            if let response = response as? NSHTTPURLResponse {
                print("response=\(response)")
                if response.statusCode == 200 {
                    if data != nil {
                        do {
                            let responseJSON =  try  NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary;
                            let urlString = responseJSON["link"] as! String
                            let directDownloadURL = NSURL(string: urlString)

                            // Call your method loadFileAsync
                            YourClass.loadFileAsync(directDownloadURL!, completion: { (path, error) -> Void in
                                print(path)
                            })

                        }
                        catch let JSONError as NSError {
                            print("\(JSONError)")
                        }
                        catch {
                            print("unknown error in JSON Parsing");
                        }

                    }
                }
            }
        }
        else {
            print("Failure: \(error!.localizedDescription)");
        }
    })
    task.resume()

}

I have not done error handling, so you need to further refine this code. But this will surely work. I have tested it.



来源:https://stackoverflow.com/questions/36216971/download-youtube-video-in-mp3-format-in-ios-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!