Android: Playing an Asset Sound Using WebView

后端 未结 1 572
陌清茗
陌清茗 2020-12-05 15:52

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

相关标签:
1条回答
  • 2020-12-05 16:48

    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().

    0 讨论(0)
提交回复
热议问题