简体   繁体   中英

How to download music .mp3 files to app storage in android?

Music files should be downloaded to the app itself, it shouldn't get stored on mobile memory (file manager or SD card).

FileManager Class to store mp3 file inside app folders.

public class FileManager {

    private final Context context;

    FileManager(Context context) {
        this.context = context;
    }

    public String getRootPath() {
    File file = new File(context.getFilesDir(),"");
    return file.getAbsolutePath();
}
public String getFilePath(String name) {
        File file = new File(context.getFilesDir(), name);
        return file.getAbsolutePath();
    }
  }

Download request

@RequiresApi(api = Build.VERSION_CODES.O)
    private void initDownload(String soundUri) {
        Log.d(TAG, "initDownload: " + soundUri);

        Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).build();

        ApiService retrofitInterface = retrofit.create(ApiService.class);
        Call<ResponseBody> request = retrofitInterface.downloadFile(soundUri);

        request.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
               if (response.body() != null) {
                    Thread thread = new Thread(() -> {
                        try {
                            saveVoice(response.body());
                        } catch (IOException e) {
                            Log.d(TAG, "onResponse: " + e);
                        }
                    });
                    thread.start();
                }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {

        }
    });
    }




@RequiresApi(api = Build.VERSION_CODES.O)
private void saveVoice(ResponseBody body) throws IOException {
    try {
        String mp3Key= "YOUR_KEY_TO_STORE_FILE";

        int count;
        byte data[] = new byte[1024 * 4];
        InputStream bis = new BufferedInputStream(body.byteStream(), 1024 * 8);
        File outputFile = new File(fileManager.getRootPath(), voiceKey);
        OutputStream output = new FileOutputStream(outputFile);
        long startTime = System.currentTimeMillis();
        int timeCount = 1;
        while ((count = bis.read(data)) != -1) {

            long currentTime = System.currentTimeMillis() - startTime;

            if (currentTime > 1000 * timeCount) {

                timeCount++;
            }
            output.write(data, 0, count);
        }
        output.flush();
        output.close();
        bis.close();
    } catch (Exception e) {
        Log.d(TAG, "saveVoice: " + e);
    }
}

After successfully download you can read file with the key that you wrote file to app storage. To do that:

String filePath = fileManager.getFilePath(mp3Key); // filePath returns local url of file

For example, you can do:

 mediaPlayer.setDataSource(filePath );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM