I'm writing an app which plays an mp3 file.
In Android this is straight forward:
- Use
Xamarin.Essentials.FilePicker
to pick the mp3 filepath - Use Android.Media.MediaPlayer to play the mp3 filepath
I tried a similar approach for iOS:
- Use
Xamarin.Essentials.FilePicker
to pick the mp3 filepath (either from icloud or on phone) - Use AVAudioEngine to play the mp3 filepath
This works in the simulator but throws an exception when trying to create an AVAudioFile. (LibVlcSharp also fails when trying to load the filepath).
NSError err;
AVAudioFile file = new AVAudioFile(new NSUrl(audioUri, false), out err);
//err is null after this call throws an exception
Exception: "Could not initialize an instance of the type 'AVFoundation.AVAudioFile': the native 'initForReading:error:' method returned nil.\nIt is possible to ignore this condition by setting ObjCRuntime.Class.ThrowOnInitFailure to false."
(Setting ThrowOnInitFailure = false
doesn't help as file is still null).
I suspect it's a permissions issue, so I tried using the MPMediaPickerController:
MPMediaPickerController mp = new MPMediaPickerController();
mp.AllowsPickingMultipleItems = false;
mp.ShowsCloudItems = true;
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mp, true, null);
with MPMediaLibraryAuthorizationStatus
set to Authorized
and the following set in info.plist:
<key>NSAppleMusicUsageDescription</key>
<string>Select a music file</string>
This code does nothing whatsoever.
How can I get this or the file picker method to work?
UPDATE
I've managed to get the MediaPicker working. Will update on that soon.
My next problem is I get an NSUrl
from the MediaPicker. If I pass this directly into the AVAudioEngine
, it plays fine.
But if I save the NSUrl
to a string for serialization purposes, and then try to recreate it with the following code, the same exception above occurs when trying to create AVAudioFile
.
//url1 works fine
NSUrl url1 = mediaItemCollection.Items[0].AssetURL;
AVAudioFile file = new AVAudioFile(url1, out err);
//url2 throws the same exception above
string str = mediaItemCollection.Items[0].AssetURL.AbsoluteString;
NSUrl url2 = new NSUrl(str, false)
AVAudioFile file = new AVAudioFile(url2, out err);
Any ideas?