11

我正在尝试制作一个用于共享音频文件的按钮。这是行不通的。首先,我尝试直接从我的原始文件夹发送文件,而不将其复制到手机卡上。那并没有解决我的问题。我尝试的第二件事是将文件保存到手机然后共享。将文件保存到手机的部分现在可以使用,但是当我尝试将音频文件共享到另一台设备时,所有兼容的应用程序都会崩溃(Whatsapp、Gmail 等)。

这是我的代码:

    String sharePath = Environment.getExternalStorageDirectory().getPath()
    + "/Soundboard/Ringtones/custom_ringtone.ogg";
    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("audio/*");
    share.putExtra(Intent.EXTRA_STREAM, sharePath);
    startActivity(Intent.createChooser(share, "Share Sound File"));

顺便说一句,音频文件是一个 .ogg 文件。我希望这些应用程序可以处理这种类型的文件。如果不是,我应该将其转换为 .mp3。

提前致谢!

4

9 回答 9

27

好的,发现我做错了什么。对于有同样问题的人,我是这样解决的:

我忘了将字符串解析为 uri。那是我必须添加的唯一代码行。Uri uri = Uri.parse(sharePath);

这是完整的其余部分:

    String sharePath = Environment.getExternalStorageDirectory().getPath()
            + "/Soundboard/Ringtones/custom_ringtone.ogg";
    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"));

另外不要忘记添加权限,WRITE_EXTERNAL_STORAGE否则在运行应用程序时会出错。

于 2013-09-08T18:40:48.300 回答
4

这是我的方式。

Uri uri = Uri.parse("file://" + sharePath);
于 2017-05-08T02:47:44.300 回答
1

通过 WhatsApp 发送音频文件:

我们必须记住,要共享的媒体文件WhatsApp必须存储在外部存储目录中,在这种情况下,您要发送存储在/raw文件夹中的文件,因此我们必须制作一个副本,然后打算通过该文件发送该文件WhatsApp:

这是一个假设有一个文件的例子/raw/jorgesys_sound.mp3

在此处输入图像描述

这是使用的方法

  private void sendWhatsAppAudio(){
        try {
           //Copy file to external ExternalStorage.
           String mediaPath = copyFiletoExternalStorage(R.raw.jorgesys_sound, "jorgesys_sound.mp3");

           Intent shareMedia = new Intent(Intent.ACTION_SEND);
            //set WhatsApp application.
            shareMedia.setPackage("com.whatsapp");
            shareMedia.setType("audio/*");
            //set path of media file in ExternalStorage.
            shareMedia.putExtra(Intent.EXTRA_STREAM, Uri.parse(mediaPath));
        startActivity(Intent.createChooser(shareMedia, "Compartiendo archivo."));
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "Whatsapp no se encuentra instalado", Toast.LENGTH_LONG).show();
        }
    }

    private String copyFiletoExternalStorage(int resourceId, String resourceName){
        String pathSDCard = Environment.getExternalStorageDirectory() + "/Android/data/" + resourceName;
        try{
        InputStream in = getResources().openRawResource(resourceId);
        FileOutputStream out = null;
        out = new FileOutputStream(pathSDCard);
        byte[] buff = new byte[1024];
        int read = 0;
        try {
            while ((read = in.read(buff)) > 0) {
                    out.write(buff, 0, read);
            }
        } finally {
            in.close();
            out.close();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return  pathSDCard;
  }

使用这种方法,您可以通过 WhatsApp 发送任何文件。

在此处输入图像描述

记得有权限:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
于 2017-09-15T16:12:17.370 回答
1

下面的代码对我有用

    SoundFiles soundFiles=.....
    String FullFilePath=soundFiles.getPath();
    Uri uri = Uri.fromFile(new File(FullFilePath));
    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("audio/*");
    share.putExtra(Intent.EXTRA_STREAM, uri);
    startActivity(Intent.createChooser(share, "Share Sound File"));
于 2019-06-08T10:59:58.117 回答
0

更改此行,它将支持 whatsapp 和其他应用程序:

share.setType("audio/mp3");

因为whatsapp不支持 ("audio/*");("*/*");

于 2016-08-02T05:35:01.073 回答
0
Intent intent = new Intent(); 
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new
File(Environment.getExternalStorageDirectory().getPath() + 
"/myMusic/Sound.mp3"))); 
intent.setType("audio/*");
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
startActivity(Intent.createChooser(intent, "Share Audio Abd Alazez..."));
于 2020-01-23T21:31:12.103 回答
0

