从zip文件播放媒体而不解压缩

时间:2013-02-24 19:36:31

标签: android zip android-mediaplayer

我知道在SO上已经存在这样的一些问题,但它们与在播放之前提取文件有关。

在Android文档here中,它解释了您可以直接从.zip文件播放文件而无需将其解压缩。

  

提示:如果要将媒体文件打包成ZIP,则可以使用媒体   使用偏移和长度控件(例如   MediaPlayer.setDataSource()和SoundPool.load())无需   打开你的ZIP。为了使其工作,您不能执行   创建ZIP时对媒体文件进行额外压缩   包。例如,使用zip工具时,应使用-n   选项以指定不应压缩的文件后缀:

     

zip -n .mp4; .ogg main_expansion media_files

我已经制作了一个(未压缩的)zip包,但是我无法弄清楚如何从ZipEntryFileDescriptor,他们没有进一步解释。如何在不解压缩zip文件的情况下获得FileDescriptor

4 个答案:

答案 0 :(得分:2)

即使您未在自己的应用中使用APK扩展程序,也可以使用 APK扩展程序库来执行此操作。

请按照此文档获取库:Using the APK Expansion Zip Library

使用您喜欢的拉链工具将您的声音文件压缩而无需压缩。

使用此代码加载音乐:

ZipResourceFile expansionFile = new ZipResourceFile("myZipFile.zip");
AssetFileDescriptor assetFileDescriptor = expansionFile.getAssetFileDescriptor("myMusic.mp3");
try {
    mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor());
    mediaPlayer.prepare();
    mediaPlayer.start();
}
catch (IOException e) {
    // Handle exception
}

答案 1 :(得分:1)

try {
    ZipFile zf= new ZipFile(filename);
    ZipEntry ze = zip.getEntry(fileName);
    if (ze!= null) {
        InputStream in = zf.getInputStream(ze);
        File f = File.createTempFile("_AUDIO_", ".wav");
        FileOutputStream out = new FileOutputStream(f);
        IOUtils.copy(in, out);
        // play f
    }
} catch (IOException e) {

}

possible duplicate question

答案 2 :(得分:1)

针对此问题的最新解决方案并不多,所以我也一直坚持这一做法–直到我在尝试读取zip文件的函数中创建MediaPlayer的新实例。突然开始播放,没有问题。现在,我将(全局)MediaPlayer传递给如下函数:(Kotlin)

private fun preparePlayer(mp: MediaPlayer, position: Int) {

    // Path of shared storage
    val root: File = Environment.getExternalStorageDirectory()
    Log.i("ROOT", root.toString())

    // path of the zip file
    val zipFilePath = File(root.absolutePath+"/Android/obb/MY_PACKAGE_NAME/MY_ZIP_FILE.zip")

    // Is zip file recognized?
    val zipFileExists = zipFilePath.exists()
    Log.i("Does zip file exist?", zipFileExists.toString())

    // Define the zip file as ZipResourceFile
    val expansionFile = ZipResourceFile(zipFilePath.absolutePath)

    // Your media in the zip file
    val afd = expansionFile.getAssetFileDescriptor("track_01.mp3")

    // val mp = MediaPlayer()   // not necessary if you pass it as a function parameter
    mp.setDataSource(afd.fileDescriptor, afd.startOffset, afd.length)
    mp.prepare()
    mp.start()   // Music should start playing automatically

也许这可以帮助其他人。祝你好运!

答案 3 :(得分:0)

如果您想使用zip解压缩的媒体文件而不解压缩,则必须将起始偏移量和长度添加到setDataSource

ZipResourceFile expansionFile = new ZipResourceFile("myZipFile.zip");
AssetFileDescriptor assetFileDescriptor = expansionFile.getAssetFileDescriptor("myMusic.mp3");
try {
    mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),
                              assetFileDescriptor.getStartOffset(),
                              assetFileDescriptor.getLength());
    mediaPlayer.prepare();
    mediaPlayer.start();
}
catch (IOException e) {
    // Handle exception
}
相关问题