微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Android 将音频/mp3 文件保存到外部存储

如何解决Android 将音频/mp3 文件保存到外部存储

我有关于保存音频/mp3 的问题 文件到外部存储 保存文件后,它显示在外部存储中 但是当我打开任何 android 音乐播放器时,文件没有显示在那里 我尝试将文件夹更改为“/storage/emulated/0/Music/”仍然没有显示 即使在下载文件夹中也没有。

该应用程序用于使用 API 从 YouTube 下载音乐

public class DownloadedActivity extends AppCompatActivity implements AdapterMusicDownloaded.ClickCallBack,View.OnClickListener {
private RecyclerView lvManager;
private AdapterMusicDownloaded adapterMusicSearch;
private ArrayList<ItemmusicDownloaded> arrayList = new ArrayList<>();
private LinearLayout llEmptyFile;
private static final String AUTHORITY = "com.free.music.downloader" + ".fileprovider";
public static final String PATH = Environment.getExternalStorageDirectory().toString() + "/FreeMusic/";
public static final String UPDATE_MUSIC = "update_music";
private ImageView imgBackSearch;
private InterstitialAd mInterstitialAd;
private AdView adView;
private ProgressBar loading;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_downloaded_songs);
    initViews();
}

private void initViews() {
    loading = findViewById(R.id.loading);
    adView = findViewById(R.id.adView);
    initAdsFull();
    MobileAds.initialize(this,getResources().getString(R.string.mobile_id));
    AdRequest adRequest = new AdRequest.Builder().build();
    adView.loadAd(adRequest);
    llEmptyFile = findViewById(R.id.ll_empty_file);
    imgBackSearch = findViewById(R.id.img_back_downloaded);
    imgBackSearch.setonClickListener(this);
    lvManager = findViewById(R.id.lv_main);
    linearlayoutmanager manager = new linearlayoutmanager(this);
    manager.setorientation(linearlayoutmanager.VERTICAL);
    adapterMusicSearch = new AdapterMusicDownloaded(arrayList,this);
    adapterMusicSearch.setCallBack(this);
    lvManager.setLayoutManager(manager);
    lvManager.setAdapter(adapterMusicSearch);
    LoadAsync loadAsync = new LoadAsync();
    loadAsync.execute();

}

@Override
public void clickItemmusic(int position) {
    Intent playIntent = new Intent(Intent.ACTION_VIEW);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        final File photoFile = new File(arrayList.get(position).getLink());
        Uri photoURI = FileProvider.getUriForFile(this,AUTHORITY,photoFile);
        playIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
        playIntent.setDataAndType(photoURI,"audio/*");
    } else {
        playIntent.setDataAndType(Uri.parse(arrayList.get(position).getLink()),"audio/*");
    }
    startActivity(playIntent);
}

@Override
public void clickOptionItemmusic(final int postion,View view) {
    PopupMenu popupMenu = new PopupMenu(this,view);
    popupMenu.inflate(R.menu.menu_option_main);
    popupMenu.show();
    popupMenu.setonMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.menu_delete:
                    File file = new File(arrayList.get(postion).getLink());
                    boolean deleted = file.delete();
                    if (deleted) {
                        Toast.makeText(DownloadedActivity.this,getResources().getString(R.string.delete_finish),Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(DownloadedActivity.this,getResources().getString(R.string.delete_error),Toast.LENGTH_SHORT).show();
                    }
                    arrayList.remove(postion);
                    adapterMusicSearch.notifyDataSetChanged();
                    break;
                case R.id.menu_share_main:
                    Intent shareIntent = new Intent(Intent.ACTION_SEND);
                    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    final File photoFile = new File(arrayList.get(postion).getLink());
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        Uri photoURI = FileProvider.getUriForFile(DownloadedActivity.this,photoFile);
                        shareIntent.putExtra(Intent.EXTRA_STREAM,photoURI);
                    } else {
                        shareIntent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(photoFile));
                    }

                    shareIntent.setType("audio/*");
                    startActivity(Intent.createChooser(shareIntent,"Share music"));
                    break;
                default:
                    break;
            }
            return false;
        }
    });
}

