【问题标题】:Playing AUDIO from WebView从 WebView 播放音频
【发布时间】:2021-07-21 00:34:07
【问题描述】:

我一直在寻找如何在 webview 中播放来自任何网站的音频?

我注意到 Chrome 浏览器正在播放音频,但我的 WebView 应用没有播放。 你能提供我任何资源或代码sn-p吗?

提前致谢!

【问题讨论】:

    标签: android webview audio-player


    【解决方案1】:

    试试这个,希望它能解决你的问题。

    WebView webView = findViewById(R.id.webview);
    webView.setWebViewClient(new WebViewClient());
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setAllowContentAccess(true);
    webSettings.setDomStorageEnabled(true);
    webView.loadUrl(url);
    

    另外,将android:hardwareAccelerated="true" 添加到清单中的activity tag 中。

    【讨论】:

      【解决方案2】:

      这可以通过Javascript接口完成

      创建类 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>
      

      【讨论】:

      • 感谢您的快速回答,但请告诉我如何添加以下 HTML 代码以及应在何处添加?强烈推荐您的帮助!
      • 不客气!!现在非常习惯这些问题,因此快速回答。老实说,我对这个位置不太熟悉,因为在我的一个课程中编写代码是一个挑战,但我确实发现 webtoolkitonline 有一个很棒的界面,而且编写代码真的很好,所以试试吧!对不起,如果我没有太多帮助。祝你好运!
      • 您导出了 Android.playSound() 和 .pauseSound() 但您改为调用 Android.showToast()。这不是错误吗?
      猜你喜欢
      • 2015-05-27
      • 2011-05-29
      • 2012-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-15
      相关资源
      最近更新 更多