【问题标题】:Audio not working in Android WebView using shouldInterceptRequest()使用 shouldInterceptRequest() 在 Android WebView 中音频不起作用
【发布时间】:2016-04-20 04:33:33
【问题描述】:

我的 Android 应用在 WebView 中显示 html5 电子书。
我有一个包含所有资源的电子书的压缩文件:文本、图像和音频(mp3 文件)。
为了解压这本书,我使用了 shouldInterceptRequest(),它拦截 file:///... 请求,并通过 WebResourceResponse 对象返回数据。该代码适用于文本和图像。
当我访问音频资源时,出现运行时错误,并且无法播放音频文件。
注意:我确实看到返回的解压缩文件大小正确(大约 10MB)。

我收到的错误消息:
cr_MediaResourceGetter 文件不存在
cr_MediaResourceGetter 无法配置元数据提取器

我的音频 HTML 代码:

<div xmlns="http://www.w3.org/1999/xhtml">
  <p style="text-align:center;margin:0px;">
    <audio controls="controls" src="../Audio/01-AudioTrack-01.mp3">Your browser does not support the audio tag.</audio>
    <br />
  </p>
</div>

我的 Android 代码:

    setWebViewClient(new WebViewClient()
    {
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, final String url)
    {
        String urlWithoutAnchor = URLUtil.stripAnchor(url); 
        String fileName = urlWithoutAnchor;

        try {
            byte [] resource = tbxPool.getResource(fileName); 
         /* SIMPLE VERSION without calling setResponseHeaders():
            return new WebResourceResponse(mimeType, "UTF-8", new ByteArrayInputStream(resource)); 
            */
            WebResourceResponse returnedMediaResource = new WebResourceResponse(mimeType, "UTF-8", new ByteArrayInputStream(resource));
            if (mimeType.toLowerCase().startsWith("audio")) {
                Map<String, String> responseHeaders = new HashMap<String, String>();

                responseHeaders.put("Content-Type", mimeType);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//2CLEAN
                    returnedMediaResource.setResponseHeaders(responseHeaders); 
                    Logger.v(TAG, "Response Headers added to audio resource");
                }
                else {
                    //TODO: Handle else for API<21. Toast?
                }
            }                               
            return returnedMediaResource;
        } catch (IOException e) {
            Logger.e(TAG, "failed to load resource "+fileName,e);
            return null;
        }
    }
}

环境
安卓 6.0.1 (Nexus 5) Android 系统 WebView 版本 47

需求说明
音频将像 html5 文档一样在浏览器中播放,无需启动外部播放器。

问题:
我究竟做错了什么?!非常感谢!

