Home > Software engineering >  How to play mp3 file from relative folder?
How to play mp3 file from relative folder?

Time:11-15

I tried to play a mp3 file from relative folder. I defined xaml look like.

<MediaElement x:Name="background_Sound" Source="\Music\Background_sound.mp3" LoadedBehavior="Pause" Volume="0.3" />

I want to play this file when the form open:

public MainWindow()
        {
            InitializeComponent();
            background_Sound.LoadedBehavior = MediaState.Play;

        }

But nothing happens. I tried full path other mp3 Source = "E:\test.mp3", it worked well.

I tried to find more solutions from internet. Can you give me your advance. Thank you so much.

CodePudding user response:

Make sure that

  • the MP3-File is located in a folder named Music in your Visual Studio Project
  • its Build Action is set to Content
  • the Copy to Output Directory option is set to Copy always or Copy if newer

Then load the file by a valid relative path URI, without a leading \.

<MediaElement Source="Music\Background_sound.mp3" .../>

Alternative URIs are ".\Music\Background_sound.mp3" or "Music/Background_sound.mp3" or "./Music/Background_sound.mp3"

  •  Tags:  
  • wpf
  • Related