Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play audio on webview in android?

Tags:

android

I want to play an audio from a URL on webview. I also want it to have play and pause button. I have tried opening the URL directly like this:-

myView = (WebView) findViewById(R.id.webView);
    myView.getSettings().setJavaScriptEnabled(true);
    myView.loadUrl(myUrl);

But this isn't working.

like image 352
Pankaj Kumar Avatar asked Feb 07 '23 04:02

Pankaj Kumar


2 Answers

This can be done through Javascript Interface

Create a Class WebInterface

public class WebInterface{
    Context mContext;

    WebInterface(Context c) {
        mContext = c;
    }

    @JavascriptInterface
    public void playSound(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }

    @JavascriptInterface
    public void pauseSound(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
}

In your WebView class

WebView browser;
browser=(WebView)findViewById(R.id.webkit);   
browser.getSettings().setJavaScriptEnabled(true);
browser.addJavascriptInterface(new WebInterface(this), "Android");        
browser.loadUrl("http://someurl.com");

In HTML code

<html>
<head>
<script type="text/javascript">
    function playSound(toast) {
        Android.showToast(toast);
    }

    function pauseSound(toast) {
        Android.showToast(toast);
    }
</script>
</head>
<body>
<input type="button" value="Say hello" onClick="playSound('Sound Played!')" />
<input type="button" value="Say hello" onClick="pauseSound('Sound Paused!')" />
</body>
</html>
like image 81
Murtaza Khursheed Hussain Avatar answered Feb 11 '23 14:02

Murtaza Khursheed Hussain


Try, this is the working code,

 WebView mWebView;
 mWebView = (WebView)findViewById(R.id.webView);

    // Enable Javascript
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    mWebView.loadUrl("http://www.stephaniequinn.com/Music/Allegro%20from%20Duet%20in%20C%20Major.mp3");

    // Force links and redirects to open in the WebView instead of in a browser
    mWebView.setWebViewClient(new WebViewClient());

i tried with one sample audio url. it should work.

Happy Coding..!!!

like image 40
Sathish Kumar J Avatar answered Feb 11 '23 16:02

Sathish Kumar J