B4A Library Youtube View - Embed videos in your apps!

Hi everyone, I would like to introduce you this Youtube library (from the oficial Youtube Android Api provided by google), its not actually a View, its a fragment, but you can use it almost as a view. It will allow you to have full control of the video via code (play, pause, seek to a specific time, listen to lot of events, etc).
Here is an example of what it looks like:

screenshot-3-jpg.18691


Before you continue reading, I'll first say the main drawback: Its only supported by Android 4.0+.
Why? (You can skip the explanation if you want) Well, because there are basically 4 ways for playing videos with this API:
1) Using the YoutubeStandalonePlayer, which allows you to play videos in fullscreen (its an other activity) or in a lightbox which you can't control the position. You can find this wrapper in Erel's post.
2) Working with Intents, which basically opens the Youtube app, and you can play around with some parameters.
3) Using YoutubePlayerView, which is the real interesting one, it allows you to embed a view in your applications, as if were a button, imageview, etc. The problem for making a wrapper for this view is that the activity in which you are going to use this view, needs to extend an activity called YouTubeBaseActivity, and the Activities in B4A doesn't extend this activity.
4) Using YoutubePlayerFragment, which is the wrapper I made. A fragment is a piece of an application's user interface or behavior that can be placed in an activity, and contains views (this fragment contains a YoutubePlayerView). Fragments are only natively supported by Android 4.0+. There is a support for fragments for android < 4.0, but the activity needs to extend an activity called FragmentActivity, which leads to the same problem as point 3).


Ok, after saying that, here is how to setup:

Setup instructions:
1. Download the native library: https://developers.google.com/youtube/android/player/downloads/
2. Copy libs\YouTubeAndroidPlayerApi.Jar from the zip file to Basic4android libraries folder.
3. Download the attached library, unzip it and copy the files to the libraries folder.
4. Get a developer key. Follow these instructions: https://developers.google.com/youtube/android/player/register
Note that you can leave the SHA1 field empty.

Now, for using the view, you need to pass a Panel as argument in the initialization method. The Panel is the one that will contain the real Youtube View. The fragment will fill both height and width of the Panel, and the video will actually play with a 16:9 aspect ratio, so I suggest you to make the panel with a 16:9 aspect ratio or you will have black edged at the bottom or right of the panel.

Also, the documentation of the API says:
Note that while videos are playing, this View has a minimum size of 200x110 dp. If you make the view any smaller, videos will automatically stop playing. Also, it is not permitted to overlay the view with other views while a video is playing.

Here is an example code:
B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

End Sub
Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Dim Youtube As SNYouTube
    Dim Panel1 As Panel
End Sub
Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("Layout1")
    Youtube.Initialize("Youtube","xxxxxxxx",Panel1)
End Sub
Sub Activity_Resume
End Sub
Sub Activity_Pause (UserClosed As Boolean)
End Sub
Sub Youtube_OnFinishedInitialization(Success As Boolean)
    Log("Success: " & Success)
    If Success Then
        Youtube.loadVideo("0xdZXOM_Otc")
    End If
End Sub

Note that after initialization, you need to wait to the "OnFinishedInitialization" event before actually starting playing videos.

