Program Club

Android 애플리케이션에서 YouTube 비디오를 재생하는 방법은 무엇입니까?

proclub 2020. 10. 14. 21:27
반응형

Android 애플리케이션에서 YouTube 비디오를 재생하는 방법은 무엇입니까?


YouTube내 응용 프로그램에서 비디오를 재생하려면 어떻게합니까 ? play video다운로드하지 않고 YouTube에서 직접 스트리밍 하고 싶습니다 . 또한 동영상을 재생하면서 메뉴 옵션을 제공하고 싶습니다. 기본 의도를 사용하여 비디오를 재생하고 싶지 않습니다. 어떻게 할 수 있습니까?


이것은 btn 클릭 이벤트입니다.

btnvideo.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

    startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.youtube.com/watch?v=Hxy8BZGQ5Jo")));
    Log.i("Video", "Video Playing....");

    }
}); 

이 유형은 비디오를 표시 할 수있는 YouTube로 다른 페이지에서 열렸습니다.


공식 YouTube Android Player API를 확인 하세요 .


단계

  1. 메뉴 옵션이있는 플레이어 (전체 화면) 화면에 대한 새 활동을 만듭니다. 다른 스레드에서 미디어 플레이어와 UI를 실행합니다.

  2. 미디어 재생 용-일반적으로 오디오 / 비디오 재생을 위해 android에는 mediaplayer api가 있습니다. FILE_PATH는 파일의 경로이며 url (youtube) 스트림 또는 로컬 파일 경로 일 수 있습니다.

     MediaPlayer mp = new MediaPlayer();
        mp.setDataSource(FILE_PATH);
        mp.prepare();
        mp.start();
    

또한 확인하십시오 : Android YouTube 앱 Play Video Intent에서 이미 자세히 논의했습니다.


YouTube Android Player API를 사용하세요.

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>

MainActivity.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);
        }
    });
}
}

및 PlayerConfig.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";
}

'Hce74cEAAaE'를 https://www.youtube.com/watch?v=Hce74cEAAaE 의 동영상 ID로 바꿉니다 . Console.developers.google.com에서 API_KEY를 가져 와서 PlayerConfig.API_KEY에서도 교체합니다. 자세한 내용은 https://www.youtube.com/watch?v=3LiubyYpEUk 다음 자습서를 단계별로 수행 할 수 있습니다.


여기 에서 찾을 수있는 Android-Youtube-Player 앱을 볼 수 있습니다 .
이 샘플 앱에서 YouTube 동영상은 webview가 아닌 ​​videoview 내에서 재생됩니다.


이 링크가 http://android-coding.blogspot.in/2011/03/simple-example-using-videoview-to-play.html에 도움이 되기를 바랍니다.

youtube 비디오를 rtsp로 변환하려면이 github 코드를 사용하십시오 -youtube-url2rtsp


이 답변은 정말 늦을 수 있지만 유용합니다.

android-youtube-player를 사용하여 앱 자체에서 YouTube 동영상을 재생할 수 있습니다 .

일부 코드 스 니펫 :

URL에 동영상 ID가있는 YouTube 동영상을 재생하려면 인 OpenYouTubePlayerActivity텐트 를 호출하기 만하면됩니다.

Intent intent = new Intent(null, Uri.parse("ytv://"+v), this, 
            OpenYouTubePlayerActivity.class);
startActivity(intent);

여기서 v는 동영상 ID입니다.

매니페스트 파일에 다음 권한을 추가합니다.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

또한 매니페스트 파일에서이 활동을 선언합니다.

<activity 
        android:name="com.keyes.youtube.OpenYouTubePlayerActivity"></activity>

추가 정보는 코드 파일 의 첫 번째 부분에서 얻을 수 있습니다 .

누구에게나 도움이되기를 바랍니다!


Google에는 동영상 재생 기능을 Android 애플리케이션에 통합 할 수 있는 YouTube Android Player API 가 있습니다. API 자체는 사용하기 매우 쉽고 잘 작동합니다. 예를 들어, 다음은 API를 사용하여 비디오를 재생하는 새 활동을 만드는 방법입니다.

Intent intent = YouTubeStandalonePlayer.createVideoIntent(this, "<<YOUTUBE_API_KEY>>", "<<Youtube Video ID>>", 0, true, false);   
startActivity(intent);

참조 자세한 내용은.


https://developers.google.com/youtube/iframe_api_reference에 설명 된대로 iframe을 사용할 수 있습니다.

나는 Google의 조언을 정확히 따르지 않지만 이것은 내가 사용하는 코드이며 잘 작동합니다.

