如何在安卓设备上制作YouTube视频缩略图?

30

在我的Android活动中,我想通过YouTube应用程序或其他应用程序播放YouTube视频。为此,我希望在我的活动中加载该视频的缩略图。

这是否可行?如果是,如何实现?


你尝试过自己开始吗? - simchona
为什么它不起作用?Stack Overflow 不会为您提供针对不具体问题的答案。 - simchona
我想知道这是否可能? - Krishna
视频文件的缩略图是可用的。我想知道是否可以从YouTube获取。 - Krishna
我已经从YouTube获取了v=id,但如何将drawable转换并将其设置为ImageView?请帮帮我... - Harsha
显示剩余2条评论
4个回答

79

YouTube在特定可预测的URL上放置视频缩略图。虽然可能有点麻烦,但我相信你可以找到一种方法来显示从URL中获取的图片,或者下载它们然后显示它们。

这里是我的博客上关于这些缩略图URL的信息。

我将复制并粘贴我在博客文章中写的内容:

查看视频链接-例如,http://www.youtube.com/watch?v=GDFUdMvacI0

取出视频ID...即在“v =”之后的部分,在这种情况下为GDFUdMvacI0。如果URL比这更长,则仅继续到下一个&符号。例如,http://www.youtube.com/watch?v=GDFUdMvacI0&feature=youtu.be是相同的,GDFUdMvacI0

然后只需用以下缩略图图像的视频ID替换您的视频ID:

  • 0.jpg 是一张全尺寸的图片。其他三张非常小 (120×90) ,是 YouTube 自动从视频中的三个特定点截取的。

如何以编程方式获取视频ID? - SubbaReddy PolamReddy
这取决于你拥有的信息。我对你的具体情况一无所知,所以恐怕无法帮助你。请修改你的问题,包含更多关于你正在做什么的细节——你是在尝试从URL中解析视频ID吗?你是通过API提交新的YouTube视频吗?还是其他什么? - Chad Schultz
如何获取YouTube播放列表缩略图URL? - Mostafa Imran

28
  • 下载picasso jar文件并将其放入“libs”文件夹中

  • 使用picasso下载图像

  • 使用方法extractYoutubeId(url)从YoutubeVideo Url中提取youtube id

要获取YouTube视频的图像,请使用给定的链接,并将YouTube id放入该链接中,如下所示:"http://img.youtube.com/vi/"+extractYoutubeId(url)+"/0.jpg"

Youtube视频缩略图

    package com.app.download_video_demo;

    import java.net.MalformedURLException;
    import java.net.URL;

    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.ImageView;

    import com.squareup.picasso.Picasso;


    // get Picasso jar file and put that jar file in libs folder

    public class Youtube_Video_thumnail extends Activity
    {
        ImageView iv_youtube_thumnail,iv_play;
        String videoId;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            super.setContentView(R.layout.youtube_video_activity);

            init();

            try 
            {
                videoId=extractYoutubeId("http://www.youtube.com/watch?v=t7UxjpUaL3Y");

                Log.e("VideoId is->","" + videoId);

                String img_url="http://img.youtube.com/vi/"+videoId+"/0.jpg"; // this is link which will give u thumnail image of that video

                // picasso jar file download image for u and set image in imagview

                Picasso.with(Youtube_Video_thumnail.this)
                .load(img_url) 
                .placeholder(R.drawable.ic_launcher) 
                .into(iv_youtube_thumnail);

            } 
            catch (MalformedURLException e) 
            {
                e.printStackTrace();
            }

        }
        public void init()
        {
            iv_youtube_thumnail=(ImageView)findViewById(R.id.img_thumnail);
            iv_play=(ImageView)findViewById(R.id.iv_play_pause);
        }

        // extract youtube video id and return that id
        // ex--> "http://www.youtube.com/watch?v=t7UxjpUaL3Y"
        // videoid is-->t7UxjpUaL3Y


        public String extractYoutubeId(String url) throws MalformedURLException {
            String query = new URL(url).getQuery();
            String[] param = query.split("&");
            String id = null;
            for (String row : param) {
                String[] param1 = row.split("=");
                if (param1[0].equals("v")) {
                    id = param1[1];
                }
            }
            return id;
        }

    }

