【问题标题】:Android. To download mp3 properly安卓。正确下载 mp3
【发布时间】:2015-07-28 09:02:14
【问题描述】:

我遇到了一个奇怪的问题。我编写用于下载 mp3 文件的 android 应用程序。我用 url 下载 mp3,效果很好。但是除了 VLC 之外的任何播放器都无法在设备上找到这些下载的 mp3 文件。如果我使用任何文件管理器,我可以找到这些文件,但它们没有 mp3 标签。

例如。

这是随我的应用程序下载的文件。我用 FX 文件管理器打开它的属性。

它是用另一个程序(不是我的)下载的 mp3。如您所见,该文件具有 mp3 标签(显示在屏幕底部)

这是我下载文件的代码:

@Override
protected Void doInBackground(String... params) {               
    InputStream inputStream =  null;
    FileOutputStream fileOutput =  null;
    try {
        URL url = new URL(params[0]); 
        File file = new File(path);              
        URLConnection urlConnection = url.openConnection();

        inputStream = urlConnection.getInputStream();
        fileOutput = new FileOutputStream(file);

        int totalSize = urlConnection.getContentLength();
        int downloadedSize = 0;

        byte[] buffer = new byte[16384];
        int bufferLength = 0; 

        while ((bufferLength = inputStream.read(buffer)) > 0 ) {

            while(isPaused) {
                sleep();
            }

            if(isCancelled()) {                 
                if(file.exists())
                    file.delete();
                return null;
            }

            fileOutput.write(buffer, 0, bufferLength);
            downloadedSize += bufferLength;
            publishProgress(downloadedSize, totalSize);
        }

        if(totalSize > getFreeMemorySize()) {
        //if(true) {
            if(errorHandler != null)
                errorHandler.onMemorySizeException();
            cancel(true);
        }                       
    } catch (IOException e) {
        int i = e.hashCode();
        e.getStackTrace();
    }
    finally {
        try {

            if(inputStream != null)
                inputStream.close();
            if(fileOutput != null)
                fileOutput.close();    

        } catch (IOException e) {
            int i = e.hashCode();
            e.getStackTrace();
        }
    }
    return null;
} 

我哪里错了?为什么使用我的应用程序下载的 mp3 文件可以在 mp3 播放器中找到?我该如何解决?

【问题讨论】:

  • 你的文件路径是什么
  • 我不认为这会解决问题,但你应该刷新你的流。
  • 所有文件路径都显示在脚本中
  • 手机重启后UPD所有玩家都能找到我下载的文件

标签: java android download mp3


【解决方案1】:

您观察到的事实是 MediaStore 不会不断更新他的数据库。数据库只有在重启和挂载 sd 卡后才会更新。

如果您希望文件立即显示,您必须告诉 MediaStore 添加它们。

使用 MediaScannerConnection.scanFile 方法通知 MediaStore。 (MediaScannerConnection doucumentation) 请注意,您可以一次添加多个文件/路径。另外值得注意的是,此方法是异步的,文件是在单独的进程中添加的,这可能需要一些时间 - 操作完成时会通知您。

MediaScannerConnection.scanFile(
  context,
  new String[]{file.getAbsolutePath()},
  null,
  new OnScanCompletedListener() {
     @Override
     public void onScanCompleted(String path, Uri uri) {
         // only at this point are files in MediaStore
     }
  });

【讨论】:

    猜你喜欢
    • 2012-02-25
    • 1970-01-01
    • 2015-10-02
    • 2015-04-15
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-07
    相关资源
    最近更新 更多