下载音频 Zip 文件并将它们保存在内部存储中并使用媒体播放器播放

时间:2021-01-17 00:36:38

标签: java android

代码

请指导我如何存储(音频)文件,以便我可以在媒体播放器上将它们用作播放列表,或者告诉我是否做错了什么,我之前没有处理过文件,所以任何简洁和基本的解释将不胜感激。提前致谢

ps,我能够读取 logcat 中的文件名,这意味着我正在获取或下载它们?

 @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        protected Void doInBackground(String... strings) {
            try {


//                mediaPlayer.setDataSource("http://www.archive.org/download/i_do_not_love_thee_norton_librivox/i_do_not_love_thee_norton_librivox_64kb_mp3.zip");
//                mediaPlayer.prepare();
//                duration = mediaPlayer.getDuration();

                //TODO: CONTINUE FROM HERE (THE DATA HAS BEEN DOWNLOADED IN THE BACKGROUND THREAD)
                //InputStream fis = new URL("http://www.archive.org/download/i_do_not_love_thee_norton_librivox/i_do_not_love_thee_norton_librivox_64kb_mp3.zip").openConnection().getInputStream();
                URL url = new URL("http://www.archive.org/download/sonnets_portugese_knf_librivox/sonnets_portugese_knf_librivox_64kb_mp3.zip");
                URLConnection urlConnection = url.openConnection();

                //URL url = new URL("http://www.archive.org/download/tristan_iseult_librivox/tristan_iseult_librivox_64kb_mp3.zip/");
                //URLConnection connection = url.openConnection();
                ZipInputStream zis = new ZipInputStream(urlConnection.getInputStream());

                ZipEntry ze;
                //TODO: SETTING UP PROGRESS
//
                int count = 0;
                while ((ze = zis.getNextEntry()) != null) {
                    count++;
                    /**
                     * FILES ARE NOT IN ORDER AT THE TIME OF DOWNLOADING
                     */

                    //TODO: HOW TO SAVE EACH ZIPENTRY (AUDIO FILE) IN ORDER TO PLAY THEM WITH MEDIAPLAYER?
                    name += count + ze.getName() + "\n";
                    //publishProgress(""+(int)((total*100)/lenghtOfFile));
                    Log.d("This", "doInBackground: " + ze.getName() + "\n");// + " Size: " + ze.getSize() + " Time: " + ze.getTime()


                    //zis.closeEntry();
                }

                zis.close();

            } catch (IOException e) {
                Log.d("This", "doInBackground: " + e.getMessage());

            }


            return null;
        }

1 个答案:

答案 0 :(得分:-1)

您正在尝试下载并解压缩文件。有两种方法

<块引用>
  1. 以编程方式下载然后解压缩,然后在文件资源管理器中再次保存
  2. 获取文件,然后解压缩,然后下载。

我不确定没有。 2 行不行。我正在正确查看您的源代码。不幸的是,我注意到您可以获取文件名,但是您似乎无法将其保存到文件资源管理器中。我不确定我是否错了。我是说那个原因,我们不会按照你写的方式下载。

我在这里implementing一些源代码

public class DownloadVideoAsyncTask extends AsyncTask<String, Integer, String> {

private Context mContext;

public DownloadVideoAsyncTask(Context context) {
    mContext = context;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();

}

@Override
protected String doInBackground(String... sUrl) {
    InputStream input = null;
    OutputStream output = null;
    HttpURLConnection connection = null;
    try {
        URL url = new URL(sUrl[0]);
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        // expect HTTP 200 OK, so we don't mistakenly save error report
        // instead of the file
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return "Server returned HTTP " + connection.getResponseCode()
                    + " " + connection.getResponseMessage();
        }

        // this will be useful to display download percentage
        // might be -1: server did not report the length
        int fileLength = connection.getContentLength();

        // download the file
        input = connection.getInputStream();

        //output = new FileOutputStream("/data/data/com.example.vadym.test1/textfile.txt");
        output = new FileOutputStream(mContext.getFilesDir() + "/file.mp4");

        byte data[] = new byte[4096];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            // allow canceling with back button
            if (isCancelled()) {
                input.close();
                return null;
            }
            total += count;
            // publishing the progress....
            if (fileLength > 0) // only if total length is known
                publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
        }
    } catch (Exception e) {
        return e.toString();
    } finally {
        try {
            if (output != null)
                output.close();
            if (input != null)
                input.close();
        } catch (IOException ignored) {
        }

        if (connection != null)
            connection.disconnect();
    }
    return null;
}

