Reputation: 2490
In a Xamarin.iOS Application AVAudioPlayer
is used to record and play some audio files.
The user records and saves some audio files very fast and when he tries to play one of them it throws a System.Exception in the line:
NSError error;
_player = new AVAudioPlayer(NSUrl.FromFilename(_audioPlaybackFilePath), "m4a", out error);
System.Exception: Could not initialize an instance of the type 'AVFoundation.AVAudioPlayer': the native 'initWithContentsOfURL:fileTypeHint:error:' method returned nil. It is possible to ignore this condition by setting MonoTouch.ObjCRuntime.Class.ThrowOnInitFailure to false.
The file in the given path exists.
Upvotes: 2
Views: 1564
Reputation:
In my case, it was because I forgot to specify the extension of the file. The right way to do it (ie: for mp3 files) is :
var soundResource = NSUrl.FromFilename("alert.mp3");
And not
var soundResource = NSUrl.FromFilename("alert");
Upvotes: 0
Reputation: 1141
We got this error using the package Plugin.AudioRecorder which uses AVAudioPlayer
. We could fix it by adding the following code to FinishedLaunching
:
AudioPlayer.OnPrepareAudioSession = audioSession =>
{
// maybe force audio to route to the speaker?
var success = audioSession.OverrideOutputAudioPort (AVAudioSessionPortOverride.Speaker, out NSError error);
};
Upvotes: 0
Reputation: 1
As @SushilHangover pointed out use AVAudioPlayer.FromData and feed it with a stream like:
theStream.Position = 0;
AVAudioPlayer.FromData(NSData.FromStream(theStream));
AND, this is very important, the stream has always be positioned to 0.
Upvotes: 0