I want to add custom sound file to ringtone library (MediaStore) of my device, so that if users wishes to changes sound of notification created by my App, he should simple go to notification settings and pick my app specific ringtone (myApp_Ring_1, myApp_Ring_2 etc..) from ringtone manager. Currently my sound file is getting copied to Music folder that than being added to Mediastore (Ringtone Manager). Kindly help. Below is my code.
public void AddAlertSound(Context c )
{
InsertCustomSoundInMediaStore("AlertSound/myApp_Ring_1.mp3", "myApp_Ring_1", c);
}
public Android.Net.Uri InsertCustomSoundInMediaStore(string filePath, string name, Context c)
{
ContentValues values = new ContentValues();
ContentResolver contentResolver = c.ContentResolver;
var appName = "myApp";
values.Put(MediaStore.MediaColumns.DisplayName, name + ".mp3");
values.Put(MediaStore.MediaColumns.Title, name);
values.Put(MediaStore.MediaColumns.MimeType, "audio/mp3");
values.Put(MediaStore.MediaColumns.Size, GetDuration(filePath));
values.Put(MediaStore.Audio.Media.InterfaceConsts.Artist, appName);
values.Put(MediaStore.Audio.Media.InterfaceConsts.IsRingtone, true);
values.Put(MediaStore.Audio.Media.InterfaceConsts.IsNotification, true);
values.Put(MediaStore.Audio.Media.InterfaceConsts.IsAlarm, true);
values.Put(MediaStore.Audio.Media.InterfaceConsts.IsMusic, false);
Android.Net.Uri newUri = contentResolver.Insert(MediaStore.Audio.Media.ExternalContentUri, values);
try
{
AssetManager assets = c.Assets;
AssetFileDescriptor descriptor = Android.App.Application.Context.Assets.OpenFd(filePath);
using (System.IO.Stream inputStream = descriptor.CreateInputStream())
{
using (System.IO.Stream outputStream = contentResolver.OpenOutputStream(newUri))
{
byte[] buffer = new byte[inputStream.Length];
int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
outputStream.Write(buffer, 0, bytesRead);
outputStream.Flush();
}
}
}
}
catch (Exception ex)
{
Toast.MakeText(c, ex + "", ToastLength.Long).Show();
System.Console.WriteLine(ex.Message);
}
return newUri;
}
public double GetDuration(string fileName)
{
MediaPlayer mediaPlayer = new MediaPlayer();
AssetFileDescriptor descriptor = Android.App.Application.Context.Assets.OpenFd(fileName);
mediaPlayer.SetDataSource(descriptor.FileDescriptor, descriptor.StartOffset, descriptor.Length);
mediaPlayer.Prepare();
return mediaPlayer.Duration;
}