您好,我正在开发一个 Android 应用程序,我的应用程序的一部分想要将歌曲标题解析到 YouTube 并获取视频链接。获得 100% 正确的视频并不重要。那么我如何从 youtube 检索数据呢?
谁能帮我找到一个解决方案,这对我来说真的很有帮助。
谢谢
最佳答案
最常见的方法是使用 Youtube 数据 API,它会返回 XML/Json,您可以对其进行解析以检索诸如视频 url 之类的内容。
更新 (2017/01/24) (v3)
使用以下调用通过搜索查询搜索 YouTube 视频:
https://www.googleapis.com/youtube/v3/search?part=snippet&q=fun%20video&key=YOUR-API-KEY
它支持以下基本参数进行搜索:
- part :您要在搜索中检索的视频数据。对于基本搜索,推荐值为 snippet。
- q : 你要搜索的文字
- key:您的 Google Developer API key 。此 key 可以在 Google Developer API Console 获得在您的应用程序的凭据页面上。确保在您的 key 所属的应用程序上启用 Youtube Data API v3。
有关更多参数,请参阅 Google API Documentation
使用 Java 库
在 Android 上,您可以使用平台上可用的标准 HTTP 请求类对 URL 执行 HTTP 请求,或者您可以使用 Google API Java Library如下图:
YouTube youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("YOUR-APPLICATION-NAME").build();
String queryTerm = "A fun video"
// Define the API request for retrieving search results.
YouTube.Search.List search = youtube.search().list("id,snippet");
search.setKey("Your-Api-Key");
search.setQ(queryTerm);
// Call the API and print first result.
SearchListResponse searchResponse = search.execute();
if(searchResponse.getItems().size() == 0)
{
//No items found.
return;
}
SearchResult firstItem = searchResponse.getItems().get(0);
ResourceId rId = firstItem.getId();
// Confirm that the result represents a video. Otherwise, the
// item will not contain a video ID.
if (rId.getKind().equals("youtube#video")) {
Thumbnail thumbnail = firstItem.getSnippet().getThumbnails().getDefault();
Log.d("YOUTUBE_SAMPLE","Video Id" + rId.getVideoId());
Log.d("YOUTUBE_SAMPLE","Title: " + firstItem.getSnippet().getTitle());
Log.d("YOUTUBE_SAMPLE","Thumbnail: " + thumbnail.getUrl());
}
关于Android 从 youtube 获取视频链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12157379/