Search code examples
mp3media-playerwindows-phone-8filenotfoundexception

Windows phone 8 on emulator - why can't I play audio files?


I'm converting an app that was written in Silverlight, and so far I've succeeded in solving all of the problems, except for one:

For some reason, the emulator refuses to play any audio files of the app, and it doesn't even throw an exception. I've checked, and in the ringtone category it can make sounds.

The original code was :

<Grid x:Name="sharedFullScreenFilePathContainer"
Tag="{Binding StringFormat=\{0\},Converter={StaticResource fullScreenImageConverter}}">

    <Image x:Name="fullScreenImage" Stretch="Fill"
Source="{Binding ElementName=sharedFullScreenFilePathContainer,Path=Tag, StringFormat=../Assets/images/\{0\}.jpg}"
ImageFailed="onFullScreenImageFailedToLoad" MouseLeftButtonDown="onPressedOnFullScreenImage" />

    <MediaElement x:Name="mediaPlayer" AutoPlay="True"
Source="{Binding ElementName=sharedFullScreenFilePathContainer,Path=Tag, StringFormat=../Assets/sounds/\{0\}.wma}" />
</Grid>

so, the image that I set to this item's context is really shown, but the sound that really exists on the path I set to it doesn't play (I've checked in the "Bin" folder).

I've tried to use code instead of xaml, but I still have the same problem.

I've tried this (though it's usually used for background music):

AudioTrack audioTrack = new AudioTrack(new Uri("../Assets/sounds/" + fileToOpen, UriKind.Relative), "", "", "", null);
BackgroundAudioPlayer player = BackgroundAudioPlayer.Instance;
player.Track = audioTrack;
player.Play();

It didn't play anything, and also didn't throw any exception.

I've also tried the next code, but it throws an exception (file not found exception) probably because I don't call it right:

Stream stream = TitleContainer.OpenStream("@Assets/sounds/" + fileToOpen);
SoundEffect effect = SoundEffect.FromStream(stream);
FrameworkDispatcher.Update();
effect.Play();

I've also tried using wma files but it also didn't work.

I also tried to play with the "copy to output directory" parameter of the mp3 files (to "always" and "only if new" ) and with the "build action" parameter (to "none" and "content" ). Nothing helps.

Can anyone please help me? I didn't develop for Silverlight/WP for a very long time and I can't find out how to fix it .

Btw, since later I need to know when the sound has finished playing (and also to be able to stop it), I would like to use code anyway. I would be happy if you could also tell me how to do it too (I can ask it on a new post if needed).


EDIT: ok , i've found out the problem : i kept getting a weird exception when using the MediaPlayer.Play() method , and after checking out about the exception , i've found out that it's a known issue , and that i need to call FrameworkDispatcher.Update(); right before i call the Play() method .

so the solution would be to do something like this:

Song song = Song.FromUri(...);
MediaPlayer.Stop(); 
FrameworkDispatcher.Update();
MediaPlayer.Play(song);

the exception is:

'System.InvalidOperationException' occurred in System.Windows.ni.dll"

i've found the solution here .

Now the question is why , and how come I didn't find anything related to it in the demos of windows phone ? Also , i would like to know what this function does .


ok , since nobody gave me an answer to both questions , and I still wish to give the bounty , I will ask another question :

If there is really no solution other than using the MediaPlayer class for windows phone , how do i capture the event of finishing playing an audio file ? Even getting the audio file duration doesn't work (keeps returning 0 length , no matter which class i've tried to use) ...


Solution

  • Use the MediaElement instead, this can play media files stored in your application, but stops playing when the application stops (you can make some advance chance to your app so it keep running, but it will not work very well)

    In your XAML:

            <Button x:Name="PlayFile"
                    Click="PlayFile_Click_1"
                    Content="Play mp3" />
    

    In your Code behind:

        MediaElement MyMedia = new MediaElement();
        // Constructor
        public MainPage()
        {
            InitializeComponent();
    
            this.LayoutRoot.Children.Add(MyMedia);
    
            MyMedia.CurrentStateChanged += MyMedia_CurrentStateChanged;
            MyMedia.MediaEnded += MyMedia_MediaEnded;
        }
    
        void MyMedia_MediaEnded(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Ended event " + MyMedia.CurrentState.ToString());
            // Set the source to null, force a Close event in current state
            MyMedia.Source = null;
        }
    
        void MyMedia_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
    
            switch (MyMedia.CurrentState)
            {
                case System.Windows.Media.MediaElementState.AcquiringLicense:
                    break;
                case System.Windows.Media.MediaElementState.Buffering:
                    break;
                case System.Windows.Media.MediaElementState.Closed:
                    break;
                case System.Windows.Media.MediaElementState.Individualizing:
                    break;
                case System.Windows.Media.MediaElementState.Opening:
                    break;
                case System.Windows.Media.MediaElementState.Paused:
                    break;
                case System.Windows.Media.MediaElementState.Playing:
                    break;
                case System.Windows.Media.MediaElementState.Stopped:
                    break;
                default:
                    break;
            }
    
            System.Diagnostics.Debug.WriteLine("CurrentState event " + MyMedia.CurrentState.ToString());
        }
    
        private void PlayFile_Click_1(object sender, RoutedEventArgs e)
        {
            // Play Awesome music file, stored as content in the Assets folder in your app
            MyMedia.Source = new Uri("Assets/AwesomeMusic.mp3", UriKind.RelativeOrAbsolute);
            MyMedia.Play();
        }