android - 如何共享音频文件

标签 android audio share

我的应用程序的ListView包含多个音频文件。如果用户长按ListViewItem,它将共享所选的音频文件。
我已经读过,为了共享内容,首先我必须将文件复制到外部存储中,然后再共享。
我使用以下代码来做到这一点:

private void copyToExternalStorage(String sourceFilePath, String fileName)
{
    File sourceFile = new File(sourceFilePath);
    String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myApp";
    File destinationFile = new File(destinationPath);
    if (!destinationFile.exists())
        destinationFile.mkdirs();
    destinationFile = new File(destinationPath + "/" + fileName + ".mp3");
    try
    {
        FileUtils.copyFile(sourceFile, destinationFile);
    } catch (IOException e)
    {
        e.printStackTrace();
    }
}

private void share(String file, String trackName)
{
    copyToExternalStorage(file, trackName);
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("audio/*");
    String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myApp/" +
            trackName +
            ".mp3";
    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(path));
    startActivity(Intent.createChooser(shareIntent, "Share audio"));
}

@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l)
{
    share(getResources().getStringArray(R.array.sounds)[i], getResources().getStringArray(R.array.tracks)
                    [i]);
    return true;
}
R.array.sounds是我存储音频文件的位置,R.array.tracks是我存储音轨名称的位置。
我遇到的问题是我的应用程序在给定的sourceFilePath中找不到任何文件,因此它不会复制或共享任何内容。

任何帮助都感激不尽。

最佳答案

您不必在任何地方复制文件。让您的应用公开响应您共享的Uri的ContentProvider会更安全,更安全(但工作更多)。 Uri本质上成为文件/资源​​的定位器,其他应用程序可以使用它来读取它。

查看official docs on file sharing入门。

关于android - 如何共享音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35387000/

相关文章:

ios - 如何列出所有使用 Graph API 3.x 版本的 friend ?

android - 在 Android MVP 中将 BroadcastReceiver 放在哪里?

android - Android 19-22 的 ImageWriter 替代品?

ios - 如何在不在设备上下载 mp3 文件的情况下从 URL 流式传输音频

java - 从 java 轮询 NFS 共享会破坏文件系统

java - 为什么在 Android 10 操作系统中共享内容时不显示标记为 Intent LinkedIn 的共享托盘图标

java - SD卡写入失败?

android - 在Android上同时连接到MOBILE时如何检查Wi-Fi连接(SSID)

c 插孔音频连接套件 : how to properly play a song if my sound card sample rate differs from the song's?

audio - 用 J2ME 播放音频