[Solved] Why can’t I play an MP3 file from a separate object?


The code you are writing in the Offnen.cs file isn’t doing anything with the file because the variable “mp” is local to the object o (Offnen). Perhaps something like this is what you are looking for:

MainWindow.xaml.cs

#region Öffnen der Datei
private void menuOffnen_Click(object sender, RoutedEventArgs e)
{
    mp.Pause();
    Offnen o = new Offnen();
    o.OffnenDerDatei(mp);
    mp.Play();
}
#endregion

Offnen.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
using System.Windows.Media;

namespace Music_Player
{
    class Offnen : MainWindow
    {
        public void OffnenDerDatei(MediaPlayer mPlayer)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.DefaultExt = ".mp3";
            dlg.Filter = "MP3 files (*.mp3)|*.mp3|M4A files (*.m4a)|*.m4a|All files (*.*)|*.*";
            if (dlg.ShowDialog() == true)
            {
                mPlayer.Open(new Uri(dlg.FileName));
                //labelsong.Content = dlg.SafeFileName; // fyi this variable looks to be undeclared
            }
        }
    }
}

I see that you have Offnen inheriting from MainWindow, but I think you might be assuming that inheritance means it will inherit the object. This is not true, class inheritance simply inherits the structure, so all of the variables (such as mp and labelsong) that belong to MainWindow will not belong to an instance of Offnen that you create within MainWindow.

It’s probably beyond the scope of the question, but I would recommend you consider making the OffnenDerDatei a function that belongs to MainWindow. Otherwise, as you have it now, there is no point to Offnen inheriting from MainWindow.

0

solved Why can’t I play an MP3 file from a separate object?