从 android 应用程序打开 Chromecast youtube 视频 [英] Open Chromecast youtube video from android application

查看:16
本文介绍了从 android 应用程序打开 Chromecast youtube 视频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个应用程序,其中有一个带有 youtube 链接的列表视图.现在我想使用 chrome cast 播放这些视频.我遵循了官方文档,我可以使用直接 mp4 链接播放其他视频,但它不适用于 youtube 链接.

I created an app in which there is a list view with youtube links. Now I want to play these videos using chrome cast. I followed the official documentation and I am able to play other videos with direct mp4 link, but its not working for youtube links.

当然,其他链接直接连接到视频(以 *.mp4 结尾),但是我如何添加带有 youtube 链接的媒体?不知何故,我需要创建一个带有 youtube 链接的 MediaInfo 对象,但我不知道该怎么做,或者甚至可能.

Of course the other links are directly connected to a video (ending *.mp4), but how can i add a media with a youtube link? Somehow I need to create a MediaInfo object with youtube link, but I don't know how to do that or is it even possible.

我找到了这个信息

MimeData data = new MimeData("v=g1LsT1PVjUA", MimeData.TYPE_TEXT);mSession.startSession("YouTube", 数据);

MimeData data = new MimeData("v=g1LsT1PVjUA", MimeData.TYPE_TEXT); mSession.startSession("YouTube", data);

从我的 Android 应用打开 Chromecast YouTube 视频

但我不确定如何获取会话并使用 youtube 会话加载它.如果有人可以帮助我,我将不胜感激.

But I am not sure how to get the session and load it with youtube session. I would appreciate if someone can help me with this.

感谢您的帮助

推荐答案

去年我编写了一个 Android 应用程序,可以在连接到大屏幕电视的 VLC 上播放 YouTube/本地媒体.它玩得非常好,但我总是想用更优雅的东西替换 VLC 笔记本电脑.当 Chromecast 终于与官方 SDK 一起发布时,我真的很兴奋.我在尝试启动 YouTube 接收器应用程序来播放 YouTube 视频时也遇到了同样的问题,所以我决定深入研究 VLC 是如何做到这一点的(开源很棒:))我发现 YouTube 视频 ID 只是一个嵌入了很多东西的 JavaScript 页面.诀窍是从中提取正确的信息.不幸的是,VLC 脚本是用 Lua 编写的,所以我花了几个星期学习了足够的 Lua 来浏览 Lua 脚本.您可以在 youtube.lua 上搜索脚本的源代码.

I wrote an Android app that plays YouTube/Local media on VLC attached to a big screen TV last year. It was playing very nice but I always want to replace the VLC laptop with something more elegant. I was really excited when Chromecast was finally released with an official SDK. I too ran into the same problem when trying to launch YouTube receiver app to play YouTube video so I decided to delve into how VLC was able to do that (Is open source great :)) I found out that the YouTube video ID is just a JavaScript page with lots of stuff embedded inside. The trick is to pull out the correct info from it. Unfortunately, the VLC script is written in Lua so I spent a couple weeks learning enough Lua to navigate my way around the Lua script. You can google youtube.lua for the source code of the script.

我用 Java 重写了脚本,并且能够修改 CastVideos Android 以轻松播放 YouTube 视频.请注意,由于 Chromecast 只能播放 mp4 视频容器格式,因此其他格式的视频可能无法播放.

I rewrote the script in Java and was able to modify CastVideos Android to play YouTube video at ease. Note that since Chromecast can only play mp4 video container format, video in other format may not play.

如果有人感兴趣,这是我的测试代码.您可以使用 CastHelloVideo-chrome 加载自定义媒体来测试 URL.

Here is my test code if anyone is interested. You can test the URL using CastHelloVideo-chrome load custom media.

