//检查是否拥有录音和存储权限 private boolean checkPermission() { int result = ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE); int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.RECORD_AUDIO); return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED; }
//如果没有权限,则申请权限 private void requestPermission() { ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.RECORD_AUDIO}, RequestPermissionCode); }
//录制音频 MediaRecorder recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); recorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB); recorder.setOutputFile(audioFileName);
try { recorder.prepare(); recorder.start(); } catch (IOException e) { e.printStackTrace(); }
//共享音频到Facebook Messenger shareToFacebookMessenger(Uri.fromFile(new File(audioFileName)));
//共享音频到WhatsApp shareToWhatsApp(Uri.fromFile(new File(audioFileName)));
//分享功能 public void shareToFacebookMessenger(Uri uri) { Intent share = new Intent(Intent.ACTION_SEND); share.setType("audio/*"); share.putExtra(Intent.EXTRA_STREAM, uri); share.setPackage("com.facebook.orca"); startActivity(Intent.createChooser(share, "Share audio file")); }
public void shareToWhatsApp(Uri uri) { Intent share = new Intent(Intent.ACTION_SEND); share.setType("audio/*"); share.putExtra(Intent.EXTRA_STREAM, uri); share.setPackage("com.whatsapp"); startActivity(Intent.createChooser(share, "Share audio file")); }