首页 > 解决方案 > 如何将音频文件保存到外部存储?

问题描述

我创建了一个保存音频的功能,但不知道如何使它工作。如果有人能帮助我会很好吗?

    private void saveAudio(int sound) {

    String root = Environment.getExternalStorageDirectory().toString();
    if (checkPermissionwrite()) { // check or ask permission
        File myDir = new File(root, "/KangleiPdDrums/Sounds");
        if (!myDir.exists()) {
            myDir.mkdirs();
        }
        String fname = "Sound1.mp3";
        File file = new File(myDir, fname);
        if (file.exists()) {
            file.delete();
        }
        try {
            file.createNewFile(); // if file already exists will do nothing
            FileOutputStream out = new FileOutputStream(file);
          
            out.write(sound);
            out.flush();
            out.close();
            file.setReadable(true, false);
            String pathed = file.getPath();
            Toast.makeText(getApplicationContext(), "Saved at " + pathed, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

标签: androidandroid-studio

解决方案


让我试着解释一下

String root = Environment.getExternalStorageDirectory().toString();

在根变量中,他正在获取私有外部存储的根引用。

if (checkPermissionwrite()) { }// check or ask permission

在这里,即使您的代码中没有此功能,但此功能将用于获取用户的写入权限

File myDir = new File(root, "/KangleiPdDrums/Sounds");
        if (!myDir.exists()) {
            myDir.mkdirs();
        }

在这里,他正在您的外部存储的根文件夹中创建一个目录或文件夹,然后他正在检查该目录是否已经存在,如果不存在则创建该目录。

String fname = "Sound1.mp3";
        File file = new File(myDir, fname);
        if (file.exists()) {
            file.delete();
        }

在这里,他将文件名存储在名称文件夹中并创建文件,然后检查该文件是否已存在,然后删除该文件。

 try {
            file.createNewFile(); // if file already exists will do nothing
            FileOutputStream out = new FileOutputStream(file);
          
            out.write(sound);
            out.flush();
            out.close();
            file.setReadable(true, false);
            String pathed = file.getPath();
            Toast.makeText(getApplicationContext(), "Saved at " + pathed, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

在这里,这段代码用于在他一开始创建的目录中写入文件/音频,我认为这很简单

让我为了解印地语或乌尔都语的印度和巴基斯坦用户提供一个链接,他们也可以通过视频了解它

https://youtu.be/SZPF9KuPIV8


推荐阅读