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

标签 ios swift video youtube mp3

有什么方法可以获取 youtube 视频的 .mp3 链接吗?我尝试了多个在线 youtube 到 mp3 转换器网站,但它只是将文件下载到系统中,并且不提供任何 mp3 链接。

或者

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

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

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

}

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

关于ios - 在 iOS Swift 中下载 mp3 格式的 youtube 视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36216971/

相关文章:

swift - touchesBegan 在静态 tableView 中未被调用

javascript - 无法在 play_pause 处读取 null 的属性 'pause'

ios - 如何使用 AVAssetWriter 制作缩小尺寸的视频?

ios - 为 iOS 的所有 View 保持相同的按钮高度

ios - 调用框架中的方法

swift - 如何在模块化大复杂功能中设置带有文本的图像?

javascript - 控制 iPhone/iPad 上的视频覆盖

ios - 为什么我在 iOS 9.3.2 和 10.0.1 的 google-analytics 中出现 SSLError?

ios - MessageKit 不显示消息输入栏 Swift 5

swift - Json 快速生成一个字符串数组