【问题讨论】:

    标签: android html audio android-webview android-mediaplayer


    【解决方案1】:

    我发现这个问题的解决方法并不优雅,但它是唯一对我有用的方法:将音频文件写入 sd 卡:(.
    阶段 1):何时使用章节 URL 调用 shouldInterceptRequest()。
    首先截取章节(在截取其他章节资源(图像、音频、字体...)之前。
    当章节被截取时,我们在 html 中搜索 &lt;audio&gt; 标签。如果找到,我们替换相对路径(例如 SRC="../Audio/abc.mp3") 带有绝对路径(例如 SRC="/storage/tmp/abc.mp3")

    第 2 阶段):何时使用音频 url 调用 shouldInterceptRequest()。
    你的注意力。像所有解决方法一样,这有点棘手(但有效!):
    在第 1 阶段之后)音频 url 将是一个绝对 url(绝对 url 是现在写在修改后的 html 中的内容)。
    我们现在必须做两件事:
    a) 从压缩的 epub 中读取音频文件。
    为此,我们需要“欺骗”代码,并从其原始压缩相对 url 中读取音频文件,例如“../Audio/abc.mp3”在我们的例子中 (尽管 shouldInterceptRequest 已使用“/storage/tmp/abc.mp3”调用)。
    b) 读取压缩后的音频文件后,将其写入存储(sdcard)

    Stage 3) 当 shouldInterceptRequest() 使用章节 URL 调用时, 我们删除临时音频文件 注意:如果您按照代码进行操作,您将看到这是 shouldInterceptRequest() 中的步骤 0),在阶段 1) 之前执行,但我发现上面的解释更清楚。

    if (isChapterFile(mimeType)) {  
        deleteTempFiles(); // this line is stage 3)  
            changeAudioPathsInHtml(tzis); // this line is stage 1)
    

    这是代码:

    setWebViewClient(new WebViewClient()
    {
        private String tmpPath = TbxApplication.getAppPath(null) + "/tmp/"; 
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, final String url) 
        {
            Logger.d(TAG, "in shouldInterceptRequest for " + url);  
            String urlWithoutAnchor = URLUtil.stripAnchor(url); 
            String mimeType = StringUtils.getFileMimeType(urlWithoutAnchor);
            String urlWithoutBase; //the url stripped from leading 'epubBaseUrl' (base url for example:"file:///storage/.../123456.tbx")
    
                if (isAudioFile(mimeType)) { //write AUDIO file to phone storage. See AUDIO WORKAROUND DOCUMENTATION    
                    String storagePath = StringUtils.truncateFileScheme(url);  //WebView calls shoudlInterceptRequest() with "file://..."
                    try {
                        String oEBPSAudioPath = storagePathToOEBPSAudioPath(storagePath); //e.g. change"/storage/tmp" to "OEBPS/Audio/abc.mp3"
                        byte[] audioBytes = tbxPool.getMedia(oEBPSAudioPath); 
                        FileUtils.writeByteArrayToFile(audioBytes, storagePath); //TODO: To be strict, write in separate thread
                        Logger.d(TAG, String.format("%s written to %s", oEBPSAudioPath, storagePath));
                        return null;//webView will read resource from file
                                    //Note: return new WebResourceResponse("audio/mpeg", "UTF-8", new ByteArrayInputStream(audioBytes));
                                    //did NOT work,so we had to change html for audio to point to local storage & write to disk
                                    //see AUDIO WORKAROUND DOCUMENTATION in this file
                    } catch (Exception e) {
                        Logger.e(TAG,e.getMessage());
                        return null;
                    } 
                } 
                .....
                else {
                    if (isChapterFile(mimeType)) { //This is a CHAPTER
                        deleteTempFiles(); //Loading a new chapter. Delete previous chapter audio files. See AUDIO WORKAROUND DOCUMENTATION in this file
                        InputStream htmlWithChangedAudioPaths = changeAudioPathsInHtml(tzis); //see AUDIO WORKAROUND DOCUMENTATION in this file
                        WebResourceResponse webResourceResponse = new WebResourceResponse(mimeType, "UTF-8", htmlWithChangedAudioPaths);
                        return webResourceResponse; 
                    }
    
            //Changes relative paths of audio files, to absolute paths on storage
            //see AUDIO WORKAROUND DOCUMENTATION in this file
            private InputStream changeAudioPathsInHtml(InputStream inputStream) {
                String inputString = StringUtils.inputStreamToString(inputStream);
                String outputString = inputString.replaceAll("\"../Audio/", "\"" + tmpPath);// e.g. SRC="../Audio/abc.mp3" ==>SRC="/sdcard/tmp/abc.mp3"                                                                              //where '*' stands for multiple whitespaces would be more elegant
                return StringUtils.stringToInputStream(outputString); 
            }
    
            /** Example:
             * storagePath="/storage/tmp/abc.mp3
             * Returns: "OEBPS/Audio/abc.mp3"*/
            private String storagePathToOEBPSAudioPath(String storagePath){
                String fileName = StringUtils.getFileName(storagePath);
                String tbxOEBPSAudioPath = "OEBPS/Audio/" + fileName;
                return tbxOEBPSAudioPath; 
            }
    
    public static void writeByteArrayToFile(byte[] byteArray, String outPath) { 
        try {
            File file = new File(outPath);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(byteArray);
            fos.close();
        } catch (IOException e) {
            Logger.e(TAG, String.format("Could not write %s", outPath));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 2021-08-30
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-21
      • 2015-04-20
      相关资源
      最近更新 更多