【问题标题】:download youtube video in mp3 format in iOS Swift在 iOS Swift 中下载 mp3 格式的 youtube 视频
【发布时间】:2016-03-25 09:02:53
【问题描述】:

有没有办法获取 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()
    }
}

【问题讨论】:

  • 您需要获取转换后的mp3的直接下载地址。为此,您必须使用所用 URL 网页中的 HTML(将视频转换为 mp3)。检查此codeproject.com/Tips/587931/YouTube-to-mp .. 这不在 iOS 中,但您可能必须以类似的方式工作。
  • 有没有其他方法可以得到转换后的mp3的直接下载链接?
  • 不确定,检查一次youtubeinmp3.com/api

标签: ios swift video youtube mp3


【解决方案1】:

按照我的 cmets 中的建议,使用 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()

}

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

【讨论】:

  • 我已经尝试过了,不,它没有用 :(,它下载的是一个 get 文件而不是 mp3 文件。而且我们从youtubeinmp3.com/api 得到的 url 不是一个 mp3 文件。
  • 将扩展名为 .mp3 的文件保存。它会起作用的。您可以通过将扩展名为 get 的文件重命名为 .mp3 来测试它。
  • 抱歉耽搁了……我忙于其他工作。并且没有 .mp3 扩展名 dinn 的保存文件对我有用。保存的文件没有播放。如果您也尝试过.. 它对您有用吗?我的意思是您可以玩吗?
  • 是的,我刚刚将“get”命名文件重命名为“get.mp3”。并在 iTunes 中播放该文件。它对我有用。
  • 抱歉,回复晚了,您的解决方案有效,但只有几次。有时它会失败,因为 youtubeinmp3 链接没有返回 json 格式的数据。我已经测试了很多次,链接有时会返回 json 响应,有时会重定向到不同的页面。
猜你喜欢
  • 2016-11-15
  • 2021-01-13
  • 2014-11-26
  • 2018-05-05
  • 2011-05-16
  • 1970-01-01
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多