我从一个webservice获得一个输入流,并将其转换为字节数组,这样我就可以创建一个临时文件并使用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"));这首歌播放得很好,我已经包括了在外部存储器中读写的权限,但是我需要帮助来分享这首歌,不管是字节还是文件,还是其他任何有用的东西。
发布于 2017-11-07 01:06:24
您需要从
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()在文件名的末尾生成随机数,这样您就无法对正确的路径进行硬编码)。
此外,此解决方案还使用您所包含的权限(访问外部存储)。
https://stackoverflow.com/questions/47117191
复制相似问题