Here is the complete reference:
SNYoutube
Version:
1
  • SNYouTube
    Events:
    • OnAdStarted
    • OnBuffering (Buffering As Boolean )
    • OnError (Error As String )
    • OnFinishedInitialization (Success As Boolean)
    • OnFullScreen (B As Boolean)
    • OnLoaded
    • OnLoading
    • OnPaused
    • OnPlaying
    • OnStopped
    • OnVideoEnded
    • OnVideoStarted
    Methods:
    • Initialize (EventName As String, Key As String, P As PanelWrapper)
    • cuePlaylist (playList As String)
      Cues the specified playlist, but does not download any of the video streams or start playing until play() or seekToMillis(int) is called.
    • cuePlaylist2 (playlistId As String, startIndex As Int, timeMillis As Int)
      Cues the specified playlist, but does not download any of the video streams or start playing until play() or seekToMillis(int) is called.
    • cueVideo (videoId As String)
      Loads the specified video's thumbnail and prepares the player to play the video, but does not download any of the video stream until play() is called.
    • cueVideo2 (videoId As String, timeMillis As Int)
      Loads the specified video's thumbnail and prepares the player to play the video, but does not download any of the video stream until play() is called.
    • cueVideos (videoIds As List)
      Cues a list of videos, but does not download any of the video streams or start playing until play() or seekToMillis(int) is called.
    • cueVideos2 (videoIds As List, startIndex As Int, timeMillis As Int)
      Cues a list of videos, but does not download any of the video streams or start playing until play() or seekToMillis(int) is called.
    • hasNext As Boolean
      Determines whether the currently loaded playlist has a next video.
    • hasPrevious As Boolean
      Determines whether the currently loaded playlist has a previous video.
    • isPlaying As Boolean
      Determines whether the player is currently playing.
    • loadPlaylist (playlistId As String)
      Loads and plays the specified playlist.
    • loadPlaylist2 (playlistId As String, startIndex As Int, timeMillis As Int)
      Loads and plays the specified playlist.
    • loadVideo (videoId As String)
      Loads and plays the specified video.
    • loadVideo2 (videoId As String, timeMillis As Int)
      Loads and plays the specified video.
    • loadVideos (videoIds As List)
      Loads and plays a list of videos.
    • loadVideos2 (videoIds As List, startIndex As Int, timeMillis As Int)
      Loads and plays a list of videos.
    • nextVideo
      Plays the next video in the loaded playlist.
    • pause
      Pauses the currently playing video.
    • play
      Starts video playback of the currently cued / loaded video.
    • previousVideo
      Plays the previous video in the loaded playlist.
    • release
      Stop any loading or video playback and release any system resources used by this YouTubePlayer.
    • seekRelativeMillis (milliSeconds As Int)
      Seeks forward or backwards by the specified number of seconds.
    • seekToMillis (milliSeconds As Int)
      Seeks to the specified time in the video.
    Permissions:
    • android.permission.INTERNET
    Properties:
    • CurrentTimeMillis As Int [read only]
      Gets the current elapsed time of the playing video relative to its start.
    • DurationMillis As Int [read only]
      Gets the duration of the currently loaded video.
    • Fullscreen As Boolean [write only]
      Inform the player that it is being laid out fullscreen.
    • FullscreenControlFlags As Int
      Gets the currently set fullscreen control flags.
    • ManageAudioFocus As Boolean [write only]
      Specifies whether or not the player will handle audio focus as part of its playback lifecycle.
    • ShowFullscreenButton As Boolean [write only]
      Shows or hides the fullscreen button on the player controls.
 

Attachments

  • YoutubeView.zip
    16.5 KB · Views: 530
  • Screenshot 3.jpg
    Screenshot 3.jpg
    177.5 KB · Views: 958

socialnetis

Active Member
Licensed User
Hi, I wasn't aware of this #extends attribute. I'm a little away in the android programming as I'm focusing
in my final thesis to graduate, so I don't think I would have time to extend it right now.

However, have you seen the Android versions market share? Take a look HERE.
Android < 4.0 represents only about 15%.

But if you really need to target Android < 4.0 you can still use Erel's Youtube library (http://www.basic4ppc.com/android/forum/threads/youtube-library.24818/#content), it doesn't have the benefits of a view, but its the only solution I can see right now
 

Rick Harris

Well-Known Member
Licensed User
I like your player because it has more possibilities than Erel's version.
However, your library does not play Youtube "Live" video's, whereas Erel's version does!
Can you please amend this.

Is it also possible to add an event that triggers when the user taps on the Youtube player (i.e. when the controls re-appear)?
 

StephanP82

Member
Licensed User
Thanks for this nice library. I'm trying to play two Youtube Videos at the same time. So I've created two instances of SNYoutube and placed each on a seperate panel. But when I start video playback in one of it, the other player is paused and if I try to press 'play' it handles the other instance. What can I do to get the two videos playing at the same time?
 

StephanP82

Member
Licensed User
Okay... Maybe someone knows another solution for my problem. I want to create a kind of DJ-App for Youtube, which allows to create playlists of Youtube-Videos and play them in the order of the list. Some seconds before the video ends, it should fade into the next video in the other panel. To make this possible, the second video needs to be started some seconds before the first one ends. Maybe it could work with a Youtube-Lib for the first and a webview for the second video?
 

Rick Harris

