In my Android application, I want to set the audio file from the raw folder as a ringtone. For this, I wrote the code below, but it does not work.
Please help me solve this problem. Thanks.
The code:
String name =best_song_ever.mp3; File newSoundFile = new File("/sdcard/media/ringtone", "myringtone.mp3"); Uri mUri = Uri.parse("android.resource://" + context.getPackageName() + "/raw/" + name); ContentResolver mCr = context.getContentResolver(); AssetFileDescriptor soundFile; try { soundFile = mCr.openAssetFileDescriptor(mUri, "r"); } catch (FileNotFoundException e) { soundFile = null; } try { byte[] readData = new byte[1024]; FileInputStream fis = soundFile.createInputStream(); FileOutputStream fos = new FileOutputStream(newSoundFile); int i = fis.read(readData); while (i != -1) { fos.write(readData, 0, i); i = fis.read(readData); } fos.close(); } catch (IOException io) { } ContentValues values = new ContentValues(); values.put(MediaStore.MediaColumns.DATA, newSoundFile.getAbsolutePath()); values.put(MediaStore.MediaColumns.TITLE, "my ringtone"); values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/oog"); values.put(MediaStore.MediaColumns.SIZE, newSoundFile.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); Uri uri = MediaStore.Audio.Media .getContentUriForPath(newSoundFile.getAbsolutePath()); Uri newUri = mCr.insert(uri, values); try { RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri); } catch (Throwable t) { } Toast.makeText(context, name + " is set as ringtone.", Toast.LENGTH_LONG).show(); }
source share