@Override
protected void onProgressUpdate(Integer... values) {
    super.onProgressUpdate(values);
    Log.d("ptg", "onProgressUpdate: " + values[0]);

}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);

}
}

我有更简单的源代码。但是,我必须下载那个。可能需要很长时间。虽然我会努力。在那之前,你试试吧。

如何以编程方式解压缩?我正在实施两次网站链接

  1. stackoverflow question
  2. codejava

如果你完全相信java,那么我希望你能在android studio中实现codejava的源代码。

private boolean unpackZip(String path, String zipname)
{       
 InputStream is;
 ZipInputStream zis;
 try 
 {
     is = new FileInputStream(path + zipname);
     zis = new ZipInputStream(new BufferedInputStream(is));          
     ZipEntry ze;

     while((ze = zis.getNextEntry()) != null) 
     {
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         byte[] buffer = new byte[1024];
         int count;

         String filename = ze.getName();
         FileOutputStream fout = new FileOutputStream(path + filename);

         // reading and writing
         while((count = zis.read(buffer)) != -1) 
         {
             baos.write(buffer, 0, count);
             byte[] bytes = baos.toByteArray();
             fout.write(bytes);             
             baos.reset();
         }

         fout.close();               
         zis.closeEntry();
     }

     zis.close();
 } 
 catch(IOException e)
 {
     e.printStackTrace();
     return false;
 }

return true;
}

这样您就可以解压缩文件。我认为这个源代码的输出会在主文件上重写。

编辑: 如何下载

File locationImage = new File(Environment.getExternalStorageDirectory()
                        + "/Socio-Book/pictures/"+name+".png");


                //save image to internal storage
                direct = new File(Environment.getExternalStorageDirectory()
                        + "/Socio-Book/pictures");

                if (!direct.exists()) {
                    direct.mkdirs();
                }


                //save data to sqlite DB
                    boolean check=mydb.insertData(id,name,pass);

                //download image or not
                if(!locationImage.exists()) {
                    DownloadManager mgr = (DownloadManager) getApplicationContext().getSystemService(Context.DOWNLOAD_SERVICE);
                    Uri downloadUri = Uri.parse(Constant.BASE_URL+"/y_chat/sign_up/"+name+"/profile.png");
                    DownloadManager.Request request = new DownloadManager.Request(
                            downloadUri);


                    request.setAllowedNetworkTypes(
                            DownloadManager.Request.NETWORK_WIFI
                                    | DownloadManager.Request.NETWORK_MOBILE)
                            .setAllowedOverRoaming(false).setTitle("Image")
                            .setDestinationInExternalPublicDir("/Socio-Book/pictures", name + ".png");

                    mgr.enqueue(request);

以下源代码需要更多说明

Uri downloadUri = Uri.parse(Constant.BASE_URL+"/y_chat/sign_up/"+name+"/profile.png");
DownloadManager.Request request = new DownloadManager.Request(
                            downloadUri);

它来自我上面的源代码。 Uri 是文件的位置(链接)。我在这里写的 Constant.BASE_URL 是网站链接。其他是文件的位置。

Uri downloadUri = Uri.parse("http://www.archive.org/download/sonnets_portugese_knf_librivox/sonnets_portugese_knf_librivox_64kb_mp3.zip");