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

socialnetis

Active Member
Licensed User
Longtime User
If you put any view in foreground, like a label of something, the video not playing and says: "Error: UNAUTHORIZED_OVERLAY"
in error event

Sub Youtube_OnError(Error As String)
Log("Error: " & Error) <=Error: UNAUTHORIZED_OVERLAY
End Sub
Are you overlying a view in front of the youtubeView? Because the documentation 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.
However you can overlay a View while the video is not playing, and hide it when the video starts playing.

Can it play live youtube??
I haven't tested and don't know what channels are using live stream right now.
 

Alberto Iglesias

Well-Known Member
Licensed User
Longtime User

DonManfred

Expert
Licensed User
Longtime User
I´m using this lib in a project now... the app runs in Portrait-mode... when a user click on fullscreen button of your lib in my app then the direction will change to Landscape. Can i supress this? I dont want to go in Landscape

But everything else is working fine. Thank you for sharing this library!
 

MarcoRome

Expert
Licensed User
Longtime User
Hi SocialNetis :)
After that Youtube is initialize and Youtube work... i set Youtube.isPlaying = True .... and the App Crash .

Any Idea ??

B4X:
.............
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

Sub PAUSEButton_Click
if Youtube.isPlaying = True then
    If PAUSEButton.Text = "Pause" Then
        Youtube.pause
        PAUSEButton.Text = "Play"
    Else
        Youtube.play
        PAUSEButton.Text = "Pause"
    End If
end if
End Sub

Thank you
 
Last edited:

MarcoRome

Expert
Licensed User
Longtime User
Hi i have one question.

image-music-CD76_53B276B2.png


1) Point one... is possibile if i utilize Youtube.LoadPlayList("DfXXXXXX", XX,YY) know the name the video ( in this example "Ricky ....") ??

2) If video dont work ( as in picture ) and i want the next video ( if i utilize nextVideo dont work in this case ) exist one function that work in this direction ?

Thank
 

MarcoRome

Expert
Licensed User
Longtime User
ok. Thank you Erel.
Exist one function or method to move to the nextvideo in this cases ?
 

ivan.tellez

Active Member
Licensed User
Longtime User
there are basically 4 ways for playing videos with this API:
1) Using the YoutubeStandalonePlayer.
2) Working with Intents.
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 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).

Hi, after reading this, I remembered that latest versions of B4A had the activity attribute #extends:

Is this attribute what is needed to use YoutubePlayerView and YoutubePlayerFragment on andoid < 4.0?

And if it is, could you update your lib to offer the YoutubePlayerView?

Thanks
 
Top