JOHN JOHNNNY

JOHN JOHNNNY

  • NA
  • 190
  • 140k

Adding play/pause to html file in webview

Jul 22 2016 11:59 AM
Hi Everyone<br />I developed an app that requires mp3 audio file to be played <br />whenever the user clicks on a button in html file displaying in a webview.<br />While testing the app the audio file plays well in the webview but after exiting<br />the app the sound continues to play i tried adding a stop/pause button but not working<br />Kindly help and below is my code<br /><br />HTML<br />&lt;body&gt;<br />&lt;div class="clear"&gt;<br /> &lt;button onclick="AndAud.playAudio('audio/hymn42.mp3');"&gt;Play Audio&lt;/button&gt;<br /> &lt;br&gt;<br /> &lt;button onclick="AndAud.pauseAudio('audio/hymn42.mp3');"&gt;Pause Audio&lt;/button&gt;<br /> &lt;br&gt;<br /> &lt;button onclick="AndAud.stopAudio('audio/hymn42.mp3');"&gt;Stop Audio&lt;/button&gt;<br /><br />&lt;/div&gt;<br />&lt;/body&gt;<br /><br />Webview<br />public class MainActivity extends ActionBarActivity {<br /><br /> WebView myWebView;<br /> Context context;<br /><br /> @Override<br /> protected void onCreate(Bundle savedInstanceState) {<br /> super.onCreate(savedInstanceState);<br /> setContentView(R.layout.activity_main);<br /><br /> WebView myWebView = (WebView) findViewById(R.id.webview);<br /><br /> //Set it to a webChromeClient<br /> myWebView.setWebChromeClient(new WebChromeClient());<br /><br /> //the default for WebView is that JavaScript isn't enabled in WebView<br /> myWebView.getSettings().setJavaScriptEnabled(true);<br /><br /> //the index.html file is placed in the assets folder<br /> myWebView.loadUrl("file:///android_asset/hymnpage20.html");<br /><br /> myWebView.addJavascriptInterface(new AudioInterface(this), "AndAud");<br /> }<br /><br />Audio Interface Activity<br /><br />public class AudioInterface {<br /> Context mContext;<br /><br /> AudioInterface(Context c) {<br /> mContext = c;<br /> }<br /><br /> //Play an audio file from the webpage<br /> @JavascriptInterface<br /> public void playAudio(String aud) { //String aud - file name passed<br /> //from the JavaScript function<br /> final MediaPlayer mp;<br /><br /> try {<br /> AssetFileDescriptor fileDescriptor =<br /> mContext.getAssets().openFd(aud);<br /> mp = new MediaPlayer();<br /> mp.setDataSource(fileDescriptor.getFileDescriptor(),<br /> fileDescriptor.getStartOffset(),<br /> fileDescriptor.getLength());<br /> fileDescriptor.close();<br /> mp.prepare();<br /> mp.start();<br /> } catch (IllegalArgumentException e) {<br /> // TODO Auto-generated catch block<br /> e.printStackTrace();<br /> } catch (IllegalStateException e) {<br /> // TODO Auto-generated catch block<br /> e.printStackTrace();<br /> } catch (IOException e) {<br /> // TODO Auto-generated catch block<br /> e.printStackTrace();<br /> }<br /><br /> }

Answers (1)