0

我正在编写一个应用程序,让用户从资源中下载声音文件并将它们用作铃声(或更具体地说,通知声音)。

到目前为止,该应用程序在我指定的目录中成功创建了 mp3 文件,我可以使用手机上的文件资源管理器打开它,它会按预期播放,但在系统的声音设置中,它只会显示为一个数字,uri 的我会假设,并且不会播放声音。如果我尝试手动设置铃声,它不会显示在可用的声音文件中。

我的代码:

//this is just here temporarily, after this is working it will be moved to onCreate on the main activity.
if(!Settings.System.canWrite(holder.itemView.getContext())){
               Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse("package:" + context.getPackageName()));
               context.startActivity(intent);
}     

//tmpFile is the sound file that is successfuly created right before these lines of code

//this part is used to get the length in seconds of the soundfile - not sure if is important to add it to MediaStore
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
               mediaMetadataRetriever.setDataSource(tmpFile.getAbsolutePath());
               String durationStr = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
               assert durationStr != null;
               int seconds = parseInt(durationStr);
               seconds = seconds / 1000;

//adding contentvalues to the newly created file
ContentValues values = new ContentValues();
               values.put(MediaStore.MediaColumns.DATA, tmpFile.getAbsolutePath());
               values.put(MediaStore.MediaColumns.TITLE, fileTitle);
               values.put(MediaStore.MediaColumns.SIZE, tmpFile.length());
               values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg");
               values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);
               values.put(MediaStore.Audio.Media.DURATION, seconds);
               values.put(MediaStore.Audio.Media.IS_RINGTONE, false);     
               values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
               values.put(MediaStore.Audio.Media.IS_ALARM, false);
               values.put(MediaStore.Audio.Media.IS_MUSIC, false);

//adding the uri to MediaStore with the above extra values then passing it to RingtoneManager
Uri uri = MediaStore.Audio.Media.getContentUriForPath(tmpFile.getAbsolutePath());
               assert uri != null;
               context.getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + tmpFile.getAbsolutePath() + "\"", null);
               Uri newUri = context.getContentResolver().insert(uri, values);
               RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, newUri);

我错过了什么吗?

开发工具包 30

4

0 回答 0