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