java 使用网站将 youtube 转换为 mp3

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12436584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:52:49  来源:igfitidea点击:

youtube to mp3 conversion using web site

javayoutube

提问by user1610362

I'm trying to make program that can download youtube videos as mp3 files. I used this site youtube-mp3.orgin order to achive that. So, i downloaded content of www.youtube-mp3.org/?c#v=sTbd2e2EyTkwhere sTbd2e2EyTk is video id, now i have to get link to mp3 file(in this case http://www.youtube-mp3.org/get?video_id.....) but there is no link in downloaded content. I noticed that chrome developers tools(ctrl+shift+j, tab Elements) show that link and view source(ctrl+u) option in chrome gives me the same result which i get by downloading page using java. How can i get that link? I tried to fetch data using JSoap but those data that i need are not loaded on page immediately so i cannot get them.

我正在尝试制作可以将 youtube 视频下载为 mp3 文件的程序。我使用了这个网站youtube-mp3.org来实现这一目标。所以,我下载了www.youtube-mp3.org/?c#v=sTbd2e2EyTk 的内容,其中 sTbd2e2EyTk 是视频 ID,现在我必须获得 mp3 文件的链接(在这种情况下为http://www.youtube-mp3.org /get?video_id.....) 但下载的内容中没有链接。我注意到chrome开发人员工具(ctrl+shift+j,tab Elements)显示chrome中的链接和查看源(ctrl+u)选项给了我与使用java下载页面相同的结果。我怎样才能得到那个链接?我尝试使用 JSoap 获取数据,但是我需要的那些数据没有立即加载到页面上,所以我无法获取它们。

Next code is for downloading content of web page...

下一个代码用于下载网页内容...

 URL tU = new URL("http://www.youtube-mp3.org/?c#v=sTbd2e2EyTk");
 HttpURLConnection conn = (HttpURLConnection) tU.openConnection();
 InputStream ins = conn.getInputStream();
 BufferedReader rd = new BufferedReader(new InputStreamReader(ins));
 String line;
 StringBuffer content = new StringBuffer();
 while ((line = rd.readLine()) != null) {
     content.append(line);
 }
 System.out.println(content.toString());

I used this method for getting file but i need link..

我使用这种方法来获取文件,但我需要链接..

   private static void downloadStreamData(String url, String fileName) throws Exception {
    URL tU = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) tU.openConnection();

    String type = conn.getContentType();
    InputStream ins = conn.getInputStream();
    FileOutputStream fout = new FileOutputStream(new File(fileName));
    byte[] outputByte = new byte[4096];
    int bytesRead;
    int length = conn.getContentLength();
    int read = 0;
    while ((bytesRead = ins.read(outputByte, 0, 4096)) != -1) {
        read += bytesRead;
        System.out.println(read + " out of " + length);
        fout.write(outputByte, 0, bytesRead);
    }
    fout.flush();
    fout.close();
}

回答by MrToast

Found this

找到这个

