Reputation: 297
I am using Xamarin Forms and using Dependency Service to set ringtone from mp3 places in asset folder. Here is my code:
AssetManager assets = Forms.Context.Assets;
fileName = "Artist.mp3";
System.IO.Stream inputStream;
System.IO.Stream outputStream;
try
{
inputStream = assets.Open("Sounds/" + fileName);
**_ outputStream = Forms.Context.OpenFileOutput(fileName, FileCreationMode.Private); _**
byte[] buffer = new byte[65536 * 2];
int read;
while ((read = inputStream.Read(buffer, 0, (int)inputStream.Length)) != -1)
{
outputStream.Write(buffer, 0, read);
}
inputStream.Close();
inputStream = null;
outputStream.Flush();
outputStream.Close();
outputStream = null;
Java.IO.File newSoundFile = new Java.IO.File(basepath + "/Sounds/" + fileName);
if (newSoundFile.Exists())
{
ContentValues values = new ContentValues();
values.Put(MediaStore.MediaColumns.Data, newSoundFile.AbsolutePath);
values.Put(MediaStore.MediaColumns.Title, "Test Ringtone");
values.Put(MediaStore.MediaColumns.MimeType, "audio/*");
values.Put(MediaStore.MediaColumns.Size, newSoundFile.Length());
values.Put(MediaStore.Audio.Media.InterfaceConsts.Artist, "Artist MP3");
values.Put(MediaStore.Audio.Media.InterfaceConsts.Duration, 2300);
values.Put(MediaStore.Audio.Media.InterfaceConsts.IsRingtone, true);
values.Put(MediaStore.Audio.Media.InterfaceConsts.IsNotification, false);
values.Put(MediaStore.Audio.Media.InterfaceConsts.IsAlarm, false);
values.Put(MediaStore.Audio.Media.InterfaceConsts.IsMusic, false);
Android.Net.Uri uri = MediaStore.Audio.Media.GetContentUriForPath(newSoundFile.AbsolutePath);
Forms.Context.ContentResolver.Delete(uri, MediaStore.MediaColumns.Data + "=\"" + newSoundFile.AbsolutePath + "\"", null);
Android.Net.Uri newUri = Forms.Context.ContentResolver.Insert(uri, values);
try
{
RingtoneManager.SetActualDefaultRingtoneUri(Forms.Context, RingtoneType.Ringtone, newUri);
}
catch (Exception e)
{
}
}
}
catch (Exception e)
{
}
I am getting below exception in the line outputStream = Forms.Context.OpenFileOutput(fileName, FileCreationMode.Private)
System.NotSupportedException: Specified method is not supported. at Android.Runtime.InputStreamInvoker.get_Length () [0x00000] in /Users/builder/data/lanes/3053/a94a03b5/source/monodroid/src/Mono.Android/src/Runtime/InputStreamInvoker.cs:55
Upvotes: 0
Views: 595
Reputation: 14750
You are implementing Stream.CopyTo
manually. Just use it.
using (var inputStream = assets.Open("Sounds/" + fileName))
using (var outputStream = Forms.Context.OpenFileOutput(fileName, FileCreationMode.Private))
{
inputStream.CopyTo(outputStream);
}
Upvotes: 0