@Override
public void onClick(View v) {
    if (v.getId() == R.id.img_back_downloaded) {
        onBackpressed();
    }
}

@Override
public void onBackpressed() {

    if (mInterstitialAd.isLoaded()) {
        mInterstitialAd.show();
    } else {
        finish();
    }

}

private class LoadAsync extends AsyncTask<Void,Void,String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        llEmptyFile.setVisibility(View.GONE);
        loading.setVisibility(View.VISIBLE);
    }

    @SuppressLint("WrongThread")
    @Override
    protected String doInBackground(Void... voids) {
        arrayList.clear();
        File f = new File(PATH);

        File[] files = f.listFiles();
        if (f.exists()) {
            if (files.length <= 0) {
                Log.d("sizearrList","0");
                return "OK";
            } else {
                Log.d("sizearrList","2");
                arrayList.clear();

                Arrays.sort(files,new Comparator() {
                    public int compare(Object o1,Object o2) {
                        if (((File) o1).lastModified() > ((File) o2).lastModified()) {
                            return -1;
                        } else if (((File) o1).lastModified() < ((File) o2).lastModified()) {
                            return +1;
                        } else {
                            return 0;
                        }
                    }
                });

                for (File aFile : files) {
                    if (!aFile.isDirectory()) {
                        String name = aFile.getName();
                        String path = aFile.getPath();
                        getTimeVideo(aFile.getAbsolutePath());


                        Date lastModified = getFileLastModified(path);
                        arrayList.add(new ItemmusicDownloaded(name,path,lastModified,getTimeVideo(aFile.getAbsolutePath())))
                        ;

                    } else {
                        Log.d("myLog","Do not add");
                    }
                }
                Log.d("sizeArRSSs",arrayList.size() + "");
                for (int i = 0; i < arrayList.size(); i++) {
                    Log.d("sizeArr",arrayList.get(i).getTitle());
                }

            }
        }
        return null;
    }


    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if (arrayList.size() == 0) {
            llEmptyFile.setVisibility(View.VISIBLE);
        } else {
            llEmptyFile.setVisibility(View.GONE);
        }
        loading.setVisibility(View.GONE);
        adapterMusicSearch.notifyDataSetChanged();
    }
}

public static Date getFileLastModified(String pathFile) {
    File file = new File(pathFile);
    return new Date(file.lastModified());
}

private void initAdsFull() {
    mInterstitialAd = new InterstitialAd(this);
    MobileAds.initialize(this,getResources().getString(R.string.mobile_id));
    mInterstitialAd.setAdUnitId(getResources().getString(R.string.ads_full));
    mInterstitialAd.loadAd(new AdRequest.Builder().build());
    mInterstitialAd.setAdListener(new AdListener() {
        @Override
        public void onAdClosed() {
            finish();
        }
    });
}

public long getTimeVideo(String pathFile) {
    try {
        MediaPlayer mp = MediaPlayer.create(this,Uri.parse(pathFile));
        int duration = mp.getDuration();
        mp.release();
        return duration;
    } catch (Exception e) {
        return 0;
    }
}

}

