Jak odtwarzać filmy z Youtube w widoku wideo Androida?

Rozwijam aplikację na Androida, która wymaga wbudowanego w nią odtwarzacza wideo youtube. Udało mi się uzyskać adres URL wideo RTSP z API, ale podczas próby załadowania tego adresu URL rtsp w moim widoku wideo android, mówi "Can't play this video.". Wcześniej opracowałem podobną aplikację w tej metodzie i działała dobrze w tym czasie, ale również nie ładuje się teraz.

Jestem tego pewien, otrzymuję poprawny adres URL RTSP z API. rtsp://v6.cache6.c.youtube.com/CiULENy73wIaHAlV9VII3c64lRMYESARFEgGUglwbGF5bGlzdHMM/0/0/0/video.3gp

Oto moja aktywność kod:

    mVideoURL = getIntent().getStringExtra("EXT_URL");
    Log.i("VIDEO URL", " " + mVideoURL);

    MediaController mc = new MediaController(this);
    mVideoStreamView = (VideoView) findViewById(R.id.vidPlayer);

    mVideoStreamView.setVideoURI(Uri.parse(mVideoURL));
    mVideoStreamView.setMediaController(mc);
    mVideoStreamView.requestFocus();
    mVideoStreamView.start();

EDIT Znalazłem dodatkowe informacje z logcat:

ARTSPConnection(6607): status: RTSP/1.0 200 OK
ASessionDescription(6607): v=0
ASessionDescription(6607): o=GoogleStreamer 378992432 328144046 IN IP4 74.125.213.182
ASessionDescription(6607): s=Video
ASessionDescription(6607): c=IN IP4 0.0.0.0
ASessionDescription(6607): b=AS:29
ASessionDescription(6607): t=0 0
ASessionDescription(6607): a=control:*
ASessionDescription(6607): a=range:npt=0-1703.000000
ASessionDescription(6607): m=video 0 RTP/AVP 98
ASessionDescription(6607): b=AS:17
ASessionDescription(6607): a=rtpmap:98 H263-2000/90000
ASessionDescription(6607): a=control:trackID=0
ASessionDescription(6607): a=cliprect:0,0,144,176
ASessionDescription(6607): a=framesize:98 176-144
ASessionDescription(6607): a=fmtp:98 profile=0;level=10
ASessionDescription(6607): m=audio 0 RTP/AVP 99
ASessionDescription(6607): b=AS:12
ASessionDescription(6607): a=rtpmap:99 AMR/8000/1
ASessionDescription(6607): a=control:trackID=1
ASessionDescription(6607): a=fmtp:99 octet-align
ARTSPConnection(6607): status: RTSP/1.0 200 OK
ARTSPConnection(6607): status: RTSP/1.0 200 OK
ARTSPConnection(6607): status: RTSP/1.0 200 OK
ARTSPConnection(6607): status: RTSP/1.0 200 OK
ARTSPConnection(6607): status: RTSP/1.0 200 OK
ASessionDescription(6607): v=0
ASessionDescription(6607): o=GoogleStreamer 1299458498 503248054 IN IP4 74.125.213.182
ASessionDescription(6607): s=Video
ASessionDescription(6607): c=IN IP4 0.0.0.0
ASessionDescription(6607): b=AS:29
ASessionDescription(6607): t=0 0
ASessionDescription(6607): a=control:*
ASessionDescription(6607): a=range:npt=0-1703.000000
ASessionDescription(6607): m=video 0 RTP/AVP 98
ASessionDescription(6607): b=AS:17
ASessionDescription(6607): a=rtpmap:98 H263-2000/90000
ASessionDescription(6607): a=control:trackID=0
ASessionDescription(6607): a=cliprect:0,0,144,176
ASessionDescription(6607): a=framesize:98 176-144
ASessionDescription(6607): a=fmtp:98 profile=0;level=10
ASessionDescription(6607): m=audio 0 RTP/AVP 99
ASessionDescription(6607): b=AS:12
ASessionDescription(6607): a=rtpmap:99 AMR/8000/1
ASessionDescription(6607): a=control:trackID=1
ASessionDescription(6607): a=fmtp:99 octet-align
ARTSPConnection(6607): status: RTSP/1.0 461 Unsupported Transport
ARTSPConnection(6607): status: RTSP/1.0 461 Unsupported Transport

Zaproponuj mi sposób ładowania filmów z youtube w widoku wideo na Androida.

Z góry dzięki...

EDIT Właśnie sprawdziłem inne urządzenie, HTC Desire (2.2). Kod działał dobrze. Zastanawiam się, jaki będzie problem z Nexusem (4.1)??

