无法将内部存储中的mp3文件播放到媒体播放器中

时间:2018-10-09 12:34:01

标签: android file android-mediaplayer android-download-manager android-internal-storage

我正在使用DownloadManager从此url下载mp3文件。这是我的代码。

// Downloading file from internet and save to internal storage.
    private void downloadFromOnline() {
        downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        DownloadManager.Request request = null;
        request = new DownloadManager.Request(Uri.parse("https://alquran.technobdapis.com/quranallaudio/arabic_with_bangla/arbn_001.mp3"));
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        request.setAllowedOverRoaming(false);
        request.setTitle("Downloading...");
        request.setDescription("Downloading...arbn_001.mp3");
        request.setVisibleInDownloadsUi(true);

        File SDCardpath = getFilesDir();
        File myDataPath = new File(SDCardpath.getAbsolutePath());

        // Internal storage file path to save the downloaded file
        // /data/data/com.technobd.internalstoragetest/files/arabic_with_bangla/arbn_001.mp3
        if (!myDataPath.exists())
            myDataPath.mkdir();

        request.setDestinationInExternalFilesDir(getApplicationContext(), myDataPath.getPath() + "/arabic_with_bangla", "arbn_001.mp3");
        long refid = downloadManager.enqueue(request);
        id = refid;
    }

我尝试使用此代码在媒体播放器中播放下载的文件。但是遗憾的是,尽管该路径中存在文件,但targetFile.exists()返回false。这是代码-

public BroadcastReceiver onComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            File SDCardpath = getFilesDir();
            File myDataPath = new File(SDCardpath.getAbsolutePath());
            File targetFile = new File(myDataPath.getPath() + "/arabic_with_bangla/" +"arbn_001.mp3");
            Log.d("FileExists", targetFile.exists() + " ");
            // Downloaded file path
            // /data/data/com.technobd.internalstoragetest/files/arabic_with_bangla/arbn_001.mp3

            // Although target file exists in device It's targetFile.exists() returning false
            // TODO: This is the main problem.
            if(targetFile.exists()){
                MediaPlayer mp = new MediaPlayer();
                try {
                    mp.setDataSource(MainActivity.this, Uri.parse(targetFile.getParent()));
                    mp.prepare();
                    mp.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else{
                // File Not Exists
                Log.d("FileExists", targetFile.exists() + " ");
            }
        }
    };

文件存在于我的设备中。

screenshot

0 个答案:

没有答案