在 iOS Swift 下载 mp3 格式的 youtube 视频

download youtube video in mp3 format in iOS Swift

有没有办法为 YouTube 视频获取 .mp3 links?我尝试了多个在线 youtube 到 mp3 转换器站点,但它们都只是在系统中下载文件,不提供任何 mp3 link。

有什么方法可以从 link 下载文件吗?假设有一些 link 像 www.somesongdownloader.com,在浏览器中加载这个 link正在下载 mp3 文件。但如果我尝试从我的 ios 代码下载相同的内容,它只是下载 php 文件而不是 mp3 文件。下面是我的代码 -

下面的代码适用于 mp3 links,我无法获取 youtube 视频,但此代码不适用于任何 url,它提供 mp3 文件以在浏览器上下载 -

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()
    }
}

正如我在评论中所建议的那样,使用 http://www.youtubeinmp3.com/api/ 你可以做到这一点。

    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()

}

我没有做错误处理,所以你需要进一步完善这段代码。但这肯定会奏效。我已经测试过了。