Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin forms play sound with CrossSimpleAudioPlayer

I wanna to play a sound that I've made download using CrossSimpleAudioPlayer plugin.

I instantiate and initialise the plugin and everything works fine on the IOS, but on android it gives me this error when I load the file "Java.IO.FileNotFoundException" but the file exists and has permission to read

And on the console appears this "[MediaPlayer] error (1, -2147483648)".

I load the clip this way

ISimpleAudioPlayer player = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;
player.Load("/data/user/0/com.my.app/files/20.wav");

When I load with a Stream instead, throws me that error "Java.IO.IOException: Prepare failed.: status=0x1"

var temp = new MemoryStream(DependencyService.Get<IFileHelper>().GetFileAsByte(path));
//This works fine and loads the file
player.Load(temp); //throws the error

If I load a link instead a local file this works fine, but I need a local file.

I don't know why this is happening on Android

like image 222
micael cunha Avatar asked Mar 07 '19 10:03

micael cunha


1 Answers

You're reading your sound file from Internal Storage (the files directory). The Files directory is a private directory that is only accessible by your application. Neither the user or the OS can access this file.

This has a path like this:

/data/user/0/com.my.app/files/20.wav

You'll have to read the file from either Public External Storage or Private External Storage. It depends on whether or not you want your sound file accessible by the MediaStore content provider.

Here the sound file can be readed from the Public External Storage which has a path like this:

/storage/emulated/0/.../

And permission need to be added to manifest:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

But its not sufficient. Permission has to be asked right before the external storage is accessed like this(using NuGet plugin Current Activity for Android project here to get the current activity):

var currentActivity = CrossCurrentActivity.Current.Activity;
            int requestCode=1;

            ActivityCompat.RequestPermissions(currentActivity, new string[] {
                Manifest.Permission.ReadExternalStorage,
                Manifest.Permission.WriteExternalStorage
            }, requestCode);

if permission is granted then proceed and copy file to external storage:

var recordingFileExternalPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.Path, AppConstants.CUSTOM_ALERT_FILENAME);

            if (ContextCompat.CheckSelfPermission(Android.App.Application.Context, Manifest.Permission.WriteExternalStorage) == (int)Permission.Granted)
            {
                try
                {
                    if (File.Exists(recordingFileExternalPath))
                    {
                        File.Delete(recordingFileExternalPath);
                    }

                    File.Copy(filePath, recordingFileExternalPath);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            else
            {
                UserDialogs.Instance.Alert("Permission to write to External Storage not approved, cannot save settings.", "Permission Denied", "Ok");
            }

If not working in CrossSimpleAudioPlayer ,you can use DependencyService with MediaPlayer to play Audio.Best using stream to play as follow:

File tempFile = new File(path);           
FileInputStream fis = new FileInputStream(tempFile);             
mediaPlayer.reset();             
mediaPlayer.setDataSource(fis.getFD());             
mediaPlayer.prepare();             
mediaPlayer.start();
like image 160
Junior Jiang Avatar answered Nov 05 '22 16:11

Junior Jiang