播放结束时未调用C#MediaPlayer_MediaEnded

时间:2019-03-02 20:43:45

标签: c# .net multithreading media-player

我正在开发Juke Box,在其中使用媒体播放器组件,并希望在每首歌曲结束以将其从播放列表中移出时接收Media Ended事件,但从未调用MediaEnded事件。这是我的代码:

using System;
using System.Linq;
using System.Windows.Media;
using System.Threading;
using System.Collections.Generic;
using JukeBox.Models;

namespace JukeBox.Helpers
{
    public class BackgroundPlayer
    {
        private static List<SongModel> queue = new List<SongModel>();

        public static SongModel _currentSong;

        private bool threadStarted = false;
        private Thread workerThread = new Thread(new ThreadStart(ThreadMethod));

        private static MediaPlayer mediaPlayer;

        private static AutoResetEvent autoResetEvent = new AutoResetEvent(false);

        public int RandomTime { get; set; } = 1;
        public Action<string> SongFinished;
        public Action RandomTimeReached;
        public BackgroundPlayer()
        {
            workerThread.IsBackground = true;
        }
        public void EnqueueSong(SongModel songModel)
        {
            queue.Add(songModel);

            if (!threadStarted)
            {
                threadStarted = true;

                workerThread.Start();
            }
        }
        public static void ThreadMethod()
        {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.MediaEnded += MediaPlayer_MediaEnded;

            while (true)
            {
                if (queue.Count > 0)
                {
                    var _currentSong = queue.First();

                    mediaPlayer.Open(new Uri(_currentSong.SongFullPath));


                    mediaPlayer.Play();

                    autoResetEvent.WaitOne();
                }

                Thread.Sleep(1000);
            }
        }
        private static void MediaPlayer_MediaEnded(object sender, EventArgs e)
        {
            queue.Remove(_currentSong);

            autoResetEvent.Set();
        }
    }
}

有人可以向我解释问题出在哪里以及如何解决吗?

0 个答案:

没有答案