Add sound to Android system sound
I'm trying to add some mp3 files from assets folder to android system sounds notification.
My problems are:
-
To add sound from assets to system sound I needed to storage permission with following code:
fun addSounds() { val file = File(requireContext().filesDir, "notifications") if (!file.exists()) file.mkdirs() val soundFile = File(file.absolutePath + "/" + "longbeep.mp3") requireContext().assets.open("long_beep.mp3").use { input -> soundFile.outputStream().use { output -> input.copyTo(output, 1024) } } registerFile(soundFile, "ShahramLong2") } private fun registerFile(file: File, fileName: String) { val values = ContentValues() values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath()); values.put(MediaStore.MediaColumns.TITLE, fileName); values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg"); values.put(MediaStore.MediaColumns.SIZE, file.length()); 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); val generalaudiouri = Media.EXTERNAL_CONTENT_URI val uri = Media.getContentUriForPath(file.absolutePath) requireContext().contentResolver.delete( Media.EXTERNAL_CONTENT_URI, MediaStore.MediaColumns.DATA + "='" + file.getAbsolutePath() + "'", null ) requireContext().contentResolver.insert(Media.EXTERNAL_CONTENT_URI, values) }
-
When changed
registerFile
to following code app crashed with exceptionCaused by: java.lang.UnsupportedOperationException: Writing to internal storage is not supported. at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:174) at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:142)
Code is:
private fun registerFile(file: File, fileName: String) { val values = ContentValues() values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath()); values.put(MediaStore.MediaColumns.TITLE, fileName); values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg"); values.put(MediaStore.MediaColumns.SIZE, file.length()); 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); val generalaudiouri = Media.EXTERNAL_CONTENT_URI val uri = Media.getContentUriForPath(file.absolutePath) // use uri instead of Media.EXTERNAL_CONTENT_URI requireContext().contentResolver.delete( uri!!, MediaStore.MediaColumns.DATA + "='" + file.getAbsolutePath() + "'", null ) requireContext().contentResolver.insert(uri!!, values) }
-
Another problem is apparently this line does not work:
requireContext().contentResolver.delete( Media.EXTERNAL_CONTENT_URI, MediaStore.MediaColumns.DATA + "='" + file.getAbsolutePath() + "'", null )
The sound is added several times.
Comments
Post a Comment