Can Android MediaPlayer play audio in a zipped file?

落爺英雄遲暮 提交于 2019-12-05 13:58:19

You can use a combination of ZipFile or ZipInputStream and java.io file operations to read the necessary data from the zip, create temp files and play those using MediaPlayer.

Alternatively, you could just use a TTS engine and not pass out a 50-bagillion-byte APK.

Edit - Example by request:

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();
}

Notes:

  1. I didn't include any safe file handling practices here. That's up to you.

  2. This isn't the way to do it, only a way to do it. There are probably 100 other ways, some of which may be better suited to what you need. I didn't use ZipInputStream simply because there's a little more logic involved and I was going for brevity. You have to check every entry to see if it's what you're looking for with ZipInputStream, whereas ZipFile allows you to just ask for what you want by name. I'm not sure what (if any) performance implications using either over the other would have.

  3. By no means are you required to use temp files (or files at all, really), but Android's MediaPlayer doesn't really like streams, so this is probably the easiest solution.

An alternative you should consider is to download the individual sound files when the user want to listen to a pronunciation. This should reduce the file size although it does mean that you can't listen to a pronunciation when there is no Internet.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!