8

i am not able to play video on Android web view.

I have kept the html and video file in my assets folder.

Whenever i load the html file , it gives me the error

05-01 12:31:16.092: E/MediaResourceGetter(17241): Unable to read file: file:///android_asset/MediaBook2%20(2)/2B952499A0E681.mp4

And whenever i press on the play button i get the following error

05-01 12:31:23.680: E/chromium(17241): [ERROR:webmediaplayer_android.cc(328)] Not implemented reached in virtual void content::WebMediaPlayerAndroid::setRate(double)
05-01 12:31:23.710: E/MediaPlayer(17241): error (1, -2147483648)
05-01 12:31:23.710: E/MediaPlayer(17241): Error (1,-2147483648)

Am able to load any remote video and run,But problem is when i load the local video from the assets folder Code to load the files and setup the web view

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    // Remove title bar
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.activity_webview);
    mContentView = (LinearLayout) findViewById(R.id.linearlayout);
    // Keep the webview setup ready
    setupWebView();


}

public void setupWebView()
{
    webView = (WebView) findViewById(R.id.webView);
    // progressBar = (ProgressBar) findViewById(R.id.progressBarForWebView);

    WebSettings webViewSettings = webView.getSettings();
    webViewSettings.setJavaScriptEnabled(true);
    webViewSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    webViewSettings.setPluginState(PluginState.ON);
    webView.getSettings().setAllowFileAccess(true);
    webView.setSoundEffectsEnabled(true);
    webView.setWebViewClient(new SLCWebViewClient());
    webView.setWebChromeClient(new WebChromeClient());
    loadContentsInWebView();

}
public void loadContentsInWebView()
    {

        String localURL = "file:///android_asset/MediaBook2 (2)/SampleForVideo.html";
        logger.debug("WebView URL: {}", localURL);
        try {
            webView.loadUrl(localURL);
        }
        catch (Exception e) {
            e.printStackTrace();
            logger.error("Error while loading url", e);
        }
    }
    private class SLCWebViewClient extends WebViewClient
{
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url)
    {
        view.setWebChromeClient(new WebChromeClient()
        {

            private View mCustomView;

            @Override
            public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback)
            {
                // if a view already exists then immediately terminate the new one
                if (mCustomView != null) {
                    callback.onCustomViewHidden();
                    return;
                }

                // Add the custom view to its container.
                mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
                mCustomView = view;
                mCustomViewCallback = callback;

                // hide main browser view
                mContentView.setVisibility(View.GONE);

                // Finally show the custom view container.
                mCustomViewContainer.setVisibility(View.VISIBLE);
                mCustomViewContainer.bringToFront();
            }

        });

        webView.loadUrl(url);

        return true;
    }

The Sample For Video.html code

    <!DOCTYPE html>
<html>
<title>Testing for Video</title>
<body>

<video width="320" height="240" controls>
  <source src="2B952499A0E681.mp4">
</video>

</body>
</html>

Code for the layout file

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout
      android:id="@+id/fullscreen_custom_content"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:background="#FF000000"/>

<LinearLayout 
      android:id="@+id/linearlayout"
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent"> 

 <WebView
       android:id="@+id/webView"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent" />

cheers, Saurav

saurav
  • 5,388
  • 10
  • 56
  • 101
  • see: https://stackoverflow.com/a/12481491/1815624 for an example using audio...the issue is how you access the media files... – CrandellWS Nov 13 '20 at 19:17

3 Answers3

4

Thanks to Marcin for his answer.

I could run the the html files by loading the video. My problem was i was using /MediaBook2 (2)/SampleForVideo.html. But the '/' should be removed when loading from assets. I splitted the string by trimming off the '/' and it worked.

But that was just a sample scenario i was working on to clear my understanding.

I have a much bigger folder structure and now when the .mp4 file is eventually loaded.

The media player is shown but the player is not playing any file.

saurav
  • 5,388
  • 10
  • 56
  • 101
  • see: https://stackoverflow.com/questions/23403445/not-able-to-play-video-in-web-view#comment114616250_23403445 – CrandellWS Nov 13 '20 at 19:18
3

The file:///android_asset protocol is a WebView-specific thing. That is: other system components can't read those URLs.

The MediaResourceGetter doesn't use the WebView's network stack and therefore doesn't "understand" the file:///android_asset protocol.

In your other question you mentioned you use a local http server - try serving the .mp4 from that.

marcin.kosiba
  • 3,221
  • 14
  • 19
  • Thanks marcin for the reply. I tried serving from my NanoHTTPD Server even, it did not work. Is it related to some permission problem ?http://stackoverflow.com/questions/14194890/playing-local-video-in-webview-on-android – saurav May 01 '14 at 08:40
  • @saurav - the question you links seems related to using the file:/// scheme. I was suggesting serving the video from http://127.0.0.1 – marcin.kosiba May 01 '14 at 08:43
  • @marcin- i did that by serving my file from assets like this InputStream httpInputStream = ApplicationManager.getInstance().getAssets() .open("MediaBook2 (2)/SampleForVideo.html"); // Return the response as a stream along with the mime type response = new NanoHTTPD.Response(Status.OK, mimeTypeFromExtension, httpInputStream); – saurav May 01 '14 at 10:05
  • but getting error "Invalid url:java.lang.RuntimeException: setDataSource failed status=0x80000000 – saurav May 01 '14 at 10:06
  • @saurav - that looks like you're serving an html file to the video decoder? – marcin.kosiba May 01 '14 at 13:34
  • i don't know the internals but i am just using the web view with the configurations mentioned above. My requirement is to load the html file which will in turn load the video and play it – saurav May 01 '14 at 13:37
  • Correct see comment here: https://stackoverflow.com/questions/23403445/not-able-to-play-video-in-web-view#comment114616250_23403445 – CrandellWS Nov 13 '20 at 19:19
0

if have still a problems about play video on android webview in 2018, let's give a chance and try code below.

Java:

    import android.app.Activity;
    import android.os.Bundle;
    import android.webkit.WebChromeClient;
    import android.webkit.WebSettings;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;

    public class MainActivity extends Activity {
        private WebView webview;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            webview = new WebView(this);
            setContentView(webview);

            final WebSettings settings = webview.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setPluginState(WebSettings.PluginState.ON);

            webview.setWebViewClient(new WebViewClient() {
                // autoplay when finished loading via javascript injection
                public void onPageFinished(WebView view, String url) { 
                    webview.loadUrl("javascript:(function() { 
                        document.getElementsByTagName('video')[0].play(); 
                    })()"); 
                }
            });
            webview.setWebChromeClient(new WebChromeClient());

            webview.loadUrl("http://html5demos.com/video");
        }

        @Override
        protected void onPause() {
            super.onPause();
            webview.onPause();
        }

        @Override
        protected void onResume() {
            webview.onResume();
            super.onResume();
        }
    }

Layout:

    <?xml version="1.0" encoding="utf-8"?>
        <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="your.package.com">

        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.WAKE_LOCK" />

        <application
            android:hardwareAccelerated="true"
            android:allowBackup="false"
            android:icon="@mipmap/logo_example"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/logo_example"
            android:supportsRtl="true"
            android:theme="@style/Theme.AppCompat.NoActionBar">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>

    </manifest>

References: https://gist.github.com/aprock/5913322

haryx8
  • 67
  • 5