A framework for building web apps and services with.NET and C#. Get Started Download. Supported on Windows, Linux, and macOS. Embed A Youtube Video With Custom Start & End Points Embedding a YouTube video on your website can be great for the SEO of your website (and the YouTube video you’ve embedded) as it improves the average session time on your page.
With many organizations adopting social media and digital communication, it kind of becomes obvious to use custom videos on the site. HANA Cloud Portal promises of providing rapid solution to Design, Create, Publish your content on the fly. However, when it comes to presenting HANA Cloud Solution to clients, everyone expects HANA Cloud Portal site to match the user experience with that of modern website developed using HTML5, CSS3, jQuery and so on. One of the most common requirements that come through is using custom image or a thumbnail for video and also provide custom text overlay. Take a look at image below to understand.
As you can see, we want to display an overlaying text block, and play icon at the center. However, the background image is a custom thumbnail and not the one provided by video.
What can we do with HANA Cloud Portal Widgets?
If we want to use standard functionality of widgets, unfortunately, we do not have a lot of choice. There is a video widget that you can use. However, we cannot achieve a custom text block and a custom thumbnail with video widget. When we use video widget, we get following as start up thumbnail.
Way out
I personally feel that HTML widget provided by HANA Cloud Portal is extremely powerful. You can integrate almost any functionality to your HANA Cloud Portal site with HTML widget. For e.g. If you are using a trial version of HANA Cloud Portal, you do not have a search widget. Please note that I am not sure whether search widget is available in full license. However, you can easily develop search component in HTML and add that to your site with HTML widget.
Customizing Video Thumbnail
Now, let us understand how we can replace a standard thumbnail that you see in figure 2 with something like shown in figure 1.
Develop a custom HTML component
We will develop a custom HTML component / page and use CSS to style the HTML so that we can embed the video and get a custom thumbnail. Following is the HTML code.
Let me take a while to explain the structure of the HTML.
First, we have a DIV named “image”. This is basically a wrapper DIV that wraps a Video and Image together.
Second, we will control the visibility of the video on a user click. This is when we will change the “display:none” property of DIV named “thevideo” with “display:block”. This will basically hide custom thumbnail and instead play a video once user clicks on the image or a play button.
Third, we will define a thumbnail image and assign class “thumb” so that we can control the display properties through CSS. If you are working on HANA Cloud Portal, replace the src URL with your own custom URL to image.
Next, we will define overlay text blocks that we want to show on top of the image. Additional <span> elements are used to align text properly.
Now, we have a DIV named “thevideo” which is initially hidden with the property “display:none”. Here, we will embed video URL in an IFRAME. Note the parameter “autoplay=1”. If you set this parameter to 1, then as soon as use click on a play button or an image, video will start playing. If you do want video to play automatically, set this parameter to 0.
This basically completes the HTML markup for our custom video thumbnail HTML component. Now, let us style this page so that everything is displayed correctly.
The CSS
You can either upload a .CSS file in Documents section of your HANA Cloud Portal OR simply define styles in the HTML markup itself. Define styles within <head> and </head> tags of your html markup.
Here, I want to bring your notice to two points specifically.
First is an image class defined with “.image”. Here, the wrapper or a parent element of the HTML will be positioned relatively so that its child elements can be aligned in line with parent element.
Second, H2 and H4 elements are positioned absolutely. To explain this further, when you position an element relatively, you set it to its normal position. I understand it might be confusing to understand how to position element relatively to itself. However, one main reason to use relative position is it limits child elements positioning. So when a parent element is relatively positioned, you get more control over its child elements and then you can go on to position child elements absolutely which positions the elements relative to its first positioned parent element.
Rest of the part of styling is self-explanatory. Use “.thumb” class to control width and height of your video thumbnail.
Putting together into HANA Cloud Portal
Let us now put this together into our HANA Cloud Portal site. First, we will upload custom image into “Documents” section. To upload an image, go to HANA Cloud Portal > Documents and create a new folder so that you can share content placed in this folder. Upload your custom thumbnail here and use “Share Link” feature to get the link to your custom image. Use this link in HTML markup so that you can get your own image here.
Now, “Edit” the site you want to add this HTML to and add an HTML widget.
Once placed on the design board, simply upload HTML and you are done!
I am sure a lot of people will have this requirement while displaying custom videos publicly. Unfortunately, you cannot use HTML5 video tag here to embed a video and use its “poster” property to assign custom thumbnail. This is because we are embedding a video from streaming site YouTube. If you have a video that is available on your system, do not use this option. Use HTML5 Video tag and use its “Poster” property to set custom thumbnail. However, for other of you who have to embed video from streaming sites, this is the best way to customize video display in line with your organizational branding.
This post was updated in January 2017.
The YouTube Android Player API enables you to incorporate video playback functionality into your Android applications. The API allows you to load and play YouTube videos (and playlists) and to customize and control the video playback experience.
You can load or cue videos into a player view embedded in your application’s UI. You can then control playback programmatically. For example play, pause, or seek to a specific point in the loaded video. You can register event listeners to get callbacks for certain events, such as the player loading a video or the player state changing. The API also has helper functionality to support orientation changes as well as transitions to fullscreen playback.
To get started, create a new project. I called mine VideoTube. On the next window of the Android Studio wizard you can leave the Minimum SDK version at the default API 15 (the YouTube API will only work on API 10 and above). Select the Empty Activity template on the next window and MainActivity as the activity name on the last one.
Before using the Android Youtube API, you need to register your application, including your digitally signed .apk file’s public certificate in the Google Developers Console. To register the application, follow these steps.
- Go to the Google Developers Console
- Create a new project. I named mine VideoTube.
- In the sidebar on the left, make sure that Library is selected. On the right panel, select the Youtube Data API and Enable it on the page that follows.
- In the sidebar on the left, select Credentials. For credentials, the API supports OAuth 2.0, the use of an API key and of a Service account. We’ll use the API key option.
- Select API key from the Create Credentials dropdown menu. A popup will appear with the value of your API key. Keep this window open, we’ll use the key in the next step.
Note:
The popup window that displays the API key has a Restrict Key button that you can use to restrict the key from unauthorised use. In this tutorial, we won’t restrict the key, but for an app that you plan to push to production, you should definitely restrict access to it. Key restriction lets you specify which websites, IP addresses or apps can use this key. This can help prevent unauthorised use and quota theft.
Back in the Android app, create a class named Config.java and paste in the following.
Paste in your API key.
Download the latest version of the YouTube Android Player API (1.2.2 at the time of writing). Unzip the downloaded file to find the library jar file and a sample application that you can use to see what the library offers. The jar file is located in the libs folder. Copy and paste it into your project’s libs folder. To access the libs folder, use the Project perspective on the Android Studio Project Explorer. Then expand VideoTube -> app -> libs.
Change back to the Android perspective, select the build.gradle (Module: app) file and add the following to the dependencies.
Sync the project’s gradle files.
Add the following permission for internet access to the AndroidManifest.xml file as a child of the manifest
tag and a sibling to the application
.
Edit the strings.xml file as shown. These are all the string resources we’ll require.
Next we’ll add a YouTubePlayerView
to the layout file. This view is used for displaying YouTube videos.
Modify activity_main.xml as shown.
We’ll be using the YouTubePlayerView directly in our activity as opposed to using the YouTubePlayerFragment. Because of this, the activity needs to extend the YouTubeBaseActivity
class.
Modify MainActivity.java as shown.
In the above code, we created a class that is a subclass of YouTubeBaseActivity
. This is required to make use of YouTubePlayerView
. We implemented YouTubePlayer.OnInitializedListener
to listen for initialization success or failure. The interface has two methods, named onInitializationFailure()
and onInitializationSuccess()
. If initialization is successful, the cueVideo()
method plays the YouTube video and incase of failure, checks to see whether the error is recoverable by user action.
If it’s not then a Toast of the error is shown to the user and if it’s user-recoverable, then the getErrorDialog()
method shows a dialog that will enable the user to recover from the error.
For example, if the YouTube app isn’t installed on the user’s device or is out of date, the dialog will have a prompt that upon confirmation, will open the Google Play Store for the user to install or update it accordingly. If the YouTube app is disabled on the device, then the prompt will open System Settings for the user to enable it.
When the user returns from the error recovery dialog, onActivityResult()
is called checks to see if the user performed a recovery action. If so, we retry initialization.
Run the app and you should be able to play the video specified in the code.
Note:
You need the YouTube app on your device for the video to play. The API client library interacts with a service that is distributed as part of the YouTube app for the Android platform. Users need to run version 4.2.16 of the mobile YouTube app (or higher) to use the API. Generally, devices running Android 2.2 (Froyo) or later that have the Google Play Store app should be able to run the up-to-date version of the YouTube app.
Responding to Playback Events and State Changes
In the app, you might need to take some action depending on the YouTube player’s events such as buffering, play, pause, seek and stop. You might want to show the user a message or overlay the player view with another view once video playback stops or ends.
The YouTubePlayer
has the following interface definitions to listen to such events:
– YouTubePlayer.PlayerStateChangeListener
– Interface definition for callbacks which invoked when the high level player state changes.
– YouTubePlayer.PlaybackEventListener
– Interface definition for callbacks which invoked when video playback events occur.
– YouTubePlayer.OnFullscreenListener
– Interface definition for callbacks which invoked when the player toggles between fullscreen on or off, either due to the user clicking the fullscreen button or a call to setFullscreen(boolean)
.
– YouTubePlayer.PlaylistEventListener
– Interface definition for callbacks which invoked when events related to playlists occur.
We’ll look at the first two for this app.
Add the following method to the MainActivity
class.
This will create a Toast with the message passed into the function. This will save us from writing similar lines of code.
Next add the following two subclasses to the MainActivity
class.
The above creates classes that implement the YouTubePlayer.PlaybackEventListener
and YouTubePlayer.PlayerStateChangeListener
interfaces. For each class, I have implemented the interface methods and included a comment of when the callback is invoked. You can take whatever action you want in each callback. For our example, I have included a Toast output for the onPlaying()
, onPaused()
and onStopped()
methods that will output a message when the event happens.
Add the following class variables to the MainActivity
file.
Add the following to the bottom of onCreate()
to initialize the above objects.
Modify onInitializationSuccess()
as shown. This sets the listeners on the YouTubePlayer
object.
Run the app and you should see different Toast messages appear when you start playing the video, when you pause it and when it stops (for a reason other than being paused, e.g. the video ending or a playback error).
Custom Player Controls
The YouTube library does a good job of creating an out-of-the-box user friendly interface to play YouTube videos. As a developer, you might want to take this further and provide custom controls that will give the user more control over playback. For example, enable them to jump back and forth in the video, or enable them to play the next or previous video in a playlist.
We’ll create a control in our app that will enable the user to jump to a specific time in the video.
The API provides two methods to jump playback:
– seekToMillis()
– Seeks to the specified time in the video.
– seekRelativeMillis()
– Seeks forward or backwards by the specified number of seconds.
We’ll use the first to jump to a specified time in the video.
Modify activity_main.xml as shown.
In MainActivity
add the following class variable.
At the beginning of onInitializationSuccess()
set this variable.
Add the following to the bottom of onCreate()
.
Run the app and you should be able to enter a number (in seconds) and have the video skip to that point. If you input a number that is larger than the duration of the video, then the video will skip to the end.
Conclusion
In this tutorial, we have looked at how to embed a YouTube player in your app. This is handy if you want your app users to be able to play YouTube videos while remaining in your app, instead of the YouTube app opening to play the video and then the user returning to your app after playback.
The YouTube Android library provides a great API that enables you to customise this experience and we’ve only touched on its capabilities. To find out more about the library, be sure to read through the documentation and the sample app that comes with the library download.
You can download the completed project here. Remember to place your key in the Config.java file.
I’d be keen to hear if you try the tutorial and your experiences and any questions you may have.