gpt4 book ai didi

android - 使用 shouldInterceptRequest() 在 Android WebView 中音频不工作

转载 作者:行者123 更新时间:2023-11-27 23:33:30 26 4
gpt4 key购买 nike

我的 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>

我的安卓代码:

    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 (连结 5)Android 系统 WebView 版本 47

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

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

最佳答案

我发现这个问题的解决方法并不优雅,但它是唯一对我有用的方法:将音频文件写入 SD 卡 :(。
阶段 1):当使用章节 url 调用 shouldInterceptRequest() 时。
该章节首先被拦截(在其他章节资源(图像、音频、字体、..)被拦截之前。
当章节被拦截时,我们在 html 中搜索 <audio> 标签。如果找到,我们替换相对路径(例如 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)

阶段 3) 当使用章节 url 调用 shouldInterceptRequest() 时, 我们删除临时音频文件 注意:如果您按照代码进行操作,您会看到这是 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));
}
}

关于android - 使用 shouldInterceptRequest() 在 Android WebView 中音频不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34796550/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com