'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



Solution 1:[1]

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();

Solution 2:[2]

Stream myaudio = File.OpenRead("full path to the audio");

Var player = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;

player.Load(myaudio); // make sure this argument is a stream. A string will not play

Player.Play();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Tyler2P