Videos in a NativeScript app

First, let me say that playing videos in native apps can be a hassle. As of this writing there is not an available widget to play videos in a NativeScript app. I think I read something about it being on the roadmap but I can’t recall if that was on the forums or an issue on the GitHub repo.

At any rate, lets take a look at how to play a YouTube video in your NativeScript app with the least amount of code. At the end of this tutorial we will take a second approach using the native Android VideoView.

Create a new NativeScript app and then navigate to the directory and add the platform you are working on, this tutorial will use Android.

tns create YouTubeApp
cd YouTubeApp
tns platform add android

Now open the ‘main-page.xml’ file and adjust it to look like the following:

<Page xmlns="http://schemas.nativescript.org/tns.xsd"loaded="pageLoaded">     
    <WebView src="{{ htmlString }}" height="250" />
</Page>

This layout is as simple as it gets, we have our <Page> and <WebView> components in our UI. We are going to use the WebView to load an <iframe> containing our YouTube video embed link.

The last thing to do is open our ‘main-page.js’ and modify it to look like the following code block:

var observable = require("data/observable");
 
// Our new Observable view model for data binding
var viewmodel = new observable.Observable({});
 
// Page loaded      
function pageLoaded(args) {
    var page = args.object;

    viewmodel.set("htmlString", '<iframe width="100%" height="250" src="https://www.youtube.com/embed/scGRfqV95Xw"frameborder="0"></iframe>');

    page.bindingContext = viewmodel;
}
exports.pageLoaded = pageLoaded; 

To get the correct URL for a YouTube video: go to YouTube.com, find a video, right-click and select ‘Copy Embed Code’. This will give you the string you need to set in our viewModel for htmlString.

YouTube!!!

That’s it. If you ran the app right now you would have a YouTube video loaded into your NativeScript app. The screen below is what you should see:youtubeApp

Android Native VideoView

For most cases this method is probably fine, however, I know there are instances where you might need the native video player. Hopefully the NativeScript team can ship a nice <VideoPlayer> component in the near future, but for now lets look at how to do this on Android.

Open the ‘main-page.xml’ file and change it to the following:

<Page xmlns="http://schemas.nativescript.org/tns.xsd">
  <Placeholder creatingView="createVideoView"/>
</Page>

We are going to use a <Placeholder> component to create our native video player.

Open the ‘main-page.js’ file and change it to the following:

function createVideoView(args) {
    
    //create videoview    
    var mVideoView = new android.widget.VideoView(args.context);
    var mMediaController = new android.widget.MediaController(args.context);
    mMediaController.setAnchorView(mVideoView);
        
    // parse the uri
    var videoLink = 'http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4';
    var mVideoURL = android.net.Uri.parse(videoLink);
    mVideoView.setVideoURI(mVideoURL);
    mVideoView.setMediaController(mMediaController);
    mVideoView.requestFocus();
    mVideoView.start();

    args.view = mVideoView;

    // Create our Complete Listener - this is triggered once a video reaches the end
    var completionListener = new android.media.MediaPlayer.OnCompletionListener({
        onCompletion: function(args) {
            console.log('Video Done');
        }
    });
    // Set the listener using the correct method
    mVideoView.setOnCompletionListener(completionListener);
}
exports.createVideoView = createVideoView;

If you are interested in the Android VideoView class, you can read all about it here: http://developer.android.com/intl/zh-tw/reference/android/widget/VideoView.html. A short explanation of what we are doing is constructing the VideoView and a MediaController. Simply put, the VideoView plays our video while the MediaController provides the PAUSE/PLAY and draggable slider to navigate the video timeline.

Gotchas

If you are still reading, tried the native approach, and didn’t use the EXACT url I did in the example code… you might look like this: dwight-screaming-o

I want to point out a couple of major points here and some frustrations I had while trying to use videos in my app.

  1. Google has this: https://developers.google.com/youtube/ which is the correct way to play YouTube videos in your apps now. That wasn’t the case a couple of years ago and if you start searching for how to put videos in your Android app. Most answers will be prior to Google launching the YouTube library for apps. Go ahead and try to put a YouTube video url in the ‘videoLink’ code in our sample javascript code and watch an alert come up: CAN’T PLAY THIS VIDEO. Yep, it drove me crazy for awhile.
  2. There are a lot of video formats and you might have a video that isn’t supported so be sure to check the supported video formats by the platform.
  3. If you are determined to play videos using the native Android VideoView, your best bet is probably to compress it and save it locally and then set the path to the video in the code. Which you can find the correct methods to do this in the VideoView docs.

Conclusion

I hope this has been informative for a lot of devs trying to embed videos in your NativeScript apps. I’m anxiously waiting a nice VideoPlayer component from the team that abstracts the native code into a nice API, but until then this approach should prove useful. If you have any questions or comments then let me know. I’d be glad to hear from you.

One thought on “Videos in a NativeScript app

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s