I am trying to play a sound from the assets folder when a user clicks on an tag on my application\'s WebView. I found that I can use a new class extending WebViewClient to
Where you declare your MediaPLayer
in MyWebViewClient
, add the following...
public class MyWebViewClient extends WebViewClient{
public MediaPlayer mp;
private Context context = null; // Add this line
...
}
Then add a constructor to MyWebViewClient
as follows...
public MyWebViewClient(Context context) {
this.context = context;
}
Then in shouldOverrideUrlLoading(...)
get your assets as follows...
AssetFileDescriptor afd = context.getAssets().openFd(url);
In your MainActivity
set the WebViewClient
by passing this
(which is the Activity Context
) as follows...
webMain.setWebViewClient(new MyWebViewClient(this));
Also you should return false
from shouldOverrideUrlLoading(...)
if the url ends with '.mp3' - this shows your WebView
is handling things and the 'host' application should not start an instance of the stock web browser.
EDIT: To play audio files from the assets directory, you need to set the data source differently - see the accepted answer to play-audio-file-from-the-assets-directory.
Also you should call mp.prepare()
before calling mp.start()
.