0

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.

Hai Thanh
  • 5
  • 2
  • Does this answer your question? [Getting the application's directory from a WPF application](https://stackoverflow.com/questions/938421/getting-the-applications-directory-from-a-wpf-application) – Nawed Nabi Zada Nov 14 '22 at 10:16
  • Perhaps you need to remove \ at the beginning of path. – emoacht Nov 14 '22 at 10:31

1 Answers1

0

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"

Clemens
  • 123,504
  • 12
  • 155
  • 268