How do I play YouTube
videos in my application? I want to play video
by streaming it directly from YouTube without downloading. Also, while playing videos, I want provide menu options. I don't want to play video using default intent. How can I do this?
10 Answers
This is the btn click event
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....");
}
});
this type it opened in another page with the youtube where u can show your video
Steps
Create a new Activity, for your player(fullscreen) screen with menu options. Run the mediaplayer and UI in different threads.
For playing media - In general to play audio/video there is mediaplayer api in android. FILE_PATH is the path of file - may be url(youtube) stream or local file path
MediaPlayer mp = new MediaPlayer(); mp.setDataSource(FILE_PATH); mp.prepare(); mp.start();
Also check: Android YouTube app Play Video Intent have already discussed this in detail.
Use 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);
}
});
}
}
and the PlayerConfig.java class:
package com.example.andreaskonstantakos.vfy;
/**
* Created by Andreas Konstantakos on 13/4/2017.
*/
public class PlayerConfig {
PlayerConfig(){}
public static final String API_KEY =
"xxxxx";
}
Replace the "Hce74cEAAaE" with your video ID from https://www.youtube.com/watch?v=Hce74cEAAaE. Get your API_KEY from Console.developers.google.com and also replace it on the PlayerConfig.API_KEY. For any further information you can follow the following tutorial step by step: https://www.youtube.com/watch?v=3LiubyYpEUk
I didn't want to have to have the YouTube app present on the device so I used this tutorial:
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.
Google has a YouTube Android Player API that enables you to incorporate video playback functionality into your Android applications. The API itself is very easy to use and works well. For example, here is how to create a new activity to play a video using the API.
Intent intent = YouTubeStandalonePlayer.createVideoIntent(this, "<<YOUTUBE_API_KEY>>", "<<Youtube Video ID>>", 0, true, false);
startActivity(intent);
See this for more details.
You may use iframe as described in https://developers.google.com/youtube/iframe_api_reference
I am not following the google advises exactly but this is the code I am using and it is working fine
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);
}
}
}
in /assets I have a file called 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>
and now I define a webview inside my main layout
<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" />
and I use CWebVideoView inside my activity
videoView = (WebView) view.findViewById(R.id.video);
videoView.setVisibility(View.VISIBLE);
cWebVideoView = new CWebVideoView(context, videoView);
cWebVideoView.load(url);
This answer could be really late, but its useful.
You can play youtube videos in the app itself using android-youtube-player.
Some code snippets:
To play a youtube video that has a video id in the url, you simply call the OpenYouTubePlayerActivity
intent
Intent intent = new Intent(null, Uri.parse("ytv://"+v), this,
OpenYouTubePlayerActivity.class);
startActivity(intent);
where v is the video id.
Add the following permissions in the manifest file:
<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"/>
and also declare this activity in the manifest file:
<activity
android:name="com.keyes.youtube.OpenYouTubePlayerActivity"></activity>
Further information can be obtained from the first portions of this code file.
Hope that helps anyone!
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 .