【问题标题】:How can I download a mp3 file on Android?如何在 Android 上下载 mp3 文件?
【发布时间】:2021-12-11 09:10:20
【问题描述】:

如何从 Android 下载目录中的 URL 下载 .mp3 文件?
使用OutputStreamInputStream 显然不再起作用了。这是我尝试过的:

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

    private final String videoUrl;

    public DownloadFile(String videoUrl) {
        this.videoUrl = videoUrl;
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            URL url = new URL(videoUrl);
            URLConnection connection = url.openConnection();
            connection.connect();

            InputStream input = new BufferedInputStream(url.openStream());

            String test = Environment.getExternalStorageDirectory() + "/Download/test.mp3";
            OutputStream output = new FileOutputStream(test);

            byte[] data = new byte[1024];

            output.write(data);

            output.flush();
            output.close();
            input.close();
        } catch (Exception ignored) {
        }
        return null;
    }
}

这可以下载文件,但尝试播放时收到错误消息saying that I can't play this type of audio file

另外,上面的代码来自previous question

【问题讨论】:

  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。
  • 您没有从输入流中读取数据。应该有一个循环。
  • 如果我想播放 mp3 文件而播放器无法识别或无法播放 mp3 文件,我假设我没有下载 mp3 文件 - 或者它是播放器问题,正如我所说。

标签: java android android-studio kotlin


【解决方案1】:

你知道 Android 的 DownloadManager 类吗 (https://developer.android.com/reference/android/app/DownloadManager)

 
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("your url here"));
request.setDescription("Downloading");
request.setMimeType("audio/MP3");
request.setTitle("File :");
request.allowScanningByMediaScanner();         
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "audio.mp3");
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);

【讨论】:

  • 是的,我试过这个代码,但播放器也不播放音频。我不确定我下载的不是 MP3 文件还是播放器的问题。
猜你喜欢
  • 2015-03-22
  • 2013-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-04
  • 1970-01-01
相关资源
最近更新 更多