Android MediaPlayer可以在压缩文件中播放音频吗?

编辑编码:

我正在为Android开发一个字典应用程序。 我一直在成功地让应用程序发出每个单词被查找。 这是代码:

btnPronounce.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub //Log.i(MAIN_TAG,"Start pronounciation ..."); btnPronounce.setEnabled(false); String currentWord = edWord.getText().toString().toLowerCase(); try { ZipFile zip = new ZipFile("/sdcard/app_folder/sound/zip_test.zip"); ZipEntry entry = zip.getEntry(currentWord); if (entry != null) { InputStream in = zip.getInputStream(entry); // see Note #3. File tempFile = File.createTempFile("_AUDIO_", ".wav"); FileOutputStream out = new FileOutputStream(tempFile); IOUtils.copy(in, out); // do something with tempFile (like play it) File f = tempFile; try { if (f.exists()) { Log.i(MAIN_TAG,"Audio file found!"); MediaPlayer mp = new MediaPlayer(); mp.prepare(); mp.setLooping(false); mp.start(); while (mp.getCurrentPosition() < mp.getDuration()); mp.stop(); mp.release(); Log.i(MAIN_TAG,"Pronounciation finished!"); } else { Log.i(MAIN_TAG,"File doesn't exist!!"); } } catch (IOException e) { Log.i(MAIN_TAG,e.toString()); } btnPronounce.setEnabled(true); } else { // no such entry in the zip } } catch (IOException e) { // handle your exception cases... e.printStackTrace(); } } }); 

但问题是一个文件夹中的WAV文件太多,所有这些文件都被Android设备视为音乐文件。 因此,索引此类文件需要很长时间。 此外,索引和用户浏览有时会迫使应用程序崩溃。

因此,我只是想知道以下是否可以通过编程方式完成:

  1. Android MediaPlayer可以播放压缩或包装在单个文件中的WAV / MP3文件吗? 我的意思是我想压缩或包装音频文件(或做类似的事情),以便它们作为单个文件出现在Android设备上,但MediaPlayer仍然可以播放内部的每个单独的WAV文件。
  2. 如果以上是不可能的,你们可以建议解决问题吗?

编辑:有没有其他方法/解决方案,允许将音频文件简单地放入一个大文件(图像,zip或类似…),然后让MediaPlayer读取其中的单个文件?

非常感谢你。

您可以使用ZipFileZipInputStreamjava.io文件操作的组合来从zip读取必要的数据,创建临时文件并使用MediaPlayer播放这些文件。

或者,您可以使用TTS引擎,而不是传递50万亿字节的APK。

编辑 – 按请求示例:

 try { ZipFile zip = new ZipFile("someZipFile.zip"); ZipEntry entry = zip.getEntry(fileName); if (entry != null) { InputStream in = zip.getInputStream(entry); // see Note #3. File tempFile = File.createTempFile("_AUDIO_", ".wav"); FileOutputStream out = new FileOutputStream(tempFile); IOUtils.copy(in, out); // do something with tempFile (like play it) } else { // no such entry in the zip } } catch (IOException e) { // handle your exception cases... e.printStackTrace(); } 

笔记:

  1. 我这里没有包含任何安全的文件处理方法。 随你(由你决定。

  2. 这不是实现目的的方法 ,只是一种方法 。 可能有100种其他方式,其中一些可能更适合您的需要。 我没有使用ZipInputStream只是因为涉及到更多的逻辑而我只是为了简洁。 您必须检查每个条目以查看它是否是您正在寻找的ZipInputStream ,而ZipFile允许您只是通过名称询问您想要的内容。 我不确定使用其他任何一个会产生什么(如果有的话)性能影响。

  3. 绝不是你需要使用临时文件(或者根本就是文件),但Android的MediaPlayer并不真正喜欢流,所以这可能是最简单的解决方案。

您应该考虑的另一种方法是在用户想要收听发音时下载单个声音文件。 这应该会减小文件大小,但它确实意味着在没有Internet的情况下你不能听发音。