Devi Prasad
Devi Prasad

Reputation: 839

AVAudioplayer initialize component throws a null exception

string mediafile;
mediafile=Constants.AudioLink;
NSUrl url1=new NSUrl(mediafile);
var audioplayer=AVAudioPlayer.FromUrl(url1);

URL is getting link correctly but audio player getting value null. It throws an exception below:

Could not initialize an instance of the type 'AVFoundation.AVAudioPlayer': the native 'initWithContentsOfURL:error:' method returned nil.

It is possible to ignore this condition by setting : MonoTouch.ObjCRuntime.Class.ThrowOnInitFailure to false

What can i do, Please give me the solution.

Upvotes: 1

Views: 1763

Answers (1)

SushiHangover
SushiHangover

Reputation: 74184

These is a really quick example of loading/playing an .mp3 file that has a build type of BundledResource (I dropped into the Resources folder of the project) and thus is placed in the app's root directory).

I do a quick check via AudioToolbox.AudioSource.Open to make sure the file exists, can be read, and is a valid media file type so I know that AVAudioPlayer will not throw a fatal error trying to load it.

AVAudioPlayer player; // Class level object ref
partial void playButtonTouch (UIButton sender)
{
    if (player != null && player.Playing)
        player.Stop ();
    else {
        var mp3File = "WildTurkeysEN-US.mp3";
        var mp3URL = new NSUrl (mp3File);
        Console.WriteLine (mp3URL.AbsoluteUrl);
        var mp3 = AudioToolbox.AudioSource.Open (mp3URL, AudioFilePermission.Read, AudioFileType.MP3);
        if (mp3 != null) { 
            Console.WriteLine (mp3.EstimatedDuration);
            player = AVAudioPlayer.FromUrl (mp3URL);
            player.Play ();
        } else {
            Console.WriteLine ( "File could not be loaded: {0}", mp3URL.FilePathUrl );
        }
    }
}

Upvotes: 4

Related Questions