Search code examples
c#winformsvideomedia-player

Easy to use player to embed on winforms?


I need to embed a player that can play video files and use subtitles (.srt).

Which players (with good documentation) are available for this task? And how do I set the file and subtitle to it?


Solution

  • Workaround

    Add a Windows Media Player COM object.

    Add a Timer

    private Timer playingTimer = new Timer();
    public Main()
    {
        InitializeComponent();
        
        playingTimer.Enabled = false;
        playingTimer.Tick += renderSubtitles;
    }
    

    Handle StatusChange to know when it starts to play

    private void Main_Load(object sender, EventArgs e)
    {
        player.StatusChange += player_StatusChange;
    }
    

    Activate timer when playing

    void player_StatusChange(object sender, EventArgs e)
    {
        if (player.playState == WMPLib.WMPPlayState.wmppsPlaying)
        {
            playingTimer.Enabled = true;
        }
        else
        {
            playingTimer.Enabled = false;
        }
    }
    

    Get current seconds from player.Ctlcontrols.currentPosition, if a subtitle is found make the label visible, set the text and center horizontally. If there aren't any subtitles, hide the label.

    private void renderSubtitles(object sender, EventArgs e)
    {
        var ts = TimeSpan.FromSeconds(player.Ctlcontrols.currentPosition);
        var entry = entries.FirstOrDefault(o => o.Start <= ts && o.End >= ts);
    
        if (entry != null)
        {
            subtitle.Visible = true;
            subtitle.Text = entry.Text;
            
            var w = splitContainer.Panel1.Width;
            subtitle.Location = new Point(w / 2 - subtitle.Width / 2, subtitle.Location.Y);
        }
        else
        {
            subtitle.Visible = false;
        }
    }