享受,

    package com.dql.urlexplorer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class UrlExplore {

    private static final String URL_ENCODED_STREAM_MAP     = ""url_encoded_fmt_stream_map":";
    private static final String VIDEO_TITLE_KEYWORD               = "<meta name="title"";
    private static final String VIDEO_DESCRIPTION_KEYWORD  = "<meta name="description"";
    private static final String VIDEO_THUMBNAIL_KEYWORD    = "<meta property="og:image"" ;
    private static final String CONTENT_VALUE_KEYWORD        = "content="";

    //private static final String TEST_URL = "http://www.youtube.com/watch?v=JtyCM4BTbYo";
    private static final String YT_UTRL_PREFIX = "http://www.youtube.com/watch?v=";

    public static void main(String[] args) throws IOException {

        while (true) {
               String videoId = getVideoIdFromUser();

                String urlSite = YT_UTRL_PREFIX + videoId;
                System.out.println("URL =  " + urlSite);
                System.out.println("===============================================================");
                System.out.println("Getting video site content");
                System.out.println("===============================================================");

                CloseableHttpClient httpclient = HttpClients.createDefault();
                try {
                    HttpGet httpget = new HttpGet(urlSite);

                    System.out.println("Executing request " + httpget.getRequestLine());


                    // Create a custom response handler
                    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

                        public String handleResponse(
                                final HttpResponse response) throws ClientProtocolException, IOException {
                            int status = response.getStatusLine().getStatusCode();
                            if (status >= 200 && status < 300) {
                                HttpEntity entity = response.getEntity();
                                return entity != null ? EntityUtils.toString(entity) : null;
                            } else {
                                throw new ClientProtocolException("Unexpected response status: " + status);
                            }
                        }

                    };
                    String responseBody = httpclient.execute(httpget, responseHandler);

                    if (responseBody.contains(VIDEO_TITLE_KEYWORD)) {
                        // video title
                        int titleStart = responseBody.indexOf(VIDEO_TITLE_KEYWORD);
                        StringBuilder title = new StringBuilder();
                        char ch;
                        do {
                            ch = responseBody.charAt(titleStart++);
                            title.append(ch);
                        }
                        while (ch != '>');
                        String videoTitle = getKeyContentValue(title.toString());
                         System.out.println("Video Title =  " + videoTitle);
                    }
                    if (responseBody.contains(VIDEO_DESCRIPTION_KEYWORD)) {
                        // video description
                        int descStart = responseBody.indexOf(VIDEO_DESCRIPTION_KEYWORD);
                        StringBuilder desc = new StringBuilder();
                        char ch;
                        do {
                            ch = responseBody.charAt(descStart++);
                            desc.append(ch);
                        }
                        while (ch != '>');
                        String videoDesc = getKeyContentValue(desc.toString());
                         System.out.println("Video Description =  " + videoDesc);                       
                    }
                    if (responseBody.contains(VIDEO_THUMBNAIL_KEYWORD)) {
                        // video thumbnail
                        int thumbnailStart = responseBody.indexOf(VIDEO_THUMBNAIL_KEYWORD);
                        StringBuilder thumbnailURL = new StringBuilder();
                        char ch;
                        do {
                            ch = responseBody.charAt(thumbnailStart++);
                            thumbnailURL.append(ch);
                        }
                        while (ch != '>');
                        String videoThumbnail= getKeyContentValue(thumbnailURL.toString());
                         System.out.println("Video Thumbnail =  " + videoThumbnail);                        
                    }
                    if (responseBody.contains(URL_ENCODED_STREAM_MAP)) {
                        // find the string we are looking for
                        int start = responseBody.indexOf(URL_ENCODED_STREAM_MAP) + URL_ENCODED_STREAM_MAP.length() + 1;  // is the opening "
                        String urlMap = responseBody.substring(start);
                        int end = urlMap.indexOf(""");
                        if (end > 0) {
                            urlMap = urlMap.substring(0, end);
                        }
                        String path = getURLEncodedStream(urlMap);
                        System.out.println("Video URL = " + path);
                    }

                }
                finally {
                    httpclient.close();
                }
                System.out.println( "===============================================================");
                System.out.println("Done: ");
                System.out.println("===============================================================");      
        }

    }

    static String getURLEncodedStream(String stream) throws UnsupportedEncodingException {
        // replace all the u0026 with &
         String str = stream.replace("\u0026", "&");
        //str = java.net.URLDecoder.decode(stream, "UTF-8");
        //System.out.println("Raw URL map = " + str);
        String urlMap = str.substring(str.indexOf("url=http") + 4);
        // search urlMap until we see either a & or ,
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < urlMap.length(); i++) {
            if ((urlMap.charAt(i) == '&') || (urlMap.charAt(i) == ','))
                break;
            else
                sb.append(urlMap.charAt(i));
        }
        //System.out.println(java.net.URLDecoder.decode(sb.toString(),"UTF-8"));
        return java.net.URLDecoder.decode(sb.toString(),"UTF-8");

    }

    static String getKeyContentValue(String str) {
        StringBuilder contentStr = new StringBuilder();
        int contentStart = str.indexOf(CONTENT_VALUE_KEYWORD) + CONTENT_VALUE_KEYWORD.length();
        if (contentStart > 0) {
            char ch;
            while (true) {
                ch = str.charAt(contentStart++);
                if (ch == '"')
                    break;
                contentStr.append(ch);
            }
        }
        try {
            return java.net.URLDecoder.decode(contentStr.toString(),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /*
     * Prompt the user to enter a video ID.
     */
    private static String getVideoIdFromUser() throws IOException {

        String videoId = "";

        System.out.print("Please enter a YouTube video Id: ");
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
        videoId = bReader.readLine();

        if (videoId.length() < 1) {
            // Exit if the user doesn't provide a value.
            System.out.print("Video Id can't be empty! Exiting program");
            System.exit(1);
        }

        return videoId;
    }

}`enter code here`

这篇关于从 android 应用程序打开 Chromecast youtube 视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