public class DownloadVideoAsyn extends AsyncTask<String,Integer,String> {
private String title;
private int check;
private NotificationCompat.Builder builder;
private notificationmanager manager;
private String CHANNEL_ID = "download_video_tiktok_auto";
private String pathVideo = title + ".mp3";
private int id = 1232;
private Context mContext;
private NotificationChannel mChannel;
Notification noti;

public DownloadVideoAsyn(String title,int check,Context context) {
    this.title = title;
    this.check = check;
    this.mContext = context;
}

public static final String PATH = Environment.getExternalStorageDirectory().toString() + "/FreeMusic/";
private EventDownloadVideoCallBack callBack;

public void setCallBack(EventDownloadVideoCallBack callBack) {
    this.callBack = callBack;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    if (check == 2) {
        manager = (notificationmanager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        builder = new NotificationCompat.Builder(mContext,CHANNEL_ID);


        Intent iCancel = new Intent();
        id = id + 1;
        iCancel.putExtra("id",id);
        iCancel.putExtra("pathVideo",pathVideo);
        iCancel.setAction("CANCEL_ACTION");
        PendingIntent PICancel = PendingIntent.getbroadcast(mContext,iCancel,PendingIntent.FLAG_UPDATE_CURRENT);


        builder.setSmallIcon(R.drawable.ic_download)
                .setContentTitle(title.replace("&#39;","") + ".mp3")
                .setContentText(mContext.getString(R.string.download))
                .setChannelId(CHANNEL_ID)
                .setPriority(Notification.PRIORITY_MAX)

                .addAction(R.drawable.ic_cancel,"Cancel",PICancel)
                .setAutoCancel(true);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = notificationmanager.IMPORTANCE_HIGH;
            mChannel = new NotificationChannel(CHANNEL_ID,"channel-name",importance);
            mChannel.setSound(null,null);
            manager.createNotificationChannel(mChannel);
        }

    }
}

@Override

protected String doInBackground(String... strings) {
    String link = strings[0];
    try {
        URL url = new URL(link);
        // check folder exist
        File folder = new File(PATH);
        if (!folder.exists()) {
            folder.mkdir();
        }
        String path = PATH + title.replace("&#39;","") + ".mp3";
        File file = new File(path);
        long total = 0;
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        URLConnection connection = url.openConnection();
        InputStream inputStream = connection.getInputStream();
        int fileLength = connection.getContentLength();

        //=============================
        byte[] b = new byte[1024];
        int count = inputStream.read(b);

        while (count != -1) {
            total += count;
            fileOutputStream.write(b,count);
            count = inputStream.read(b);
            int progress = (int) (total * 100 / fileLength);
            publishProgress(progress);
            if (check == 2) {
                builder.setProgress(100,progress,false);
                builder.setContentText(mContext.getString(R.string.download) + " " + progress + "%");
                noti = builder.build();
                noti.flags = Notification.FLAG_ONLY_ALERT_ONCE;
                manager.notify(id,noti);
                if (progress == 100) {
                    manager.cancel(id);
                }
            }
        }
        inputStream.close();
        fileOutputStream.close();
    } catch (Exception e) {
        e.printstacktrace();
        try {
            URL url = new URL(link);
            // check folder exist
            File folder = new File(PATH);
            if (!folder.exists()) {
                folder.mkdir();
            }
            Date currentTime = Calendar.getInstance().getTime();
            title = currentTime.getTime() + "";
            String path = PATH + title + ".mp3";
            File file = new File(path);
            long total = 0;
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            URLConnection connection = url.openConnection();
            InputStream inputStream = connection.getInputStream();
            int fileLength = connection.getContentLength();

            //=============================
            byte[] b = new byte[1024];
            int count = inputStream.read(b);

            while (count != -1) {
                total += count;
                fileOutputStream.write(b,count);
                count = inputStream.read(b);
                int progress = (int) (total * 100 / fileLength);
                publishProgress(progress);
                if (check == 2) {
                    builder.setProgress(100,false);
                    builder.setContentText(mContext.getString(R.string.download) + " " + progress + "%");
                    noti = builder.build();
                    noti.flags = Notification.FLAG_ONLY_ALERT_ONCE;
                    manager.notify(id,noti);
                    if (progress == 100) {
                        manager.cancel(id);
                    }
                }
            }
            inputStream.close();
            fileOutputStream.close();
        } catch (Exception ex) {
            return null;
        }
    }
    return PATH + title + ".mp3";
}


@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    if (s != null) {
        Uri uri = Uri.parse("file://" + "/storage/emulated/0/FreeMusic/" + s);
        Intent scanFileIntent = new Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,uri);
        mContext.sendbroadcast(scanFileIntent);
        callBack.downloadVideoFinish(s);
    }

    else {
        callBack.downloadVideoFail("Error");
    }
}


@Override
protected void onProgressUpdate(Integer... values) {
    super.onProgressUpdate(values);
    if (check == 1) {
        if (callBack != null) {
            callBack.updateProgress(values[0]);
        }
    }
}

public interface EventDownloadVideoCallBack {
    void downloadVideoFinish(String s);

    void updateProgress(int pro);

    void downloadVideoFail(String fail);

}

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。