在我的应用程序中,我使用MediaRecorder记录并保存文件。然后,当发送通知时,我想播放录制的音频文件。当我仅将声音设置为文件位置URI时,应用程序崩溃。
这是录音机,当我用MediaPlayer播放时,它的工作原理和声音听起来很棒(此代码适用于显示文件的保存位置):
//the filename is unique every time I record, but for purposes online
//it has been simplified.
_audioFilename = f.getAbsolutePath() + "/voice.3gp";
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mRecorder.setAudioEncodingBitRate(133333);
mRecorder.setAudioSamplingRate(44100);
mRecorder.setOutputFile(_audioFilename);
mRecorder.setMaxDuration(10000);
然后在调用通知时:
//Here I get the filename and prefix it with file://
//I have also tried prefixing it with content://
Uri audioUri = Uri.parse("file://" + task.getAudio());
//Create the notification channel for newer build SDKs.
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
/* create a MyNotification channel */
AudioAttributes audioAtts = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
String channelId = "myNotification";
CharSequence channelName = "Some Channel";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.BLUE);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notificationChannel.setSound(audioUri, audioAtts);
notifManager.createNotificationChannel(notificationChannel);
}
//here I build the notification and add the sound in case the SDK is older.
nb = new NotificationCompat.Builder(c, "myNotification")
.setLargeIcon(BitmapFactory.decodeResource(c.getResources(),
R.mipmap.ic_launcher))
.setSmallIcon(R.mipmap.proxi_icon_round)
.setContentTitle("ProxiAlert: You are near "+task.getTask()+ " at " + task.getAddress())
.setContentText("Task Description: "+task.getDescription())
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("Task Description: "+task.getDescription()))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
//program crashes here with the FileUriExposedException
.setSound(audioUri);
对此有什么解决方案?我是否需要将通知声音另存为铃声?为了通知可以访问该文件,必须将文件存储在其他位置吗?还是有其他解决方法(除了使用MediaPlayer之外)?