mediaplayer mp3 not working wpf
mp3, wpf
Solution
At least, there are two problems in your code, regarding how you attempted to play mp3 file using `MediaPlayer` :
- The main problem as you already suspected, is the wrong path to the file. Relative path means relative to the executable file. In development phase, it is inside `bin\debug` folder. So the path to the mp3 file should be `"../../AboutDialogSound.mp3"`.
- Another problem is declaring `MediaPlayer` object as local variable. By doing this, the object will be garbage-collected soon after the method where variable declared (`AboutDialog` constructor in this case) finished. So if you managed to fix the first problem, you will hear audio file played for a moment, then suddenly stopped because the `MediaPlayer` playing it GC-ed. Declare it as global variable instead of local.
Tips : To check for failure in `MediaPlayer` (such as file not found because of the wrong path), try to subscribe to the `MediaFailed` event. Because `MediaPlayer` doesn't throw exception, it trigger `MediaFailed` event instead.
public partial class AboutDialog
{
private MediaPlayer player;
public AboutDialog()
{
player = new MediaPlayer();
player.MediaFailed += (o, args) =>
{
MessageBox.Show("Media Failed!!");
};
player.Open(new Uri("../../AboutDialogSound.mp3", UriKind.RelativeOrAbsolute));
player.Play();
}
.....
}
Reference : http://www.wpf-tutorial.com/audio-video/playing-audio/
Problem
I have an issue with MediaPlayer class in WPF application. My project looks like this: The issue is: When my AboutDialog is initialized and appears, it doesn't play the AboutDialogSound.mp3. I think the problem is the Uri string format, I tried changing it but I still didn't work. I'm sorry I'm not good at English. Please help me with this issue. Thanks in advance.