9

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

micael cunha
  • 503
  • 5
  • 24
  • Where is your file? in Emulator, real device, or in VS project. – R15 Mar 07 '19 at 10:38
  • if the audio file is loaded from local resource folder of Android, ensure the audio file is set into Bundle Resource by its property selection – Prasanth Mar 07 '19 at 10:46
  • @CGPA6.4 the file is in a real device, and that is the correct path – micael cunha Mar 07 '19 at 11:00
  • 1
    Maybe **CrossSimpleAudioPlayer** is not so powerful, can not get path like this in Android. Have a try with native android method `MediaPlayer` to do. **DependencyService** may be useful .https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/dependency-service/introduction – Junior Jiang Mar 08 '19 at 08:46
  • @JuniorJiang-MSFT that doesn't work either. The same error appears – micael cunha Mar 13 '19 at 11:26
  • @micaelcunha Do you add this permission.`` – Junior Jiang Mar 14 '19 at 00:59

2 Answers2

2

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();
Junior Jiang
  • 12,430
  • 1
  • 10
  • 30
  • That doesn't work. I've copied the file from my internal Storage to Public Storage (I checked the file and is copied successfully) and when I do prepare from MediaPlayer it throws me that exception "Java.IO.IOException: Prepare failed.: status=0x1" I already have that permissions added – micael cunha Mar 14 '19 at 16:10
  • @micaelcunha Permission has to be asked right before the external storage is accessed.I will updtae answer. – Junior Jiang Mar 15 '19 at 01:28
  • your answer is really good and complete. But my problem isn't on permissions, I already asked for permissions in real time before writing the file. But I tested your code anyway and the result is the same, using MediaPlayer in native android throws me "Java.IO.IOException: Prepare failed.: status=0x1", using the new file that was write in external memory. – micael cunha Mar 15 '19 at 17:44
  • @micaelcunha Having a try with using stream to play.From error log ,refer to this.https://stackoverflow.com/questions/3761305/android-mediaplayer-throwing-prepare-failed-status-0x1-on-2-1-works-on-2-2.And I will update answer. – Junior Jiang Mar 18 '19 at 01:37
  • like I've already said, I already have tested all of code in that page, and nothing works. I tested again the new code you suggested and the result it's the same, same error. – micael cunha Mar 18 '19 at 17:51
  • @micaelcunha Okey ,it's strange. Maybe we miss something or this code can work in other devices.Thanks for voting up my answer. – Junior Jiang Mar 21 '19 at 08:20
0
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();
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • 1
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P May 21 '22 at 10:25