public class CWebVideoView {

    private String url;
    private Context context;
    private WebView webview;
    private static final String HTML_TEMPLATE = "webvideo.html";

    public CWebVideoView(Context context, WebView webview) {
        this.webview = webview;
        this.context = context;
        webview.setBackgroundColor(0);
        webview.getSettings().setJavaScriptEnabled(true);
    }

    public void load(String url){
        this.url = url;
        String data = readFromfile(HTML_TEMPLATE, context);
        data = data.replace("%1", url);
        webview.loadData(data, "text/html", "UTF-8");
    }

    public String readFromfile(String fileName, Context context) {
        StringBuilder returnString = new StringBuilder();
        InputStream fIn = null;
        InputStreamReader isr = null;
        BufferedReader input = null;
        try {
            fIn = context.getResources().getAssets().open(fileName, Context.MODE_WORLD_READABLE);
            isr = new InputStreamReader(fIn);
            input = new BufferedReader(isr);
            String line = "";
            while ((line = input.readLine()) != null) {
                returnString.append(line);
            }
        } catch (Exception e) {
            e.getMessage();
        } finally {
            try {
                if (isr != null)
                    isr.close();
                if (fIn != null)
                    fIn.close();
                if (input != null)
                    input.close();
            } catch (Exception e2) {
                e2.getMessage();
            }
        }
        return returnString.toString();
    }

    public void reload() {
        if (url!=null){
            load(url);
        }
    }
}

/ assets에는 webvideo.html이라는 파일이 있습니다.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <style>
            iframe   { border: 0; position:fixed; width:100%; height:100%; bgcolor="#000000"; }
            body     { margin: 0; bgcolor="#000000"; }
        </style>        
    </head>
    <body>
        <iframe src="%1" frameborder="0" allowfullscreen></iframe>
    </body>
</html>

이제 기본 레이아웃 내에 웹뷰를 정의합니다.

<WebView
    android:id="@+id/video"
    android:visibility="gone"
    android:background="#000000"
    android:layout_centerInParent="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

내 활동 내에서 CWebVideoView를 사용합니다.

videoView = (WebView) view.findViewById(R.id.video);
videoView.setVisibility(View.VISIBLE);
cWebVideoView = new CWebVideoView(context, videoView);
cWebVideoView.load(url);

기기에 YouTube 앱이있는 것을 원하지 않았기 때문에이 튜토리얼을 사용했습니다.

http://www.viralandroid.com/2015/09/how-to-embed-youtube-video-in-android-webview.html

...to produce this code in my app:

WebView mWebView; 

@Override
public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.video_webview);
    mWebView=(WebView)findViewById(R.id.videoview);

    //build your own src link with your video ID
    String videoStr = "<html><body>Promo video<br><iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/embed/47yJ2XCRLZs\" frameborder=\"0\" allowfullscreen></iframe></body></html>";

    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
        }
    });
    WebSettings ws = mWebView.getSettings();
    ws.setJavaScriptEnabled(true);
    mWebView.loadData(videoStr, "text/html", "utf-8");

}

//video_webview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="0dp"
    android:layout_marginRight="0dp"
    android:background="#000000"
    android:id="@+id/bmp_programme_ll"
    android:orientation="vertical" >

   <WebView
    android:id="@+id/videoview" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />  
</LinearLayout>     

This worked just how I wanted it. It doesn't autoplay but the video streams within my app. Worth noting that some restricted videos won't play when embedded.


you can use this project to play any you tube video , in your android app . Now for other video , or Video id ... you can do this https://gdata.youtube.com/feeds/api/users/eminemvevo/uploads/ where eminemvevo = channel .

after finding , video id , you can put that id in cueVideo("video_id")

src -> com -> examples -> youtubeapidemo -> PlayerViewDemoActivity

  @Override
  public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player , boolean wasRestored) {
    if (!wasRestored) {
      player.cueVideo("wKJ9KzGQq0w");
    }
  }

And specially for reading that video_id in a better way open this , and it as a xml[1st_file] file in your desktop after it create a new Xml file in your project or upload that[1st_file] saved file in your project , and right_click in it , and open it with xml_editor file , here you will find the video id of the particular video .

enter image description here


MediaPlayer mp=new MediaPlayer(); 
mp.setDataSource(path);
mp.setScreenOnWhilePlaying(true);
mp.setDisplay(holder);
mp.prepare();
mp.start();

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watchv=cxLG2wtE7TM"));
startActivity(intent);

참고URL : https://stackoverflow.com/questions/4654878/how-to-play-youtube-video-in-my-android-application

반응형