试试这个代码。它对我有用:

    public class MainActivity extends AppCompatActivity {
    private File mAudioFile;

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

        //TODO Should handle Allow and Deny and include checkpermission
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                1);

        //Save Audio in Storage as File
        saveAudio();

        findViewById(R.id.btn_share_audio).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                shareAudioFile();

            }
        });

    }


    private void shareAudioFile() {

        String authorities = BuildConfig.APPLICATION_ID + ".fileprovider";
        Uri    path        = FileProvider.getUriForFile(this, authorities, mAudioFile);

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.putExtra(Intent.EXTRA_STREAM, path);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setType("audio/mp3");//Replace with audio/* to choose other extensions
        startActivity(Intent.createChooser(intent, "Share Audio"));

    }

    private void saveAudio() {

        String downloadPath = Objects.requireNonNull(getExternalFilesDir(Environment.DIRECTORY_MUSIC)).getAbsolutePath() + "/";

        InputStream inputStream = getResources().openRawResource(R.raw.music);
        mAudioFile = new File(downloadPath + "audio.mp3");
        copyInputStreamToFile(inputStream, mAudioFile);
    }

    /**
     * @param inputStream raw/music
     * @param file        Storage path
     */
    private void copyInputStreamToFile(InputStream inputStream, File file) {
        OutputStream out = null;

        try {
            out = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int    len;
            while ((len = inputStream.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Ensure that the InputStreams are closed even if there's an exception.
            try {
                if (out != null) {
                    out.close();
                }
                // If you want to close the "in" InputStream yourself then remove this
                // from here but ensure that you close it yourself eventually.
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
于 2021-08-18T03:06:15.820 回答
0

我认为我有一个非常常见和最简单的方法来共享所有类型的文件。

  • 这很简单。执行以下步骤。

    • 使用媒体扫描器类获取文件 URI 并使用它来共享文件。
    • 创建发件人意图。
    • 添加文件的 mime 类型并添加文件 URI 以共享数据。
    • 最后创建一个意图选择器来选择应用程序并使用该意图启动一个活动
  • 我在下面有一个例子可以更好地理解。

    public void shareFile(String filePath) {
      if (filePath != null && !filePath.isEmpty()) {
          MediaScannerConnection.scanFile(activity, new String[]{filePath}, null,
                  (path, uri) -> {
                      Log.i(TAG, "onScanCompleted: path :- " + path + " uri :- " + uri);
                      if (uri != null) {
                          try {
                              Intent shareIntent = new Intent(Intent.ACTION_SEND); // create action send
                              shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                              shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    
                              // create mime type of file from file uri
                              String mimeType;
                              if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
                                  ContentResolver cr = activity.getContentResolver();
                                  mimeType = cr.getType(uri);
                              } else {
                                  String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
                                          .toString());
                                  mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                                          fileExtension.toLowerCase());
                              }
    
                              // shareIntent.setPackage(""); // you can specify app package name here to share file that app only
                              shareIntent.setDataAndType(uri, mimeType);
                              shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
                              startActivity(Intent.createChooser(shareIntent, "Share File"));
                          } catch (Throwable throwable) {
                              Log.i(TAG, "shareSong: error :- " + throwable.getMessage());
                          }
                      }
                  });
      } else {
          Log.i(TAG, "shareSong: currentMusic NULL");
      }
    }
    
  • 您仅将文件路径传递给此方法,它将处理所有其他事情。

  • 注意:-在调用此方法之前,您拥有READ_EXTERNAL_STORAGE权限。

我希望它对我们所有的社区都有用。

于 2021-10-06T16:09:44.170 回答
-2

我正在使用:

final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("audio/mp3");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory().toString() + "/breakfast.mp3"));
startActivity(Intent.createChooser(shareIntent, "Condividi attraverso:"));

但是gmail说“无法附加空文件”

于 2017-06-29T12:08:24.227 回答