下载mp3文件并存储在app的目录中

时间:2015-04-23 06:58:28

标签: android

在我的Android项目中,我需要以编程方式从谷歌驱动器下载网址下载.mp3文件并存储在应用程序沙箱中。然后,App可以有播放选项在本地播放此音频。

如何从服务器上下载.mp3文件并将其存储在应用程序中?之后,它可以从本地存储播放。对此非常感谢。

谢谢。

2 个答案:

答案 0 :(得分:4)

您可以使用此方法:

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

像这样调用这个方法:

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

播放:

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

答案 1 :(得分:0)

一个非常简单的解决方案是使用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();
    }
}
 

用于创建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();
    }

}