Author: Midhu, 2012-12-11

8 answers

Ponieważ nie mogę znaleźć sposobu, aby załadować adres URL rtsp w widoku wideo( dla wszystkich urządzeń i wersji Androida), rozwiązałem mój problem z inną pracą. Użyłem widoku sieci Web, aby osadzić w nim odtwarzacz youtube, a ta metoda działa dobrze na wszystkich testowanych urządzeniach.

Oto Mój kod:

mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginState(PluginState.ON);
mWebView.loadUrl("http://www.youtube.com/embed/" + videoID + "?autoplay=1&vq=small");
mWebView.setWebChromeClient(new WebChromeClient());
Dziękuję bardzo za pomoc.
 31
Author: Midhu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-28 04:09:39
private class YourAsyncTask extends AsyncTask<Void, Void, Void>
    {
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(AlertDetail.this, "", "Loading Video wait...", true);
        }

        @Override
        protected Void doInBackground(Void... params)
        {
            try
            {
                String url = "http://www.youtube.com/watch?v=1FJHYqE0RDg";
                videoUrl = getUrlVideoRTSP(url);
                Log.e("Video url for playing=========>>>>>", videoUrl);
            }
            catch (Exception e)
            {
                Log.e("Login Soap Calling in Exception", e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            super.onPostExecute(result);
            progressDialog.dismiss();
/*
            videoView.setVideoURI(Uri.parse("rtsp://v4.cache1.c.youtube.com/CiILENy73wIaGQk4RDShYkdS1BMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp"));
            videoView.setMediaController(new MediaController(AlertDetail.this));
            videoView.requestFocus();
            videoView.start();*/            
            videoView.setVideoURI(Uri.parse(videoUrl));
            MediaController mc = new MediaController(AlertDetail.this);
            videoView.setMediaController(mc);
            videoView.requestFocus();
            videoView.start();          
            mc.show();
        }

    }

public static String getUrlVideoRTSP(String urlYoutube)
    {
        try
        {
            String gdy = "http://gdata.youtube.com/feeds/api/videos/";
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            String id = extractYoutubeId(urlYoutube);
            URL url = new URL(gdy + id);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            Document doc = documentBuilder.parse(connection.getInputStream());
            Element el = doc.getDocumentElement();
            NodeList list = el.getElementsByTagName("media:content");///media:content
            String cursor = urlYoutube;
            for (int i = 0; i < list.getLength(); i++)
            {
                Node node = list.item(i);
                if (node != null)
                {
                    NamedNodeMap nodeMap = node.getAttributes();
                    HashMap<String, String> maps = new HashMap<String, String>();
                    for (int j = 0; j < nodeMap.getLength(); j++)
                    {
                        Attr att = (Attr) nodeMap.item(j);
                        maps.put(att.getName(), att.getValue());
                    }
                    if (maps.containsKey("yt:format"))
                    {
                        String f = maps.get("yt:format");
                        if (maps.containsKey("url"))
                        {
                            cursor = maps.get("url");
                        }
                        if (f.equals("1"))
                            return cursor;
                    }
                }
            }
            return cursor;
        }
        catch (Exception ex)
        {
            Log.e("Get Url Video RTSP Exception======>>", ex.toString());
        }
        return urlYoutube;

    }

protected static String extractYoutubeId(String url) throws MalformedURLException
    {
        String id = null;
        try
        {
            String query = new URL(url).getQuery();
            if (query != null)
            {
                String[] param = query.split("&");
                for (String row : param)
                {
                    String[] param1 = row.split("=");
                    if (param1[0].equals("v"))
                    {
                        id = param1[1];
                    }
                }
            }
            else
            {
                if (url.contains("embed"))
                {
                    id = url.substring(url.lastIndexOf("/") + 1);
                }
            }
        }
        catch (Exception ex)
        {
            Log.e("Exception", ex.toString());
        }
        return id;
    }
 13
Author: Nipun Gogia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-11 06:30:59

Ze względu na aktualną wersję YouTube prawdopodobnie pojawi się błąd "nie mogę odtworzyć tego filmu", jeśli użyjesz VideoView, aby pokazać swój film.

Spójrz na to approcach z YouTubePlayerView: http://xinyustudio.wordpress.com/2014/03/17/android-development-play-youtube-video-in-your-app-cant-play-this-video-and-troubleshooting/

 4
Author: Sergii,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-17 13:16:17

Użyj interfejsu API YouTube Android Player. Działa idealnie. Sprawdź mój przykład z tego miejsca:

Activity_main.xml:

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context="com.example.andreaskonstantakos.vfy.MainActivity">

<com.google.android.youtube.player.YouTubePlayerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible"
android:layout_centerHorizontal="true"
android:id="@+id/youtube_player"
android:layout_alignParentTop="true" />

<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="195dp"
android:visibility="visible"
android:id="@+id/button" />


</RelativeLayout>

Główna aktywność.java:

package com.example.andreaskonstantakos.vfy;


import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;



public class MainActivity extends YouTubeBaseActivity {

YouTubePlayerView youTubePlayerView;
Button button;
YouTubePlayer.OnInitializedListener onInitializedListener;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

     youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
     button = (Button) findViewById(R.id.button);


     onInitializedListener = new YouTubePlayer.OnInitializedListener(){

         @Override
         public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {

            youTubePlayer.loadVideo("Hce74cEAAaE");

             youTubePlayer.play();
     }

         @Override
         public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {

         }
     };

    button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

youTubePlayerView.initialize(PlayerConfig.API_KEY,onInitializedListener);
        }
    });
}
}