youtube_video_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/webvideo_layout2"
        android:layout_width="250dp"
        android:layout_height="180dp"
        android:layout_gravity="center"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        >


        <ImageView
            android:id="@+id/img_thumnail"
            android:layout_width="250dp"
            android:layout_height="180dp"
            android:layout_centerInParent="true"
            android:scaleType="fitXY" />

        <ImageView
            android:id="@+id/iv_play_pause"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:src="@drawable/icn_play" />
    </RelativeLayout>

</LinearLayout>

我可以按照说明运行缩略图吗? - amit pandya

13

试试这个

public static String getYoutubeThumbnailUrlFromVideoUrl(String videoUrl) {
   return "http://img.youtube.com/vi/"+getYoutubeVideoIdFromUrl(videoUrl) + "/0.jpg";
}

public static String getYoutubeVideoIdFromUrl(String inUrl) {
   inUrl = inUrl.replace("&feature=youtu.be", "");
   if (inUrl.toLowerCase().contains("youtu.be")) {
       return inUrl.substring(inUrl.lastIndexOf("/") + 1);
   }
   String pattern = "(?<=watch\\?v=|/videos/|embed\\/)[^#\\&\\?]*";
   Pattern compiledPattern = Pattern.compile(pattern);
   Matcher matcher = compiledPattern.matcher(inUrl);
   if (matcher.find()) {
      return matcher.group();
   }
   return null;
}

寻找能够在YouTube链接包含“youtu.be”时正常工作的解决方案,最终找到了,谢谢。 - Vivek Thummar
如果你的视频链接类似于“http://www.youtube.com/watch?v=Fs8fsrngI3Q&feature=youtu.be”,那么只需更新你的if条件为`if (inUrl.toLowerCase().contains("youtu.be/")) { ... }`。 - Vivek Thummar

2

这可能会对某些人有帮助。首先要做的是获取您想要的视频,这里我从播放列表中检索到了一个视频列表。之后我使用了这个类:
http://blog.blundell-apps.com/imageview-with-loading-spinner/
在从网络中检索缩略图时显示进度条。

    /***
 * Fetch all videos in a playlist
 * @param playlistId
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 * @throws JSONException
 */
public YouTubePlaylist fetchPlaylistVideos(String playlistId) throws ClientProtocolException, IOException, JSONException {
    String playlistUrl = "https://gdata.youtube.com/feeds/api/playlists/" + playlistId + "?v=2&alt=jsonc";
    HttpClient client = new DefaultHttpClient();
    HttpUriRequest request = new HttpGet(playlistUrl);
    HttpResponse response = client.execute(request);
    String jsonString = GeneralHelpers.convertToString(response.getEntity().getContent());
    JSONObject json = new JSONObject(jsonString);

    if (jsonString.contains("Playlist not found")) {
        Log.e(TAG, "playlist not found. id: " + playlistId);
        return null;
    }

    JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");

    String playlistTitle = json.getJSONObject("data").getString("title");
    String author = json.getJSONObject("data").getString("author");

    List<YouTubeVideo> videos = new ArrayList<YouTubeVideo>();
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject video = jsonArray.getJSONObject(i).getJSONObject("video");
        // The title of the video
        String title = video.getString("title");

        String url;
        try {
            url = video.getJSONObject("player").getString("mobile");
        } catch (JSONException ignore) {
            url = video.getJSONObject("player").getString("default");
        }

        String thumbUrl = video.getJSONObject("thumbnail").getString("sqDefault");
        String videoId = video.getString("id");
        String uploaded = video.getString("uploaded");
        String duration = video.getString("duration");
        String minutes = (Integer.parseInt(duration) / 60 < 10) ? "0" + (Integer.parseInt(duration) / 60) : "" + (Integer.parseInt(duration) / 60);
        String seconds = (Integer.parseInt(duration) % 60 < 10) ? "0" + (Integer.parseInt(duration) % 60): "" + (Integer.parseInt(duration) % 60); 
        duration = minutes + ":" + seconds;

        videos.add(new YouTubeVideo(title, author, url, thumbUrl, videoId, uploaded, duration));
    }

    YouTubePlaylist playlist = new YouTubePlaylist(author, playlistId, playlistTitle, videos);
    return playlist;
}//end fetchPlaylistVideos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接