C#C
C#3y ago
10 replies
Billateral

❔ How to play music files from resources/relative paths in wpf c# ?

I have spend good 2 to 3 hours trying to get a sound file played from relative path, it just doesnt work no matter what I try, I have tried mediaplayer, later found on stackoverflow it doesnt work from relative path so i switched to sounplayer, I have tried like 20 different codes lines I dont understand how is this so hard, is there like no support for playing sound?

what i tried
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            System.IO.Stream stream = assembly.GetManifestResourceStream("Pomodoro.Music.taskdone2.wav");
            System.Media.SoundPlayer player = new System.Media.SoundPlayer(stream);
            player.Play();

 try
            {
                System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"Music\taskdone2.wav");
                //SoundPlayer player = new SoundPlayer(audioStream);
                player.Play();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }


string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Music\\taskdone2.mp3");
MediaPlayer player = new MediaPlayer();
player.Open(new Uri(path, UriKind.Absolute));
player.Play();


string relativePath = @"./Music/taskdone2.mp3";
string absolutePath = Path.GetFullPath(relativePath);

MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.Open(new Uri(absolutePath, UriKind.Absolute));
mediaPlayer.Play();

not even once was there a sound, only thing that worked was absolute path straight from c, which i dont know how could i use that for making an app that isnt always going to be in the same place
Was this page helpful?