I PlayerConfig.Klasa java:

  package com.example.andreaskonstantakos.vfy;

/**
 * Created by Andreas Konstantakos on 13/4/2017.
 */

public class PlayerConfig {

PlayerConfig(){}

public static final String API_KEY = 
"xxxxx";
}

Zastąp "Hce74ceaae" swoim identyfikatorem wideo z https://www.youtube.com/watch?v=Hce74cEAAaE . Pobierz api_key z Console.developers.google.com a także zastąpić go na PlayerConfig.API_KEY. Aby uzyskać więcej informacji, możesz postępować zgodnie z poniższym samouczkiem krok po kroku: https://www.youtube.com/watch?v=3LiubyYpEUk

 2
Author: Andreas Konstantakos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-13 03:11:32

Sprawdź ten link . Wyjaśnia, jak zaimplementować wideo z youtube w VideoView.

 1
Author: Muhammad Adil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-13 10:35:01

Używanie Widoku Wideo:

1.Kod w układzie xml:

<VideoView

       android:layout_width=”wrap_content”

       android:layout_height=”wrap_content”

       android:id=”@+id/YoutubeVideoView” />

2.Kod w klasie java:

VideoView v = (VideoView) findViewById(R.id.YoutubeVideoView);

v.setVideoURI(Uri.parse(“rtsp://v4.cache3.c.youtube.com/CjYLENy73wIaLQlW_ji2apr6AxMYDSANFEIJbXYtZ29vZ2xlSARSBXdhdGNoYOr_86Xm06e5UAw=/0/0/0/video.3gp”));

v.setMediaController(new MediaController(this)); //sets MediaController in the video view

// MediaController containing controls for a MediaPlayer                            

v.requestFocus();//give focus to a specific view

v.start();//starts the video

Ustawiamy Video poprzez podanie łącza 3gp z youtube video dla platform mobilnych. Aby dodać kontrolki multimedialne, takie jak odtwarzanie, pauza, przewijanie do tyłu ,przewijanie do przodu i suwak postępu, dodajemy MediaController do VideoView.

Uri.parse (łącze 3GP wideo)...możesz to pobrać z youtube
 0
Author: Nipun Gogia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-11 06:19:07

To zależy od tego, w jakim formacie kodeka wideo otrzymujesz swój rtsp. Istnieją pewne urządzenia, które nie obsługują uruchomionego pliku. mp4. Przejdź do Android Media support , aby uzyskać więcej informacji. Sprawdź, czy możesz grać w inne .Pliki 3gp czy nie.

 0
Author: Rashmi.B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-11 06:58:14

Po długich poszukiwaniach znalazłem ten sposób implementacji.

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.about_fragment, container, false);

    String frameVideo = "<html><body><br><iframe width=\"320\" height=\"200\" src=\"https://www.youtube.com/embed/XDYbEuY8nIc\" frameborder=\"0\" allowfullscreen></iframe></body></html>";

    WebView displayYoutubeVideo = (WebView) rootView.findViewById(R.id.videoView);
    displayYoutubeVideo.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }
    });
    WebSettings webSettings = displayYoutubeVideo.getSettings();
    webSettings.setJavaScriptEnabled(true);
    displayYoutubeVideo.loadData(frameVideo, "text/html", "utf-8");
  return rootView;
    }

Wewnątrz układu.xml:

 <WebView android:id="@+id/videoView"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:layout_marginTop="-45dp"
            android:layout_marginLeft="-5dp"/>
To zadziała dobrze.
 0
Author: Ahmed Sadek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-01 20:05:29