Xamarin Forms: Audio file path on iPhone?

TaylorWongTaylorWong USMember

I am able to play a file from the Sounds folder of my PCL by calling the string that was saved by "sound".

await Audio.Manager.PlayBackgroundMusic(sound);

I created a separate method, soundEffect(), to read in the text property of the button clicked and based on the text, the appropriate audio file name is returned as a string. I then saved the string returned from soundEffect() into "sound" and placed it as the parameter to the PlayBackgroundMusic() method. My code runs and works on the iPhone 7 simulator on my computer with the sound path defined in the main method of the testPage.xaml.cs file.

Audio.Manager.SoundPath = "/Users/TaylorWong/Projects/test/test/Sounds";

public partial class testPage : ContentPage
{
    int count = 0;      
    public testPage()
    {
        InitializeComponent();
        Audio.Manager.SoundPath = "/Users/TaylorWong/Projects/test/test/Sounds";       
    }

    async void Button_Clicked(object sender, System.EventArgs e)
    {
        count++;
        Button btn = (Button)sender;
        string str = btn.Text;
        string sound = soundEffect(str);

        if(count != 2){
              //greys out button to show it was pressed
            btn.TextColor = Color.FromRgb(160, 160, 160);
            btn.BackgroundColor = Color.FromRgb(160, 160, 160);
              // background music on a loop 
            await Audio.Manager.PlayBackgroundMusic(sound);
        }
        else{ 
            Audio.Manager.StopBackgroundMusic();
              //resets color of button
            btn.TextColor = Color.FromRgb(51, 153, 255);
            btn.BackgroundColor = Color.FromRgb(51, 153, 255);
              //Reset count to 0
            count = 0;  
        }
    }
}

My problem occurs when I attempt to play an audio file when I run the application on my actual iPhone 6. A System Exception is thrown:

"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.ClassThrowOnInitFailure to false."

I am not using AVFoundation, I am using a downloaded NuGet package called XamarinAudioManager. I believe it is due to the unclear path to where the files are stored in Sounds folder, but I am not sure how to get the full path so my phone can read it and access the audio files. I have tried Path.GetDirectoryName, Path.GetFullPath, and Environment.GetFolderPath. I have the Sounds folder with mp3 files in the pcl of my project and have a copy of the Sounds folder in the iOS section of my project as well. How can I get the correct path that will allow my iPhone to find the files stored in the PCL?

Sign In or Register to comment.