在WhatsApp上分享歌曲,总是以"failed to send"消息结尾



我正在从网络服务获取输入流并将其转换为字节数组,以便我可以创建一个临时文件并使用 MediaPlayer 播放它(这是一个.mp3)。问题是我想在whatsapp上分享这首歌,但是每当我尝试时都会收到"无法发送"的消息。

这就是我获取和播放歌曲的方式:

if (response.body() != null) {
   byte[] bytes = new byte[0];
   try {
      bytes = toByteArray(response.body().byteStream());
   } catch (IOException e) {
      e.printStackTrace();
   }
mediaPlayer.reset();
try {
     File tempMp3 = File.createTempFile("tempfile", "mp3", getContext().getCacheDir());
     tempMp3.deleteOnExit();
     FileOutputStream fos = new FileOutputStream(tempMp3);
     fos.write(mp3);
     fos.close();
     FileInputStream fis = new FileInputStream(tempMp3);
     mediaPlayer.setDataSource(fis.getFD());
     mediaPlayer.prepare();
}
catch (IOException ex) {
     String s = ex.toString();
     ex.printStackTrace();
}
mediaPlayer.start();

这和一些类似的方式是我试图分享它的方式:

String sharePath = Environment.getExternalStorageDirectory().getPath()
                    + "/tempfile.mp3";
            Uri uri = Uri.parse(sharePath);
            Intent share = new Intent(Intent.ACTION_SEND);
            share.setType("audio/*");
            share.putExtra(Intent.EXTRA_STREAM, uri);
            startActivity(Intent.createChooser(share, "Share Sound File"));
这首歌

播放得很好,我已经包含了在外部存储中读取和写入的权限,但我需要帮助来分享这首歌,无论是字节还是文件或任何有效的内容,请。

您需要

File tempMp3 = File.createTempFile("tempfile", "mp3", getContext().getCacheDir());

File tempMp3 = new File(Environment.getExternalStorageDirectory() + "/"+ getString(R.string.temp_file) + getString(R.string.dot_mp3)); //<- this is "tempfile" and ".mp3"

然后你可以像这样分享它

String sharePath = tempMp3.getAbsolutePath();
        Uri uri = Uri.parse(sharePath);
        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("audio/*");
        share.putExtra(Intent.EXTRA_STREAM, uri);
        startActivity(Intent.createChooser(share, getString(R.string.share_song_file)));

主要问题是您存储文件的位置无法与其他应用程序共享,只能从您自己的应用程序访问,因为 getCacheDir() 方法用于创建缓存文件而不是将数据持久存储在文件中,并且对应用程序来说是私有的(并且 createTempFile() 在文件名末尾生成随机数, 因此,您将无法像这样硬编码正确的路径)。
此外,此解决方案还利用了您包含的权限(访问外部存储)。

最新更新