Can't play mp3 file from internal storage into media player

297 views Asked by At

I am downloading mp3 file from this url using DownloadManager. Here is my code.

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

I have tried to play the downloaded file in media player using this code. But unfortunately targetFile.exists() returns false although file exists in that path. Here is the code -

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

File exists in my device.

screenshot

0

There are 0 answers