not able to set a mp3 file as ringtone in android programatically

Viewed 12

I am trying to set a ringtone for a mp3 file. I am getting this file after trimming a song.

The code I am using is as follows

Code: for setting the ringtone

private fun setRingtone(path: String){
        try {
            Log.d("setRingtone", "started")
            val file = File(path)
            val values = ContentValues()
            values.put(MediaStore.MediaColumns.DATA, file.absolutePath)
            values.put(MediaStore.MediaColumns.TITLE, "my ringtone $filePrefix")
            values.put(MediaStore.MediaColumns.MIME_TYPE, getMIMEType(file.path))
            values.put(MediaStore.MediaColumns.SIZE, file.length())
            values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name)
            values.put(MediaStore.Audio.Media.IS_RINGTONE, true)
            values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true)
            values.put(MediaStore.Audio.Media.IS_ALARM, true)
            values.put(MediaStore.Audio.Media.IS_MUSIC, false)

            val uri = MediaStore.Audio.Media.getContentUriForPath(file.absolutePath)
            val newUri = this.contentResolver.insert(uri!!, values)

            RingtoneManager.setActualDefaultRingtoneUri(
                applicationContext,
                RingtoneManager.TYPE_RINGTONE,
                newUri
            )

            Toast.makeText(applicationContext, "Ringtone set successfully", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

where,

fun getMIMEType(url: String?): String? {
        var mType: String? = null
        val mExtension = MimeTypeMap.getFileExtensionFromUrl(url)
        if (mExtension != null) {
            mType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(mExtension)
        }
        return mType
    }

When I am using this, a ringtone gets set in mobile settings but the problem is that the sound of that ringtone is just a 'Ding' sound but not the audio which I want.

And the audio which I get after trimming is working fine(its correct) it has the audio that I want and I can even play that audio.

Thank You in advance

0 Answers
Related