Well-Known Member
Licensed User
Here are my thoughts on this:
1. Try to find the real video stream URL's of both Youtube video's. It is feasible to find these mp4's. Take a look here how to do this: http://stackoverflow.com/questions/34692326/get-video-source-from-youtube-video.
2. Use two full screen videoviews in your project: vv1 and vv2 to play these streams and place a full screen transparent panel (with black as background) on top of each videoview: Panel1 and Panel2. Hide vv2 and Panel2 to start with.
3. Start video1 on vv1 and determine its duration using vv1.duration.
4. Make Panel1 gradually less transparent 3 seconds before the end of video1 to simulate fade out (using a timer that fires every 100 msec and that increases alpha from 0 to 255 in steps of 8, providing fade-out of about 3 seconds).
5. When nearly faded out make vv1 and Panel1 invisible and vv2 and Panel2 visible.
6. Start video2 on vv2 with Panel2 initially being non-transparent on top of it and gradually make this panel transparent (using the timer again, but now decreasing alpha).
7. You might als want to fade-out and fade-in the sound. You could do this by controlling the music channel volume.
8. Mixing of video and sound will not be possible (I think), but if you don't fade sound and video out completely to zero, but in stead start the second video about a second before the first has stopped playing you should get some kind of fade-out and -in effect.

Take a look here regarding fading video's in and out: https://www.b4x.com/android/forum/threads/simple-animations-in-b4a-v4-00.47731/#content which might also provide you with ideas.

Be aware that Google will probably block your app for allowing Youtube material to be played outside the regular framework (especially if advertisements are skipped). Erel has created a Youtube player library. It works fine as a separate player, but has no ability whatsoever to be controlled by software and in that respect this player is a real pain (Google's doing).
 
Last edited:

StephanP82

Member
Licensed User
Thanks for your answer. I'm not sure if I have correctly understood the points 1 and 2:

1. On the linked page the talk is off 'get_video_info'. This brings a text document with a lot of information about the video but where is the real video URL? I can't find it.

2. What do you mean with fullscreen video views? Do you mean Webviews? And why they should be in fullscreen size? I've planned to put both videos on the activity and if one of it paused, i want to show an image like a venyl record on it's position. Should I place the video views in fullscreen size in this case?
 

Rick Harris

Well-Known Member
Licensed User
Thanks for your answer. I'm not sure if I have correctly understood the points 1 and 2:

1. On the linked page the talk is off 'get_video_info'. This brings a text document with a lot of information about the video but where is the real video URL? I can't find it.

2. What do you mean with fullscreen video views? Do you mean Webviews? And why they should be in fullscreen size? I've planned to put both videos on the activity and if one of it paused, i want to show an image like a venyl record on it's position. Should I place the video views in fullscreen size in this case?
1. The clue is in the part that talks about playit.pk

2. A video view is an official Android view (nothing to do with webviews). A vv can play a number of video formats, including mp4. It is part of the Audio library.
 
Last edited:

analizer3816

Member
Licensed User
@socialnetis thanks for great library.
I have to use snyoutube on overlay window by add it to overlay window's panel.
it can't initialize and show error
B4X:
Installing file.
PackageAdded: package:b4a.example2003
** Service (starter) Create **
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
android.content.res.Resources$NotFoundException: Unable to find resource ID #0x2
    at android.content.res.Resources.getResourceName(Resources.java:2713)
    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:882)
    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
    at android.app.BackStackRecord.run(BackStackRecord.java:684)
    at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1453)
    at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:146)
    at android.app.ActivityThread.main(ActivityThread.java:5487)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
    at dalvik.system.NativeStart.main(Native Method)

can you suggest me about use this library on overlay window?
 

MarcoRome

Expert
Licensed User
@socialnetis thanks for great library.
I have to use snyoutube on overlay window by add it to overlay window's panel.
it can't initialize and show error
B4X:
Installing file.
PackageAdded: package:b4a.example2003
** Service (starter) Create **
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
android.content.res.Resources$NotFoundException: Unable to find resource ID #0x2
    at android.content.res.Resources.getResourceName(Resources.java:2713)
    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:882)
    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
    at android.app.BackStackRecord.run(BackStackRecord.java:684)
    at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1453)
    at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:146)
    at android.app.ActivityThread.main(ActivityThread.java:5487)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
    at dalvik.system.NativeStart.main(Native Method)

can you suggest me about use this library on overlay window?
Do you tried this: ExoPlayer by @Erel
 

Santiago Barreiro

Member
Licensed User
Are you overlying a view in front of the youtubeView? Because the documentation says:

However you can overlay a View while the video is not playing, and hide it when the video starts playing.


I haven't tested and don't know what channels are using live stream right now.

B4X:
Youtube.Initialize("nameofevent as in google api","keygiven",Panel1)

It is important to use this two...
still, some youtube videos can be seen, others not
 
Top