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: 826
  • Screenshot 3.jpg
    Screenshot 3.jpg
    177.5 KB · Views: 1,379

socialnetis

Active Member
Licensed User
Longtime 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.b4x.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
 

StephanP82

Member
Licensed User
Longtime 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
Longtime 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?
 

StephanP82

Member
Licensed User
Longtime 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?
 

analizer3816

Member
Licensed User
Longtime 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
Longtime 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
 

Charlie Yang

New Member
Licensed User
Longtime User
Hi,
Excuse me, can SNYoutube set the volume?
Do I need to control the volume, or are there any good ideas?
 

Santiago Barreiro

New 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