Stella
Stella

Reputation: 1868

Downloading mp3 file and storing in app's directory

In my Android project, programmatically I need to download a .mp3 file from google drive download url and store in the app sandbox. Then, App can have play option to play this audio locally.

How is this possible to achieve downloading .mp3 file from server and store it locally in the app? Later, it can be played from local storage. Any help on this is very much appreciated.

Thank you.

Upvotes: 1

Views: 7382

Answers (2)

Mohamed AbdelraZek
Mohamed AbdelraZek

Reputation: 2819

a very simple solution is to use Android Download Manager Api

public void download(MediaRecords mediaRecords) {
    try {
        Toast.makeText(application, application.getString(R.string.download_started), Toast.LENGTH_SHORT).show();
        MediaRecordsOffline mediaRecordsOffline = mediaRecords.toOfflineModel();
        mediaRecordsOffline.setLocalFileUrl(Utils.getEmptyFile(mediaRecordsOffline.getId() + ".mp3").getAbsolutePath());
        dao.insertOfflineMedia(mediaRecordsOffline);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mediaRecordsOffline.getFileUrl()))
                .setTitle(mediaRecordsOffline.getName())// Title of the Download Notification
                .setDescription(mediaRecordsOffline.getDescription())// Description of the Download Notification
                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)// Visibility of the download Notification
                .setAllowedOverMetered(true)// Set if download is allowed on Mobile network
                .setDestinationUri(Uri.fromFile(Utils.getEmptyFile(mediaRecordsOffline.getId() + ".mp3")))
                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                .setAllowedOverRoaming(true);// Set if download is allowed on roaming network
        DownloadManager downloadManager = (DownloadManager) application.getSystemService(Context.DOWNLOAD_SERVICE);
        downloadManager.enqueue(request); // enqueue puts the download request in

    } catch (Exception e) {
        android.util.Log.i(TAG, "downloadManager: " + e.getMessage());
        Toast.makeText(application, application.getString(R.string.error), Toast.LENGTH_SHORT).show();
    }
}
 

Utils class which used to create the File :

public class Utils {


public static File getEmptyFile(String name) {
    File folder = Utils.createFolders();
    if (folder != null) {
        if (folder.exists()) {
            File file = new File(folder, name);
            return file;
        }
    }
    return null;
}

    public static File createFolders() {
        File baseDir = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);

        if (baseDir == null)
            return Environment.getExternalStorageDirectory();
        File aviaryFolder = new File(baseDir, ".playNow");
        if (aviaryFolder.exists())
            return aviaryFolder;
        if (aviaryFolder.isFile())
            aviaryFolder.delete();
        if (aviaryFolder.mkdirs())
            return aviaryFolder;

        return Environment.getExternalStorageDirectory();
    }

}

Upvotes: 1

Rahul Sharma
Rahul Sharma

Reputation: 6179

You can use this method:

static void downloadFile(String dwnload_file_path, String fileName,
        String pathToSave) {
    int downloadedSize = 0;
    int totalSize = 0;

    try {
        URL url = new URL(dwnload_file_path);
        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();

        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(true);

        // connect
        urlConnection.connect();

        File myDir;
        myDir = new File(pathToSave);
        myDir.mkdirs();

        // create a new file, to save the downloaded file

        String mFileName = fileName;
        File file = new File(myDir, mFileName);

        FileOutputStream fileOutput = new FileOutputStream(file);

        // Stream used for reading the data from the internet
        InputStream inputStream = urlConnection.getInputStream();

        // this is the total size of the file which we are downloading
        totalSize = urlConnection.getContentLength();

        // runOnUiThread(new Runnable() {
        // public void run() {
        // pb.setMax(totalSize);
        // }
        // });

        // create a buffer...
        byte[] buffer = new byte[1024];
        int bufferLength = 0;

        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
            downloadedSize += bufferLength;
            // update the progressbar //
            // runOnUiThread(new Runnable() {
            // public void run() {
            // pb.setProgress(downloadedSize);
            // float per = ((float)downloadedSize/totalSize) * 100;
            // cur_val.setText("Downloaded " + downloadedSize + "KB / " +
            // totalSize + "KB (" + (int)per + "%)" );
            // }
            // });
        }
        // close the output stream when complete //
        fileOutput.close();
        // runOnUiThread(new Runnable() {
        // public void run() {
        // // pb.dismiss(); // if you want close it..
        // }
        // });

    } catch (final MalformedURLException e) {
        // showError("Error : MalformedURLException " + e);
        e.printStackTrace();
    } catch (final IOException e) {
        // showError("Error : IOException " + e);
        e.printStackTrace();
    } catch (final Exception e) {
        // showError("Error : Please check your internet connection " + e);
    }
}

Call this method like this:

String SDCardRoot = Environment.getExternalStorageDirectory()
                            .toString();
                    Utils.downloadFile("http://my_audio_url/my_file.mp3", "my_file.mp3",
                            SDCardRoot+"/MyAudioFolder");

for playback:

String SDCardRoot = Environment.getExternalStorageDirectory()
                        .toString();
String audioFilePath = SDCardRoot + "/MyAudioFolder/my_file.mp3";
MediaPlayer mPlayer = new MediaPlayer();
try {
                mPlayer.setDataSource(audioFilePath);
                mPlayer.prepare();
                mPlayer.start();
            } catch (IOException e) {
                Log.e("AUDIO PLAYBACK", "prepare() failed");
            }

Upvotes: 5

Related Questions