package main.java.com.thezujev.theyoutubepld.logic;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @author azujev
*
*/
public class YouTubeMP3 {
    public static String[] getLink(String url) throws ClientProtocolException, IOException {
        boolean passCode = false;
        String h = "";
        String title = "";
        String result = "";
        String[] returnVal = {"",""};
        Map<String, String> jsonTable;
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpInitialGet = new HttpGet("http://www.youtube-mp3.org/api/pushItem/?item=http%3A//www.youtube.com/watch%3Fv%3D" + url + "&xy=_");
        httpInitialGet.addHeader("Accept-Location", "*");
        httpInitialGet.addHeader("Referrer", "http://www.youtube-mp3.org");
        HttpParams params = new SyncBasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setUserAgent(params, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1");
        httpInitialGet.setParams(params);
        HttpResponse firstResponse = httpClient.execute(httpInitialGet);

        try {
            if (firstResponse.getStatusLine().toString().contains("200")) {
                passCode = true;
            }
        } finally {
            httpInitialGet.releaseConnection();
        }

        if (passCode) {
            while (true) {
                HttpGet httpStatusGet = new HttpGet("http://www.youtube-mp3.org/api/itemInfo/?video_id=" + url + "&adloc=");
                httpStatusGet.addHeader("Accept-Location", "*");
                httpStatusGet.addHeader("Referrer", "http://www.youtube-mp3.org");
                httpStatusGet.setParams(params);
                HttpResponse secondResponse = httpClient.execute(httpStatusGet);
                HttpEntity secondEntity = secondResponse.getEntity();
                InputStream is = secondEntity.getContent();
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                        }
                        is.close();
                        result = sb.toString();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                httpStatusGet.releaseConnection();
                result = result.replaceAll("\}.*", "}");
                result = result.replaceAll(".*?\{", "{");
                try {
                    JSONObject jsonData = new JSONObject(result);
                    JSONArray jsonArray = jsonData.names();
                    JSONArray valArray = jsonData.toJSONArray(jsonArray);
                    jsonTable = new HashMap<String, String>(jsonArray.length());
                    for (int i = 0; i < jsonArray.length(); i++) {
                        jsonTable.put(jsonArray.get(i).toString(), valArray.get(i).toString());
                    }
                    if (jsonTable.get("status").equals("serving")) {
                        h = jsonTable.get("h");
                        title = jsonTable.get("title");
                        break;
                    }
                } catch (JSONException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
            returnVal[0] = "http://www.youtube-mp3.org/get?video_id=" + url + "&h=" + h;
            returnVal[1] = title;
            return returnVal;
        } else {
            //TODO: Error, vid not downloadable
        }
        return null;
    }
}

回答by Cardinal - Reinstate Monica



An answer on a similar question:

一个类似问题的回答:



Regarding the Terms of Service of the YouTube API

关于 YouTube API 的服务条款

https://developers.google.com/youtube/terms/developer-policies

https://developers.google.com/youtube/terms/developer-policies

YOU CAN'T :

你不能:

separate, isolate, or modify the audio or video components of any YouTube audiovisual content made available through the YouTube API;

promote separately the audio or video components of any YouTube audiovisual content made available through the YouTube API;

分离、隔离或修改通过 YouTube API 提供的任何 YouTube 视听内容的音频或视频组件;

单独宣传通过 YouTube API 提供的任何 YouTube 视听内容的音频或视频组件;

(Source: https://stackoverflow.com/a/26552805/5645656)

(来源:https: //stackoverflow.com/a/26552805/5645656



My answer:

我的答案:



It ispossible using a different service. Consider the code below, which uses www.320youtube.com. The method youtubeToMP3will return an MP3 file of the video's sound as a byte array:

使用不同的服务。考虑下面的代码,它使用www.320youtube.com。该方法youtubeToMP3将以字节数组的形式返回视频声音的 MP3 文件:

private static final Pattern VID_ID_PATTERN = Pattern.compile("(?<=v\=|youtu\.be\/)\w+"),
        MP3_URL_PATTERN = Pattern
                .compile("(?<=href=\\")https{0,1}\:\/\/(\w|\d){3}\.ytapivmp3\.com.+\.mp3(?=\\")");

public static byte[] youtubeToMP3(String youtubeUrl) throws IOException {
    String id = getID(youtubeUrl);
    String converter = loadConverter(id);
    String mp3url = getMP3URL(converter);
    byte[] mp3 = load(mp3url);
    return mp3;
}

private static byte[] load(String url) throws IOException {
    URL url2 = new URL(url);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    InputStream is = url2.openStream();
    byte[] byteChunk = new byte[2500];
    int n;

    while ((n = is.read(byteChunk)) > 0) {
        baos.write(byteChunk, 0, n);
    }

    is.close();
    baos.flush();
    baos.close();

    return baos.toByteArray();
}

private static String getMP3URL(String html) {
    Matcher m = MP3_URL_PATTERN.matcher(html);
    m.find();
    return m.group();
}

private static String loadConverter(String id) throws IOException {
    String url = "https://www.320youtube.com/watch?v=" + id;
    byte[] bytes = load(url);
    return new String(bytes);
}

private static String getID(String youtubeUrl) {
    Matcher m = VID_ID_PATTERN.matcher(youtubeUrl);
    if (!m.find()) {
        throw new IllegalArgumentException("Invalid YouTube URL.");
    }
    return m.group();
}

回答by loikkk

I've done this using youtube-mp3.org. You can take a look of my code here : YoutubeMp3

我已经使用 youtube-mp3.org 完成了这项工作。你可以在这里查看我的代码:YoutubeMp3

All you have to do is the following :

您所要做的就是:

    DownloadManager d = new DownloadManager();
    d.download(YoutubeMp3.builder("http://www.youtube.com/watch?v=ebcrEqm5FFg"), "C:\Users\loikkk\Music\testDownload");
    d.setDownloadListener(new DownloadListener() {

                @Override
                public void onDownloadStart(long totalFileSize) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onDownloadProcess(long currentFileSize, long totalFileSize) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onDownloadFinished() {
                     // TODO Auto-generated method stub
                }

                @Override
                public void onDownloadError(int arg0) {
                    // TODO Auto-generated method stub

                }

    });

Hope it helps,

希望能帮助到你,

@hanry and Josh M :

@hanry 和乔希 M:

I've deleted my account on Github. However if you are using Google Chrome you can use the developer console in network perspective. So You can reverse engineered the download link it's how I've done that.

我在 Github 上删除了我的帐户。但是,如果您使用的是 Google Chrome,则可以从网络角度使用开发者控制台。所以你可以对下载链接进行逆向工程,我就是这样做的。

  1. Submit my Youtube URL to Youtube-mp-3.org
  2. Inspect the response from the webservice
  3. Build the donwload link myself following the pattern They are using.
  1. 将我的 Youtube URL 提交到 Youtube-mp-3.org
  2. 检查来自网络服务的响应
  3. 按照他们正在使用的模式自己构建下载链接。

Example :

例子 :

Youtube url : http://www.youtube.com/watch?v=KMU0tzLwhbE;

Youtube 网址:http: //www.youtube.com/watch?v=KMU0tzLwhbE

Request to webservice in the content body: KMU0tzLwhbE

对内容正文中的 webservice 的请求:KMU0tzLwhbE

Response from webservice : info = { "title" : "Developers", "image" : "http://i.ytimg.com/vi/KMU0tzLwhbE/default.jpg", "length" : "3", "status" : "serving", "progress_speed" : "", "progress" : "", "ads" : "", "pf" : "http://ping.aclst.com/ping.php/10754233/KMU0tzLwhbE?h=401301", "h" : "e8e446dbd937a0d8f636fdc8d8bb9874" };

来自网络服务的响应: info = { "title" : "Developers", "image" : " http://i.ytimg.com/vi/KMU0tzLwhbE/default.jpg", "length" : "3", "status" :“服务”,“进度速度”:“”,“进度”:“”,“广告”:“”,“pf”:“ http://ping.aclst.com/ping.php/10754233/KMU0tzLwhbE?h =401301", "h" : "e8e446dbd937a0d8f636fdc8d8bb9874" };

Download link : http://www.youtube-mp3.org/get?ab=128&video_id=KMU0tzLwhbE&h=e8e446dbd937a0d8f636fdc8d8bb9874&r=1388680822878.1534658195

下载链接:http: //www.youtube-mp3.org/get?ab=128& video_id=KMU0tzLwhbE& h=e8e446dbd937a0d8f636fdc8d8bb9874&r= 1388680822878.1534658195

Hope it helps,

希望能帮助到你,