• 首先看一下最终的程序效果 实现的功能: 1:打开播放的音视频文件((1)菜单栏“文件”->“打开”,(2)工具栏(下面)“打开”(3)播放器右键->打开) 2:暂停,继续播放,停止音视频文件 3:进度条和右下角文本框...

    首先看一下最终的程序效果


    实现的功能:

    1:打开播放的音视频文件((1)菜单栏“文件”->“打开”,(2)工具栏(下面)“打开”(3)播放器右键->打开)

    2:暂停,继续播放,停止音视频文件

    3:进度条和右下角文本框显示播放进度

    4:拖动进度条对视频定位播放

    5:工具栏(下面)“快进”,“快退”均为5s

    6:音量调节

    7:菜单栏“文件”下可记录最近播放的三个文件

    8:在有记录的情况下,初始状态时双击视频播放区或单击“播放”播放上次关闭时播放的视频


    需准备的东西:

    VLC的动态链接库*.dll

    1,在网上直接下载VLC播放器安装http://www.videolan.org点击打开链接/

    2,安装好后在VLC安装目录下libvlc.dll,libvlccore.dll及plugins目录下的所有文件拷贝到C#的debug目录下(下左图VLC安装目录,右图C#项目debug目录)

    若是release 也需放到release目录



    C#编程

    (1)创建一个C#的winform项目

    (2)c#封装libvlc的API接口

    新建一个类

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Security;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace WindowsFormsApplication1
    {
        class VlcPlayer
        {
            private IntPtr libvlc_instance_;
            private IntPtr libvlc_media_player_;
            private double duration_;
            public VlcPlayer(string pluginPath)
            {
                string plugin_arg = "--plugin-path=" + pluginPath;
                string[] arguments = { "-I", "dummy", "--ignore-config", "--no-video-title", plugin_arg };
                libvlc_instance_ = LibVlcAPI.libvlc_new(arguments);
    
                libvlc_media_player_ = LibVlcAPI.libvlc_media_player_new(libvlc_instance_);
            }
            public void SetRenderWindow(int wndHandle)
            {
                if (libvlc_instance_ != IntPtr.Zero && wndHandle != 0)
                {
                    LibVlcAPI.libvlc_media_player_set_hwnd(libvlc_media_player_, wndHandle);
                }
            }
            public void PlayFile(string filePath)
            {
                IntPtr libvlc_media = LibVlcAPI.libvlc_media_new_path(libvlc_instance_, filePath);
                if (libvlc_media != IntPtr.Zero)
                {
                    LibVlcAPI.libvlc_media_parse(libvlc_media);
                    duration_ = LibVlcAPI.libvlc_media_get_duration(libvlc_media) / 1000.0;
                    LibVlcAPI.libvlc_media_player_set_media(libvlc_media_player_, libvlc_media);
                    LibVlcAPI.libvlc_media_release(libvlc_media);
                    LibVlcAPI.libvlc_media_player_play(libvlc_media_player_);
                }
            }
            public void Pause()
            {
                if (libvlc_media_player_ != IntPtr.Zero)
                {
                    LibVlcAPI.libvlc_media_player_pause(libvlc_media_player_);
                }
            }
            public void Play()
            {
                if (libvlc_media_player_ != IntPtr.Zero)
                {
                    LibVlcAPI.libvlc_media_player_play(libvlc_media_player_);
                  //  LibVlcAPI.libvlc_media_player_pause(libvlc_media_player_);
                }
            }
            public void Stop()
            {
                if (libvlc_media_player_ != IntPtr.Zero)
                {
                    LibVlcAPI.libvlc_media_player_stop(libvlc_media_player_);
                }
            }
          //  public void FastForward()
           // {
            //    if (libvlc_media_player_ != IntPtr.Zero)
             //   {
              //      LibVlcAPI.libvlc_media_player_fastforward(libvlc_media_player_);
               // }
           // }
            public double GetPlayTime()
            {
                return LibVlcAPI.libvlc_media_player_get_time(libvlc_media_player_) / 1000.0;
            }
            public void SetPlayTime(double seekTime)
            {
                LibVlcAPI.libvlc_media_player_set_time(libvlc_media_player_, (Int64)(seekTime * 1000));
            }
            public int GetVolume()
            {
                return LibVlcAPI.libvlc_audio_get_volume(libvlc_media_player_);
            }
            public void SetVolume(int volume)
            {
                LibVlcAPI.libvlc_audio_set_volume(libvlc_media_player_, volume);
            }
            public void SetFullScreen(bool istrue)
            {
                LibVlcAPI.libvlc_set_fullscreen(libvlc_media_player_, istrue ? 1 : 0);
            }
            public double Duration()
            {
                return duration_;
            }
            public string Version()
            {
                return LibVlcAPI.libvlc_get_version();
            }
        }
        internal static class LibVlcAPI
        {
            internal struct PointerToArrayOfPointerHelper
            {
                [MarshalAs(UnmanagedType.ByValArray, SizeConst = 11)]
                public IntPtr[] pointers;
            }
            public static IntPtr libvlc_new(string[] arguments)
            {
                PointerToArrayOfPointerHelper argv = new PointerToArrayOfPointerHelper();
                argv.pointers = new IntPtr[11];
                for (int i = 0; i < arguments.Length; i++)
                {
                    argv.pointers[i] = Marshal.StringToHGlobalAnsi(arguments[i]);
                }
                IntPtr argvPtr = IntPtr.Zero;
                try
                {
                    int size = Marshal.SizeOf(typeof(PointerToArrayOfPointerHelper));
                    argvPtr = Marshal.AllocHGlobal(size);
                    Marshal.StructureToPtr(argv, argvPtr, false);
                    return libvlc_new(arguments.Length, argvPtr);
                }
                finally
                {
                    for (int i = 0; i < arguments.Length + 1; i++)
                    {
                        if (argv.pointers[i] != IntPtr.Zero)
                        {
                            Marshal.FreeHGlobal(argv.pointers[i]);
                        }
                    }
                    if (argvPtr != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(argvPtr);
                    }
                }
            }
            public static IntPtr libvlc_media_new_path(IntPtr libvlc_instance, string path)
            {
                IntPtr pMrl = IntPtr.Zero;
                try
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(path);
                    pMrl = Marshal.AllocHGlobal(bytes.Length + 1);
                    Marshal.Copy(bytes, 0, pMrl, bytes.Length);
                    Marshal.WriteByte(pMrl, bytes.Length, 0);
                    return libvlc_media_new_path(libvlc_instance, pMrl);
                }
                finally
                {
                    if (pMrl != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(pMrl);
                    }
                }
            }
            public static IntPtr libvlc_media_new_location(IntPtr libvlc_instance, string path)
            {
                IntPtr pMrl = IntPtr.Zero;
                try
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(path);
                    pMrl = Marshal.AllocHGlobal(bytes.Length + 1);
                    Marshal.Copy(bytes, 0, pMrl, bytes.Length);
                    Marshal.WriteByte(pMrl, bytes.Length, 0);
                    return libvlc_media_new_path(libvlc_instance, pMrl);
                }
                finally
                {
                    if (pMrl != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(pMrl);
                    }
                }
            }
    
            // ----------------------------------------------------------------------------------------
            // 以下是libvlc.dll导出函数
    
            // 创建一个libvlc实例,它是引用计数的
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            private static extern IntPtr libvlc_new(int argc, IntPtr argv);
    
            // 释放libvlc实例
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_release(IntPtr libvlc_instance);
    
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern String libvlc_get_version();
    
            // 从视频来源(例如Url)构建一个libvlc_meida
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            private static extern IntPtr libvlc_media_new_location(IntPtr libvlc_instance, IntPtr path);
    
            // 从本地文件路径构建一个libvlc_media
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            private static extern IntPtr libvlc_media_new_path(IntPtr libvlc_instance, IntPtr path);
    
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_media_release(IntPtr libvlc_media_inst);
    
            // 创建libvlc_media_player(播放核心)
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern IntPtr libvlc_media_player_new(IntPtr libvlc_instance);
    
            // 将视频(libvlc_media)绑定到播放器上
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_media_player_set_media(IntPtr libvlc_media_player, IntPtr libvlc_media);
    
            // 设置图像输出的窗口
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_media_player_set_hwnd(IntPtr libvlc_mediaplayer, Int32 drawable);
    
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_media_player_play(IntPtr libvlc_mediaplayer);
    
            /// <summary>
            /// 
            /// </summary>
            /// <param name="libvlc_mediaplayer"></param>
            //[DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            //[SuppressUnmanagedCodeSecurity]
           // public static extern void libvlc_media_player_fastforward(IntPtr libvlc_mediaplayer);
    
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_media_player_pause(IntPtr libvlc_mediaplayer);
    
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_media_player_stop(IntPtr libvlc_mediaplayer);
    
            // 解析视频资源的媒体信息(如时长等)
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_media_parse(IntPtr libvlc_media);
    
            // 返回视频的时长(必须先调用libvlc_media_parse之后,该函数才会生效)
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern Int64 libvlc_media_get_duration(IntPtr libvlc_media);
    
            // 当前播放的时间
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern Int64 libvlc_media_player_get_time(IntPtr libvlc_mediaplayer);
    
            // 设置播放位置(拖动)
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_media_player_set_time(IntPtr libvlc_mediaplayer, Int64 time);
    
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_media_player_release(IntPtr libvlc_mediaplayer);
    
            // 获取和设置音量
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern int libvlc_audio_get_volume(IntPtr libvlc_media_player);
    
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_audio_set_volume(IntPtr libvlc_media_player, int volume);
    
            // 设置全屏
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_set_fullscreen(IntPtr libvlc_media_player, int isFullScreen);
    
        }
    }
    
    (3)窗口布局编辑


    (3)选几个要点说说,其余参考附件的源码

    1,播放过程中的窗口右键菜单问题

    注意窗口布局中黑色panel那块有两个panel,一个panel1,一个panel2,panel1位于底层,panel2位于表层,panel2背景色设置为transparent,这么做的原因是panel1在指定成播放后contextMenuStrip属性失效,为了能在播放后仍能在播放区使用右键并且不影响播放,故添加透明的panel2

    2,记录之前打开的三次文件

            /// <summary>
            /// 菜单栏文件实现功能
            /// 1 打开待播放文件
            /// 2 记录历史信息
            /// 3 历史信息最多不超过3条
            /// 4 点击历史信息可以实现播放menuitem_Click()
            /// 5 如果点击历史信息不能播放(出现错误)则删除该历史信息item和Menu.ini (方法:try catch)
            /// 6 Menu.ini记录的信息最多不超过3条,不重复记录
            /// 7 在历史信息中右键可以选择删除
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            /// 
            #region 菜单栏-文件
    
    
            /// <summary>
            /// 打开ToolStripMenuItem_Click
            /// 打开文件并将文件目录添加到Menu.ini
            /// 若打开相同文件则不添加(这个有Bug,这样的话按tsBtn_play打开的就不是上一个了,因为打开相同的不添加)
            /// 若记录行数超过3个,则先记录后三个数据,再重新建一个Menu.ini(清除数据),接着讲记录的后三个数据写入
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            /// 
            private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
            {
                //bool isSame = false;
                openFileDialog1.FileName = "";
                if(this.openFileDialog1.ShowDialog()==DialogResult.OK)
                { 
                    //StreamReader sr0 = new StreamReader(address + "\\Menu.ini", true);
                   // while (sr0.Peek() > -1)
                   // {
                  //      if ((sr0.ReadLine() == openFileDialog1.FileName)|(openFileDialog1.FileName==""))
                  //      {
                  //          isSame = true;
                   //     }
                  //  }
                   // sr0.Close();
                   // if (isSame == false)// 若打开相同文件则不添加
                  //  {
                        StreamWriter s = new StreamWriter(address + "\\Menu.ini", true);
                        s.WriteLine(openFileDialog1.FileName);
                        s.Flush();
                        s.Close();
                 //   }
                    string[] text = File.ReadAllLines(address + "\\Menu.ini");
                    int row = text.Length;//行
                    int rowcount;
                    string[] tempdata = new string[] {"","",""};
                    if (row > 3)// 若记录行数超过3个,则先记录后三个数据,再重新建一个Menu.ini(清除数据),接着讲记录的后三个数据写入
                    {
                        StreamReader sr1 = new StreamReader(address + "\\Menu.ini", true);
                        while (sr1.Peek() > -1)
                        {
                            sr1.ReadLine();//空读,跳过原始的第一个数据,从第二个数据开始读
                            for (rowcount = 0; rowcount < 3; rowcount++)
                            {
                                tempdata[rowcount] = sr1.ReadLine();
                            }
                        }
                        sr1.Close();
                        FileStream fs = new FileStream(address + "\\Menu.ini", FileMode.Create, FileAccess.Write);
                        fs.Close();
                        StreamWriter s1 = new StreamWriter(address + "\\Menu.ini", true);
                        s1.WriteLine(tempdata[0]);
                        s1.WriteLine(tempdata[1]);
                        s1.WriteLine(tempdata[2]);
                        s1.Flush();
                        s1.Close();
                    }
                   // StreamReader sr2 = new StreamReader(address + "\\Menu.ini", true);
                   // while(sr2.Pee)
                    vlcPlayer.PlayFile(openFileDialog1.FileName);
                    trackBar1.SetRange(0, (int)vlcPlayer.Duration());
                    trackBar1.Value = 0;
                    timer1.Start();
                    is_playinig = true;
                    tSBtn_play.Image = Properties.Resources.暂停;
                    tSBtn_play.Text = "暂停";
                    media_is_open = true;              
                    //label_media_name.Text = openFileDialog1.FileName.Substring(openFileDialog1.FileName.LastIndexOf('\\') + 1, openFileDialog1.FileName.Length - 1 - openFileDialog1.FileName.LastIndexOf('\\'));
                    //获取文件名的另一种方法,不带后缀
                    label_media_name.Text = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
                    label_media_name.Show();
                }
            }
            /// <summary>
            /// 将Menu.ini中的历史记录添加到文件菜单栏
            /// </summary>
            private void readFilePath()
            {
                int items_count = this.文件ToolStripMenuItem.DropDownItems.Count;
                switch (items_count)
                {
                    case 4:
                        this.文件ToolStripMenuItem.DropDownItems.RemoveAt(1);
                        break;
                    case 5:
                        this.文件ToolStripMenuItem.DropDownItems.RemoveAt(1);//移走第一项后原本第二项又成第一项了,所以继续移走第一项
                        this.文件ToolStripMenuItem.DropDownItems.RemoveAt(1);
                        break;
                    case 6:
                        this.文件ToolStripMenuItem.DropDownItems.RemoveAt(1);
                        this.文件ToolStripMenuItem.DropDownItems.RemoveAt(1);
                        this.文件ToolStripMenuItem.DropDownItems.RemoveAt(1);
                        break;
                    default:
                        break;
                }
                
                StreamReader sr = new StreamReader(address + "\\Menu.ini", true);
                int i =1;
                while (sr.Peek() > -1)//peek是用来确定你read的文件是否结束了,如果结束了会返回int型 -1 
                {
                        ToolStripMenuItem menuitem = new ToolStripMenuItem(sr.ReadLine());
                        this.文件ToolStripMenuItem.DropDownItems.Insert(i, menuitem);
                        i++;
                        menuitem.Click += new EventHandler(menuitem_Click); 
                }
                sr.Close();
            }
            /// <summary>
            /// 打开历史记录并播放
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void menuitem_Click(object sender, EventArgs e)
            {
                try
                {
                    ToolStripMenuItem menu = (ToolStripMenuItem)sender;
                    vlcPlayer.PlayFile(menu.Text);
                    trackBar1.SetRange(0, (int)vlcPlayer.Duration());
                    trackBar1.Value = 0;
                    timer1.Start();
                    is_playinig = true;
                    tSBtn_play.Image = Properties.Resources.暂停;
                    tSBtn_play.Text = "暂停";
                    media_is_open = true;
                    label_media_name.Text = Path.GetFileNameWithoutExtension(menu.Text);
                    label_media_name.Show();
                }
                catch
                {
                    MessageBox.Show("文件不存在", "提示");
                }
            }
    
            private void 文件ToolStripMenuItem_Click(object sender, EventArgs e)
            {
                readFilePath();
            }
            #endregion

    这段代码中这个地方注意:

    <span style="white-space:pre">		</span>    this.文件ToolStripMenuItem.DropDownItems.RemoveAt(1);
                        this.文件ToolStripMenuItem.DropDownItems.RemoveAt(1);
                        this.文件ToolStripMenuItem.DropDownItems.RemoveAt(1);
    这段原因是每移除菜单选项标号1的历史记录后,原本的标号2又变成标号1,所以继续删除标号1,而不是删除标号2;

    3,在有以前播放记录情况下打开软件直接点击播放时播放上次打开的音视频实现代码

    private void tSBtn_play_Click(object sender, EventArgs e)
            {
                if (is_playinig)
                {
                    vlcPlayer.Pause();
                    timer1.Stop();
                    is_playinig = false;
                    tSBtn_play.Image = Properties.Resources.开始;
                    tSBtn_play.Text = "播放";
                }
                else
                {
                    try
                    {
                        string[] text = File.ReadAllLines(address + "\\Menu.ini");
                        string openfilepath="";
                        int row = text.Length;//行
                        StreamReader sr1 = new StreamReader(address + "\\Menu.ini", true);
                        switch (row)
                        {
                            case 1:
                                openfilepath=sr1.ReadLine();
                                break;
                            case 2:
                                sr1.ReadLine();
                                openfilepath = sr1.ReadLine();
                                break;
                            case 3:
                                sr1.ReadLine();
                                sr1.ReadLine();
                                openfilepath = sr1.ReadLine();
                                break;
                            default:
                                break;
                        }
                        if(row==1||row==2||row==3)
                        {
                            
                            if (!media_is_open) 
                            {
                                vlcPlayer.PlayFile(openfilepath);
                            }
                            trackBar1.SetRange(0, (int)vlcPlayer.Duration());
                            vlcPlayer.SetPlayTime(trackBar1.Value);
                            vlcPlayer.Play();
                            trackBar1.Value = (int)vlcPlayer.GetPlayTime();
                           // trackBar1.Value = 0;
                            timer1.Start();
                            is_playinig = true;
                            tSBtn_play.Image = Properties.Resources.暂停;
                            tSBtn_play.Text = "暂停";
                            media_is_open = true;
                            label_media_name.Text = Path.GetFileNameWithoutExtension(openfilepath);
                            label_media_name.Show();
                        }
                        sr1.Close();
                    }
                    catch (Exception er)
                    {
                        MessageBox.Show("文件不存在", "提示");
                    }
                }
            }
    4,快进和快退实现方法,以快进为例

    private void tSB_forward_Click(object sender, EventArgs e)
            {
                vlcPlayer.Pause();
                int time = (int)vlcPlayer.GetPlayTime() + 5;
                if (time < trackBar1.Maximum)
                {
                    vlcPlayer.SetPlayTime(time);
                }
                else
                {
                    vlcPlayer.SetPlayTime(trackBar1.Maximum);
                }
                vlcPlayer.Play();
                trackBar1.Value = (int)vlcPlayer.GetPlayTime();
            }
    VLC的库中并没有快进快退方法(这个我不太确定,我没发现,若有麻烦告知我下,非常感谢)

    所以可以先将视频暂停,然后在重新设置视频的播放时间,再播放即可


    其余未说到的地方可以参考源码,欢迎跟帖交流

    参考帖子:

    http://www.cnblogs.com/haibindev/archive/2011/12/21/2296173.html

    http://blog.csdn.net/leixiaohua1020/article/details/42363079

    http://bbs.csdn.net/topics/390936942

    附源码
    http://download.csdn.net/detail/u012342996/9505082


    展开全文
  • C# VLC视频播放器

    2019-08-02 08:20:05
    1:vlc的plugins目录太大,没有上传,你可以自己添加vlc的plugins目录里面的插件 2:添加libvlc.dll、libvlccore.dll 两个文件 libvlc接口: #region libvlc_media.h /// <summary> /// 使用一个...

        

    1:vlc的plugins目录太大,没有上传,你可以自己添加vlc的plugins目录里面的插件

    2:添加libvlc.dll、libvlccore.dll 两个文件

    libvlc接口:

    #region libvlc_media.h
    
            /// <summary>
            /// 使用一个给定的媒体资源路径来建立一个(libvlc_media实例)
            /// </summary>
            /// <param name="libvlc">(libvlc实例)</param>
            /// <param name="psz_mrl">要读取的MRL(Media Resource Location)</param>
            /// <returns>(libvlc_media实例)或NULL</returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr libvlc_media_new_location(IntPtr libvlc, [MarshalAs(UnmanagedType.LPArray)] byte[] psz_mrl);
    
            /// <summary>
            /// 从本地文件系统路径来建立一个(libvlc_media实例)
            /// </summary>
            /// <param name="libvlc">(libvlc实例)</param>
            /// <param name="psz_mrl">要读取的MRL(Media Resource Location)</param>
            /// <returns>(libvlc_media实例)或NULL</returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr libvlc_media_new_path(IntPtr libvlc, [MarshalAs(UnmanagedType.LPArray)] byte[] psz_mrl);
    
            /// <summary>
            /// 使用给定的名称创建一个libvlc_media_t并将其作为一个空的节点
            /// </summary>
            /// <param name="libvlc">(libvlc实例)</param>
            /// <param name="psz_name"></param>
            /// <returns>(libvlc_media实例)或NULL</returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr libvlc_media_new_as_node(IntPtr libvlc, [MarshalAs(UnmanagedType.LPArray)] byte[] psz_name);
    
            /// <summary>
            /// 此选项将用于确定media_player如何读取媒体。这允许在每个媒体的基础上使用VLC的高级读/流选项。这些选项在vlc -long-help中有详细说明,
            /// 例如“--sout-all”。请注意,所有选项在媒体上都不可用:具体而言,由于体系结构问题,无法在单个媒体上设置视频相关选项(如文本渲染器选项)
            /// 。必须在整个libvlc实例上设置它们。
            /// </summary>
            /// <param name="libvlc_media">(libvlc_media实例)</param>
            /// <param name="psz_options ">选项(作为字符串)</param>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern void libvlc_media_add_option(IntPtr libvlc_media, [MarshalAs(UnmanagedType.LPArray)] byte[] psz_options);
    
            /// <summary>
            /// 此选项将用于确定media_player如何读取媒体。这允许在每个媒体的基础上使用VLC的高级读/流选项。这些选项在vlc -long-help中有详细说明,
            /// 例如“--sout-all”。请注意,所有选项在媒体上都不可用:具体而言,由于体系结构问题,无法在单个媒体上设置视频相关选项(如文本渲染器选项)
            /// 。必须在整个libvlc实例上设置它们。
            /// </summary>
            /// <param name="libvlc_media">(libvlc_media实例)</param>
            /// <param name="psz_options">选项(作为字符串)</param>
            /// <param name="i_flags">此选项的标志</param>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern void libvlc_media_add_option_flag(IntPtr libvlc_media, [MarshalAs(UnmanagedType.LPArray)] byte[] psz_options, int i_flags);
    
            /// <summary>
            /// 保留一个引用到一个媒体描述对象(libvlc_media_t.使用libvlc_media_release()来减少一个媒体描述对象的引用计数
            /// </summary>
            /// <param name="libvlc_media">(libvlc_media实例)</param>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern void libvlc_media_retain(IntPtr libvlc_media);
    
            /// <summary>
            /// 减少一个libvlc_media_t的引用计数,如果引用计数为0,则libvlc_media_release()将释放媒体描述符对象。它将向所有侦听器发送libvlc_MediaFreed事件
            /// 。如果已释放媒体描述符对象,则不应再次使用它
            /// </summary>
            /// <param name="libvlc_media">(libvlc_media实例)</param>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern void libvlc_media_release(IntPtr libvlc_media);
    
            /// <summary>
            /// 从媒体描述符对象获取媒体资源定位符(mrl)
            /// </summary>
            /// <param name="libvlc_media">(libvlc_media实例)</param>
            /// <returns></returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            [return: MarshalAs(UnmanagedType.AnsiBStr)]
            public static extern string libvlc_media_get_mrl(IntPtr libvlc_media);
    
            /// <summary>
            /// 复制媒体描述符对象。
            /// </summary>
            /// <param name="libvlc_media">(libvlc_media实例)</param>
            /// <returns></returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr libvlc_media_duplicate(IntPtr libvlc_media);
    
            /// <summary>
            /// 获取媒体的元数据。如果媒体还没被解析,则返回NULL,这个方法会自动调用
            /// </summary>
            /// <param name="libvlc_media">(libvlc_media实例)</param>
            /// <param name="e_meta">要阅读的元数据</param>
            /// <returns>媒体的元数据</returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr libvlc_media_get_meta(IntPtr libvlc_media, libvlc_meta_t e_meta);
    
            /// <summary>
            /// 设置媒体的元数据,此方法不会保存数据,还需要调用libvlc_media_save_meta()来保存.
            /// </summary>
            /// <param name="libvlc_media">(libvlc_media实例)</param>
            /// <param name="e_meta">要设置的元数据</param>
            /// <param name="psz_value"></param>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern void libvlc_media_set_meta(IntPtr libvlc_media, libvlc_meta_t e_meta, [MarshalAs(UnmanagedType.LPArray)] byte[] psz_value);
    
            /// <summary>
            /// 保存以前设置的元数据
            /// </summary>
            /// <param name="libvlc_media">(libvlc_media实例)</param>
            /// <returns>如果写操作成功,则为true</returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern int libvlc_media_save_meta(IntPtr libvlc_media);
    
            /// <summary>
            /// 获取媒体描述符对象的当前状态。可能的媒体状态是libvlc_NothingSpecial = 0,libvlc_Opening,libvlc_Playing,libvlc_Paused,libvlc_Stopped,
            /// libvlc_Ended,libvlc_Error
            /// </summary>
            /// <param name="libvlc_media">(libvlc_media实例)</param>
            /// <returns></returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern libvlc_state_t libvlc_media_get_state(IntPtr libvlc_media);
    
            /// <summary>
            /// 获取有关媒体的最新统计信息。
            /// </summary>
            /// <param name="libvlc_media">(libvlc_media实例)</param>
            /// <param name="p_stats">包含媒体统计信息的结构(此结构必须由调用者分配)</param>
            /// <returns>如果统计信息可用,则为true,否则为false</returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern int libvlc_media_get_stats(IntPtr libvlc_media, out libvlc_media_stats_t p_stats);
    
            /// <summary>
            /// 获取媒体描述符对象的子项。这将增加提供的媒体描述符对象的引用计数。使用libvlc_media_list_release()减少引用计数。
            /// </summary>
            /// <param name="libvlc_media">(libvlc_media实例)</param>
            /// <returns>媒体描述符子项列表或NULL</returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr libvlc_media_subitems(IntPtr libvlc_media);
    
            /// <summary>
            /// 获得一个媒体描述对象的事件管理器.
            /// </summary>
            /// <param name="libvlc_media">(libvlc_media实例)</param>
            /// <returns></returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr libvlc_media_event_manager(IntPtr libvlc_media);
    
            /// <summary>
            /// 获取媒体描述符对象项的持续时间(以毫秒为单位)
            /// </summary>
            /// <param name="libvlc_media">(libvlc_media实例)</param>
            /// <returns>媒体项的持续时间或错误的-1</returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern Int64 libvlc_media_get_duration(IntPtr libvlc_media);
    
            /// <summary>
            /// 解析一个本地媒体的元数据和轨道信息,此方法是同步的.
            /// </summary>
            /// <param name="libvlc_media">(libvlc_media实例)</param>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern void libvlc_media_parse(IntPtr libvlc_media);
    
            /// <summary>
            /// 同上,此方法不同步,你可以监听libvlc_MediaParsedChanged事件来追踪他,如果已经被解析过了则此事件不会被触发。
            /// </summary>
            /// <param name="libvlc_media">(libvlc_media实例)</param>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern void libvlc_media_parse_async(IntPtr libvlc_media);
    
            /// <summary>
            /// 获得一个媒体描述对象的分析状态。
            /// </summary>
            /// <param name="libvlc_media">(libvlc_media实例)</param>
            /// <returns>当分析过了返回true</returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern bool libvlc_media_is_parsed(IntPtr libvlc_media);
    
            /// <summary>
            /// 获取媒体描述符的用户数据,此数据仅被host程序访问,VLC.framework将它作为一个指向一个引用了一个libvlc_media_t指针的本地对象的指针来使用
            /// </summary>
            /// <param name="libvlc_media">(libvlc_media实例)</param>
            /// <returns></returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern IntPtr libvlc_media_get_user_data(IntPtr libvlc_media);
    
            /// <summary>
            /// 设置媒体描述符的用户数据,此数据仅被host程序访问,VLC.framework将它作为一个指向一个引用了一个libvlc_media_t指针的本地对象的指针来使用
            /// </summary>
            /// <param name="libvlc_media">(libvlc_media实例)</param>
            /// <param name="p_new_user_data"></param>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern void libvlc_media_set_user_data(IntPtr libvlc_media, IntPtr p_new_user_data);
    
            /// <summary>
            /// 获取媒体描述符的基本流描述。 注意,在调用此函数之前,您需要至少调用一次libvlc_media_parse()或播放媒体。不这样做会导致数组为空。
            /// </summary>
            /// <param name="libvlc_media">(libvlc_media实例)</param>
            /// <param name="tracks">用于存储已分配的基本流描述数组的地址(必须由调用者释放)[OUT]</param>
            /// <returns></returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl)]
            public static extern int libvlc_media_get_tracks_info(IntPtr libvlc_media, out IntPtr tracks);
    
            #endregion
    源码

     主页面代码:

    public MainForm()
            {
                InitializeComponent();
                mainForm = this;
    
                m_factory = new MediaPlayerFactory();
                m_player = m_factory.CreatePlayer<IDiskPlayer>();
                m_formfile = m_factory.CreateMedia<IMediaFromFile>(this.filepath);
    
                #region  player事件
    
                m_player.Events.PlayerPositionChanged += new EventHandler<MediaPlayerPositionChanged>(Events_PlayerPositionChanged);
                m_player.Events.TimeChanged += new EventHandler<MediaPlayerTimeChanged>(Events_TimeChanged);
                m_player.Events.MediaEnded += new EventHandler(Events_MediaEnded);
                m_player.Events.PlayerStopped += new EventHandler(Events_PlayerStopped);
    
                #endregion
    
                #region videoTopControl
    
                this.videoTopControl.DoubleClick += new EventHandler(videoTopControl_DoubleClick);
                this.videoTopControl.MouseDown += new MouseEventHandler(this.videoTopControl_MouseDown);
                this.videoTopControl.MouseMove += new MouseEventHandler(videoTopControl_MouseMove);
                this.videoTopControl.minbtn.Click += new EventHandler(minbtn_Click);
                this.videoTopControl.chuangkouhuabtn.Click += new EventHandler(chuangkouhuabtn_Click);
                this.videoTopControl.guanbibtn.Click += new EventHandler(guanbibtn_Click);
    
                #endregion
    
                #region  videoBottomControl
    
    
                this.videoBottomControl.MouseDown += new MouseEventHandler(this.videoBottomControl_MouseDown);
                this.videoBottomControl.MouseMove += new MouseEventHandler(videoBottomControl_MouseMove);
                this.videoBottomControl.manjinbtn.Click += new EventHandler(manjinbtn_Click);
                this.videoBottomControl.videoProgressControl.MouseDown += new MouseEventHandler(videoProgressControl_MouseDown);
                this.videoBottomControl.videoProgressControl.MouseMove += new MouseEventHandler(videoProgressControl_MouseMove);
                this.videoBottomControl.videoProgressControl.MouseLeave += new EventHandler(videoProgressControl_MouseLeave);
                this.videoBottomControl.videoProgressControl.progressChange += new ProgressChange(videoProgressControl_progressChange);
                this.videoBottomControl.kuaijinbtn.Click += new EventHandler(kuaijinbtn_Click);
                this.videoBottomControl.stopbtn.Click += new EventHandler(stopbtn_Click);
                this.videoBottomControl.playbtn.Click += new EventHandler(playbtn_Click);
                this.videoBottomControl.jinyinbtn.Click += new EventHandler(jinyinbtn_Click);
                this.videoBottomControl.AudioProgressControl.MouseDown += new MouseEventHandler(AudioProgressControl_MouseDown);
                this.videoBottomControl.AudioProgressControl.progressChange += new ProgressChange(AudioProgressControl_progressChange);
                this.videoBottomControl.openfilebtn.Click += new EventHandler(openfilebtn_Click);
                this.videoBottomControl.liebiaobtn.Click += new EventHandler(liebiaobtn_Click);
    
    
    
                #endregion
    
                this.m_player.WindowHandle = this.playpanel.Handle;
                this.videoBottomControl.jinyinbtn.ToolTipText = m_player.Volume.ToString() + "%音量";
                UISync.Init(this);
                this.videosplit.Panel2Collapsed = true;
                this.videoBottomControl.AudioProgressControl.DanQianShiChang = this.m_player.Volume / 100.0f;
                this.videoBottomControl.manjinbtn.ToolTipText = "1.0倍播放速度";
                this.videoBottomControl.kuaijinbtn.ToolTipText = "1.0倍播放速度";
                this.rct = this.RectangleToScreen(new Rectangle(this.Location, new Size(this.Width, this.Height)));
            }

     

    源码下载地址:VLC视频播放器

    转载于:https://www.cnblogs.com/tlmbem/p/10689804.html

    展开全文
  • vlcPlayer是一款免费开源的播放器项目,可以播放几乎所有的视频格式。 第一步:获取dll 安装vlcplayer视频播放器,在安装目录下面获取所需的dll。 dll文件夹:plugins 还有2个dll:libvlc.dll,libvlccore.dll ...

    vlcPlayer是一款免费开源的播放器项目,可以播放几乎所有的视频格式。

    第一步:获取dll

    安装vlcplayer视频播放器,在安装目录下面获取所需的dll。

    dll文件夹:plugins

    还有2个dll:libvlc.dll,libvlccore.dll

    第二步:获取播放器对象基类VlcPlayerBase

    using System;
    using System.Runtime.InteropServices;
    using System.Security;
    using System.Text;
    
    namespace VlcPlayer
    {
        public class VlcPlayerBase
        {
            private IntPtr libvlc_instance_;
            private IntPtr libvlc_media_player_;
    
            /// <summary>
            /// 视频时长
            /// </summary>
            private double duration_;
    
            /// <summary>
            /// VLC 播放器。
            /// </summary>
            /// <param name="pluginPath"></param>
            public VlcPlayerBase(string pluginPath)
            {
                //string pluginPath = Environment.CurrentDirectory + "\\vlc\\plugins\\";  //插件目录
                string plugin_arg = "--plugin-path=" + pluginPath;
                string[] arguments = { "-I", "dummy", "--ignore-config", "--no-video-title", plugin_arg };
                libvlc_instance_ = LibVlcAPI.libvlc_new(arguments);
    
                libvlc_media_player_ = LibVlcAPI.libvlc_media_player_new(libvlc_instance_);  //创建 libvlc_media_player 播放核心
            }
    
            /// <summary>
            /// 设置播放容器
            /// </summary>
            /// <param name="wndHandle">播放容器句柄</param>
            public void SetRenderWindow(int wndHandle)
            {
                if (libvlc_instance_ != IntPtr.Zero && wndHandle != 0)
                {
                    LibVlcAPI.libvlc_media_player_set_hwnd(libvlc_media_player_, wndHandle);  //设置播放容器
                }
            }
            
            /// <summary>
            /// 播放指定媒体文件
            /// </summary>
            /// <param name="filePath"></param>
            public void LoadFile(string filePath)
            {
                IntPtr libvlc_media = LibVlcAPI.libvlc_media_new_path(libvlc_instance_, filePath);  //创建 libvlc_media_player 播放核心
                if (libvlc_media != IntPtr.Zero)
                {
                    LibVlcAPI.libvlc_media_parse(libvlc_media);
                    duration_ = LibVlcAPI.libvlc_media_get_duration(libvlc_media) / 1000.0;  //获取视频时长
    
                    LibVlcAPI.libvlc_media_player_set_media(libvlc_media_player_, libvlc_media);  //将视频绑定到播放器去
                    LibVlcAPI.libvlc_media_release(libvlc_media);
    
                    //LibVlcAPI.libvlc_media_player_play(libvlc_media_player_);  //播放
                }
            }
    
            /// <summary>
            /// 播放
            /// </summary>
            public void Play()
            {
                if (libvlc_media_player_ != IntPtr.Zero)
                {
                    LibVlcAPI.libvlc_media_player_play(libvlc_media_player_);
                }
            }
    
            /// <summary>
            /// 暂停播放
            /// </summary>
            public void Pause()
            {
                if (libvlc_media_player_ != IntPtr.Zero)
                {
                    LibVlcAPI.libvlc_media_player_pause(libvlc_media_player_);
                }
            }
    
            /// <summary>
            /// 停止播放
            /// </summary>
            public void Stop()
            {
                if (libvlc_media_player_ != IntPtr.Zero)
                {
                    LibVlcAPI.libvlc_media_player_stop(libvlc_media_player_);
                }
            }
    
            public void Release()
            {
                if (libvlc_media_player_ != IntPtr.Zero)
                {
                    LibVlcAPI.libvlc_media_release(libvlc_media_player_);
                }
            }
            
            /// <summary>
            /// 获取播放时间进度
            /// </summary>
            /// <returns></returns>
            public double GetPlayTime()
            {
                return LibVlcAPI.libvlc_media_player_get_time(libvlc_media_player_) / 1000.0;
            }
    
            /// <summary>
            /// 设置播放时间
            /// </summary>
            /// <param name="seekTime"></param>
            public void SetPlayTime(double seekTime)
            {
                LibVlcAPI.libvlc_media_player_set_time(libvlc_media_player_, (Int64)(seekTime * 1000));
            }
    
            /// <summary>
            /// 获取音量
            /// </summary>
            /// <returns></returns>
            public int GetVolume()
            {
                return LibVlcAPI.libvlc_audio_get_volume(libvlc_media_player_);
            }
    
            /// <summary>
            /// 设置音量
            /// </summary>
            /// <param name="volume"></param>
            public void SetVolume(int volume)
            {
                LibVlcAPI.libvlc_audio_set_volume(libvlc_media_player_, volume);
            }
    
            /// <summary>
            /// 设置是否全屏
            /// </summary>
            /// <param name="istrue"></param>
            public void SetFullScreen(bool istrue)
            {
                LibVlcAPI.libvlc_set_fullscreen(libvlc_media_player_, istrue ? 1 : 0);
            }
    
            /// <summary>
            /// 视频时长
            /// </summary>
            /// <returns></returns>
            public double Duration { get { return duration_; } }
    
            /// <summary>
            /// 是否正在播放
            /// </summary>
            public bool IsPlaying
            {
                get
                {
                    if (Duration > 0 && (int)GetPlayTime() == (int)Duration) this.Stop();  //如果播放完,关闭视频
    
                    return (int)GetPlayTime() < (int)Duration /* 播放时间进度小于视频时长 */
                        && Duration > 0 /* 播放时间进度大于0 */
                        && GetPlayTime() > 0; /* 视频时长大于0 */
                }
            }
            
            /// <summary>
            /// 获取版本(VS2015 调试模式程序会直接崩掉)
            /// </summary>
            /// <returns></returns>
            public string Version { get { return LibVlcAPI.libvlc_get_version(); } }
    
        }
    
        #region vlclib.dll
    
        internal static class LibVlcAPI
        {
            internal struct PointerToArrayOfPointerHelper
            {
                [MarshalAs(UnmanagedType.ByValArray, SizeConst = 11)]
                public IntPtr[] pointers;
            }
    
            /// <summary>
            /// 传入播放参数
            /// </summary>
            /// <param name="arguments"></param>
            /// <returns></returns>
            public static IntPtr libvlc_new(string[] arguments)
            {
                PointerToArrayOfPointerHelper argv = new PointerToArrayOfPointerHelper();
                argv.pointers = new IntPtr[11];
    
                for (int i = 0; i < arguments.Length; i++)
                {
                    argv.pointers[i] = Marshal.StringToHGlobalAnsi(arguments[i]);  //将托管 System.String 中的内容复制到非托管内存,并在复制时转换为 ANSI 格式。
                }
    
                IntPtr argvPtr = IntPtr.Zero;
                try
                {
                    int size = Marshal.SizeOf(typeof(PointerToArrayOfPointerHelper));  //返回非托管类型的大小(以字节为单位)。
                    argvPtr = Marshal.AllocHGlobal(size);  //从进程的非托管内存中分配内存。
                    Marshal.StructureToPtr(argv, argvPtr, false);  //将数据从托管对象封送到非托管内存块。
    
                    return libvlc_new(arguments.Length, argvPtr);  //创建一个libvlc实例,它是引用计数的
                }
                finally
                {
                    for (int i = 0; i < arguments.Length + 1; i++)
                    {
                        if (argv.pointers[i] != IntPtr.Zero)
                        {
                            Marshal.FreeHGlobal(argv.pointers[i]);  //释放以前使用 System.Runtime.InteropServices.Marshal.AllocHGlobal(System.IntPtr) 从进程的非托管内存中分配的内存。
                        }
                    }
    
                    if (argvPtr != IntPtr.Zero) { Marshal.FreeHGlobal(argvPtr);/* 释放以前使用 System.Runtime.InteropServices.Marshal.AllocHGlobal(System.IntPtr) 从进程的非托管内存中分配的内存。 */ }
                }
            }
    
            /// <summary>
            /// 从本地文件系统路径新建,其他参照上一条
            /// </summary>
            /// <param name="libvlc_instance"></param>
            /// <param name="path"></param>
            /// <returns></returns>
            public static IntPtr libvlc_media_new_path(IntPtr libvlc_instance, string path)
            {
                IntPtr pMrl = IntPtr.Zero;
                try
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(path);
                    pMrl = Marshal.AllocHGlobal(bytes.Length + 1);
                    Marshal.Copy(bytes, 0, pMrl, bytes.Length);
                    Marshal.WriteByte(pMrl, bytes.Length, 0);
                    return libvlc_media_new_path(libvlc_instance, pMrl);  // 从本地文件路径构建一个libvlc_media
                }
                finally
                {
                    if (pMrl != IntPtr.Zero) { Marshal.FreeHGlobal(pMrl);/* 释放以前使用 System.Runtime.InteropServices.Marshal.AllocHGlobal(System.IntPtr) 从进程的非托管内存中分配的内存。 */                }
                }
            }
    
            /// <summary>
            /// 使用一个给定的媒体资源路径来建立一个libvlc_media对象.参数psz_mrl为要读取的MRL(Media Resource Location).此函数返回新建的对象或NULL.
            /// </summary>
            /// <param name="libvlc_instance"></param>
            /// <param name="path"></param>
            /// <returns></returns>
            public static IntPtr libvlc_media_new_location(IntPtr libvlc_instance, string path)
            {
                IntPtr pMrl = IntPtr.Zero;
                try
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(path);
                    pMrl = Marshal.AllocHGlobal(bytes.Length + 1);
                    Marshal.Copy(bytes, 0, pMrl, bytes.Length);
                    Marshal.WriteByte(pMrl, bytes.Length, 0);
                    return libvlc_media_new_path(libvlc_instance, pMrl);  // 从本地文件路径构建一个libvlc_media
                }
                finally
                {
                    if (pMrl != IntPtr.Zero) { Marshal.FreeHGlobal(pMrl);/* 释放以前使用 System.Runtime.InteropServices.Marshal.AllocHGlobal(System.IntPtr) 从进程的非托管内存中分配的内存。 */                }
                }
            }
    
            // ----------------------------------------------------------------------------------------
            // 以下是libvlc.dll导出函数
    
            /// <summary>
            /// 创建一个libvlc实例,它是引用计数的 
            /// </summary>
            /// <param name="argc"></param>
            /// <param name="argv"></param>
            /// <returns></returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            private static extern IntPtr libvlc_new(int argc, IntPtr argv);
    
            /// <summary>
            /// 释放libvlc实例 
            /// </summary>
            /// <param name="libvlc_instance"></param>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_release(IntPtr libvlc_instance);
    
            /// <summary>
            /// 获取版本 
            /// </summary>
            /// <returns></returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern String libvlc_get_version();
    
            /// <summary>
            /// 从视频来源(例如Url)构建一个libvlc_meida 
            /// </summary>
            /// <param name="libvlc_instance"></param>
            /// <param name="path"></param>
            /// <returns></returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            private static extern IntPtr libvlc_media_new_location(IntPtr libvlc_instance, IntPtr path);
    
            /// <summary>
            /// 从本地文件路径构建一个libvlc_media 
            /// </summary>
            /// <param name="libvlc_instance"></param>
            /// <param name="path"></param>
            /// <returns></returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            private static extern IntPtr libvlc_media_new_path(IntPtr libvlc_instance, IntPtr path);
    
            /// <summary>
            /// 
            /// </summary>
            /// <param name="libvlc_media_inst"></param>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_media_release(IntPtr libvlc_media_inst);
    
            /// <summary>
            /// 创建libvlc_media_player(播放核心) 
            /// </summary>
            /// <param name="libvlc_instance"></param>
            /// <returns></returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern IntPtr libvlc_media_player_new(IntPtr libvlc_instance);
    
            /// <summary>
            /// 将视频(libvlc_media)绑定到播放器上 
            /// </summary>
            /// <param name="libvlc_media_player"></param>
            /// <param name="libvlc_media"></param>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_media_player_set_media(IntPtr libvlc_media_player, IntPtr libvlc_media);
    
            /// <summary>
            /// 设置图像输出的窗口 
            /// </summary>
            /// <param name="libvlc_mediaplayer"></param>
            /// <param name="drawable"></param>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_media_player_set_hwnd(IntPtr libvlc_mediaplayer, Int32 drawable);
    
            #region 播放控制
            /// <summary>
            /// 播放 
            /// </summary>
            /// <param name="libvlc_mediaplayer"></param>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_media_player_play(IntPtr libvlc_mediaplayer);
    
            /// <summary>
            /// 暂停 
            /// </summary>
            /// <param name="libvlc_mediaplayer"></param>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_media_player_pause(IntPtr libvlc_mediaplayer);
    
            /// <summary>
            /// 停止 
            /// </summary>
            /// <param name="libvlc_mediaplayer"></param>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_media_player_stop(IntPtr libvlc_mediaplayer);
            #endregion
    
            /// <summary>
            /// 释放播放文件 
            /// </summary>
            /// <param name="libvlc_mediaplayer"></param>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_media_player_release(IntPtr libvlc_mediaplayer);
    
            /// <summary>
            /// 解析视频资源的媒体信息(如时长等) 
            /// </summary>
            /// <param name="libvlc_media"></param>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_media_parse(IntPtr libvlc_media);
    
            /// <summary>
            /// 返回视频的时长(必须先调用libvlc_media_parse之后,该函数才会生效) 
            /// </summary>
            /// <param name="libvlc_media"></param>
            /// <returns></returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern Int64 libvlc_media_get_duration(IntPtr libvlc_media);
    
    
            #region 播放时间进度 
    
            /// <summary>
            /// 当前播放的时间进度 
            /// </summary>
            /// <param name="libvlc_mediaplayer"></param>
            /// <returns></returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern Int64 libvlc_media_player_get_time(IntPtr libvlc_mediaplayer);
    
            /// <summary>
            /// 设置播放位置(拖动) 
            /// </summary>
            /// <param name="libvlc_mediaplayer"></param>
            /// <param name="time"></param>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_media_player_set_time(IntPtr libvlc_mediaplayer, Int64 time);
    
            #endregion
    
            #region 音量
    
            /// <summary>
            /// 获取音量 
            /// </summary>
            /// <param name="libvlc_media_player"></param>
            /// <returns></returns>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern int libvlc_audio_get_volume(IntPtr libvlc_media_player);
    
            /// <summary>
            /// 设置音量
            /// </summary>
            /// <param name="libvlc_media_player"></param>
            /// <param name="volume"></param>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_audio_set_volume(IntPtr libvlc_media_player, int volume);
    
            #endregion
    
            /// <summary>
            /// 设置全屏
            /// </summary>
            /// <param name="libvlc_media_player"></param>
            /// <param name="isFullScreen"></param>
            [DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            [SuppressUnmanagedCodeSecurity]
            public static extern void libvlc_set_fullscreen(IntPtr libvlc_media_player, int isFullScreen);
    
            /// <summary>
            /// 获取播放状态。(Win10 不支持)
            /// </summary>
            /// <param name="libvlc_mediaplayer"></param>
            /// <returns></returns>
            //[DllImport("libvlc", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
            //[SuppressUnmanagedCodeSecurity]
            //public static extern Int64 libvlc_media_player_get_state(IntPtr libvlc_mediaplayer);
    
        }
    
        #endregion
    
    }

    第三步:写代码实现

    string pluginPath = Environment.CurrentDirectory + "\\plugins\\";  //插件目录
                player = new VlcPlayerBase(pluginPath);
                player.SetRenderWindow((int)pnlVideo.Handle);//panel
                player.LoadFile(videoName[0]);//视频文件路径

    设置音量:

    int volume = this.player.GetVolume();
    volume--;
    if (volume <0) volume = 0;
    this.player.SetVolume(volume);

    还有播放状态设置:

     this.player.Play();

    this.player.Pause();

    this.player.Stop();

    其他设置:

    int durationSecond = (int)this.player.Duration;
    int playTimeSecond = (int)this.player.GetPlayTime();

    this.player.SetPlayTime(this.tkbProgress.Value);

     

    展开全文
  • c# 使用VLC播放视频,监控视频 最近公司要做一个监控视频的播放页面,让我用VLC做一个,就再网上找资料,找了很多,大部给的代码都是可以的,但是要学会自己去拼装,好多都是要用积分下载,我也下载了几个,感觉都...

    c# 使用VLC播放视频,监控视频

    最近公司要做一个监控视频的播放页面,让我用VLC做一个,就再网上找资料,找了很多,大部给的代码都是可以的,但是要学会自己去拼装,好多都是要用积分下载,我也下载了几个,感觉都是可以直接播放的,然后自己再封装一下就可以了,唯一一个地方就是屏幕大小的问题,这个需要自己写,还有就是一个延迟问题,每次都是延迟五秒,不知道为什么…

    
    //----------------------------------------------------------------*/
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Runtime.InteropServices;
    using System.Runtime.ExceptionServices;
    using System.Security;
    using System.IO;
    using System.Threading;
    
    namespace VclPlayers
    {
        using libvlc_media_t = System.IntPtr;
        using libvlc_media_player_t = System.IntPtr;
        using libvlc_instance_t = System.IntPtr;
        public class VLCPlayer
        {
            #region 全局变量
            //数组转换为指针  
            internal struct PointerToArrayOfPointerHelper
            {
                [MarshalAs(UnmanagedType.ByValArray, SizeConst = 11)]
                public IntPtr[] pointers;
            }
           
            //vlc库启动参数配置  
            private static string pluginPath = System.Environment.CurrentDirectory + "\\plugins\\";
           // private static string pluginPath = "D:\\VLCTools\\plugins\\";
            private static string plugin_arg = "--plugin-path=" + pluginPath;
            //用于播放节目时,转录节目  
            //private static string program_arg = "--sout=#duplicate{dst=std{access=file,mux=ts,dst=d:/test.ts}}";  
           private static string[] arguments = { "-I", "dummy", "--ignore-config", "--video-title",  plugin_arg };//, program_arg };  
            //private static string[] arguments = { "--verbose=2", "--network-caching=300", "--no-snapshot-preview" ,plugin_arg};
    
            #region 结构体
            public struct libvlc_media_stats_t
            {
                /* Input */
                public int i_read_bytes;
                public float f_input_bitrate;
    
                /* Demux */
                public int i_demux_read_bytes;
                public float f_demux_bitrate;
                public int i_demux_corrupted;
                public int i_demux_discontinuity;
    
                /* Decoders */
                public int i_decoded_video;
                public int i_decoded_audio;
    
                /* Video Output */
                public int i_displayed_pictures;
                public int i_lost_pictures;
    
                /* Audio output */
                public int i_played_abuffers;
                public int i_lost_abuffers;
    
                /* Stream output */
                public int i_sent_packets;
                public int i_sent_bytes;
                public float f_send_bitrate;
            }
            #endregion
    
            #endregion
            #region 私有变量
            private libvlc_instance_t lit;
            private libvlc_media_player_t lmpt;
            #endregion
            #region 公有函数
            /// <summary>
            /// 播放网络视频流
            /// </summary>
            /// <param name="url">url地址</param>
            /// <param name="handle">显示控件句柄</param>
            /// <returns>true:播放成功;false:播放失败</returns>
            public bool playUrl(string url,IntPtr handle)
            {
                lit = Create_Media_Instance();
                lmpt = Create_MediaPlayer(lit, handle);
                //播放网络视频
                return NetWork_Media_Play(lit, lmpt, url);   
                //播放本地视频
               // return Local_Media_Play(lit, lmpt, url);
            }
            /// <summary>
            /// 播放本地视频
            /// </summary>
            /// <param name="path">视频路径</param>
            /// <param name="handle">显示控件句柄</param>
            /// <returns>true:播放成功;false:播放失败</returns>
            public bool playLocalVideo(string path, IntPtr handle)
            {
                lit = Create_Media_Instance();
                lmpt = Create_MediaPlayer(lit, handle);
                return Local_Media_Play(lit, lmpt, path);
            }
            /// <summary>
            /// 释放VLC资源
            /// </summary>
            /// <returns>true:释放;false:失败</returns>
            public bool release()
            {
                try
                {
                    MediaPlayer_Stop(lmpt);
                   // Release_Media_Instance(lit);
                    Release_MediaPlayer(lmpt);
                    return true;
                }
                catch(Exception ex)
                {
                    return false;
                }
            }
            /// <summary>
            /// 是否正在播放
            /// </summary>
            /// <returns></returns>
            public bool IsPlaying()
            {
                return MediaPlayer_IsPlaying(lmpt);
            }
            /// <summary>
            /// 停止播放
            /// </summary>
            public void Stop()
            {
                MediaPlayer_Stop(lmpt);
            }
            /// <summary>
            /// 获得视频时长
            /// </summary>
            /// <param name="url"></param>
            /// <returns></returns>
            public double Durations(string url) 
            {
                return Duration(lit,url);
            }
    
            /// <summary>
            /// 暂停播放
            /// </summary>
            public void Pause() 
            {
                MediaPlayer_Pause(lmpt);
            }
             /// <summary>
             /// 播放
             /// </summary>
            public void PlayU() 
            {
                Play(lmpt);
            }
            /// <summary>
            /// 设置播放时间
            /// </summary>
            /// <param name="seekTime"></param>
            public void SetTime(double seekTime) 
            {
                if (lmpt != IntPtr.Zero) 
                {
                    SafeNativeMethods.libvlc_media_player_set_time(lmpt,(Int64)seekTime*1000);
                }
            }
            public void Aspect(string aspects) 
            {
                if (lmpt != IntPtr.Zero)
                {
                    SafeNativeMethods.libvlc_video_set_aspect_ratio(lmpt,aspects.ToCharArray());
                }
            }
             /// <summary>
             /// 获得播放时间
             /// </summary>
             /// <returns></returns>
            public double GetTime() 
            {
                double seekTime = 0;
                if (lmpt != IntPtr.Zero) {
                  seekTime =  SafeNativeMethods.libvlc_media_player_get_time(lmpt);
                }
                return seekTime;
            }
            /// <summary>
            ///获取屏幕参数
            /// </summary>
            /// <returns></returns>
            public int GetFullscreen()
            {
                return SafeNativeMethods.libvlc_get_fullscreen(lmpt);
            }
            public bool SetFullscreen(int screen) 
            {
                return SetFullScreen(lmpt,screen);
            }
            /// <summary>
            /// 录制快照
            /// </summary>
            /// <param name="path"></param>
            /// <param name="name"></param>
            /// <returns></returns>
            public bool TakeSnapshots(string path,string name) 
            {
                return TakeSnapShot(lmpt,path,name);
            }
            #endregion
            #region 私有函数
            /// <summary>  
            /// 创建VLC播放资源索引  
            /// </summary>  
            /// <param name="arguments"></param>  
            /// <returns></returns>  
            private libvlc_instance_t Create_Media_Instance()
            {
                libvlc_instance_t libvlc_instance = IntPtr.Zero;
                IntPtr argvPtr = IntPtr.Zero;
    
                try
                {
                    if (arguments.Length == 0 ||
                        arguments == null)
                    {
                        return IntPtr.Zero;
                    }
    
                    //将string数组转换为指针  
                    argvPtr = StrToIntPtr(arguments);
                    if (argvPtr == null || argvPtr == IntPtr.Zero)
                    {
                        return IntPtr.Zero;
                    }
    
                    //设置启动参数  
                    libvlc_instance = SafeNativeMethods.libvlc_new(arguments.Length, argvPtr);
                    if (libvlc_instance == null || libvlc_instance == IntPtr.Zero)
                    {
                        return IntPtr.Zero;
                    }
    
                    return libvlc_instance;
                }
                catch
                {
                    return IntPtr.Zero;
                }
            }
    
            /// <summary>  
            /// 释放VLC播放资源索引  
            /// </summary>  
            /// <param name="libvlc_instance">VLC 全局变量</param>  
            private void Release_Media_Instance(libvlc_instance_t libvlc_instance)
            {
                try
                {
                    if (libvlc_instance != IntPtr.Zero ||
                        libvlc_instance != null)
                    {
                        SafeNativeMethods.libvlc_release(libvlc_instance);
                    }
    
                    libvlc_instance = IntPtr.Zero;
                }
                catch (Exception)
                {
                    libvlc_instance = IntPtr.Zero;
                }
            }
    
            /// <summary>  
            /// 创建VLC播放器  
            /// </summary>  
            /// <param name="libvlc_instance">VLC 全局变量</param>  
            /// <param name="handle">VLC MediaPlayer需要绑定显示的窗体句柄</param>  
            /// <returns></returns>  
            private  libvlc_media_player_t Create_MediaPlayer(libvlc_instance_t libvlc_instance, IntPtr handle)
            {
                libvlc_media_player_t libvlc_media_player = IntPtr.Zero;
    
                try
                {
                    if (libvlc_instance == IntPtr.Zero ||
                        libvlc_instance == null ||
                        handle == IntPtr.Zero ||
                        handle == null)
                    {
                        return IntPtr.Zero;
                    }
    
                    //创建播放器  
                    libvlc_media_player = SafeNativeMethods.libvlc_media_player_new(libvlc_instance);
                    if (libvlc_media_player == null || libvlc_media_player == IntPtr.Zero)
                    {
                        return IntPtr.Zero;
                    }
    
                    //设置播放窗口              
                    SafeNativeMethods.libvlc_media_player_set_hwnd(libvlc_media_player, (int)handle);
    
                    return libvlc_media_player;
                }
                catch
                {
                    SafeNativeMethods.libvlc_media_player_release(libvlc_media_player);
    
                    return IntPtr.Zero;
                }
            }
    
            /// <summary>  
            /// 释放媒体播放器  
            /// </summary>  
            /// <param name="libvlc_media_player">VLC MediaPlayer变量</param>  
            private void Release_MediaPlayer(libvlc_media_player_t libvlc_media_player)
            {
                try
                {
                    if (libvlc_media_player != IntPtr.Zero ||
                        libvlc_media_player != null)
                    {
                        if (SafeNativeMethods.libvlc_media_player_is_playing(libvlc_media_player))
                        {
                            SafeNativeMethods.libvlc_media_player_stop(libvlc_media_player);
                        }
    
                        SafeNativeMethods.libvlc_media_player_release(libvlc_media_player);
                    }
    
                    libvlc_media_player = IntPtr.Zero;
                }
                catch (Exception)
                {
                    libvlc_media_player = IntPtr.Zero;
                }
            }
    
            /// <summary>  
            /// 播放网络媒体  
            /// </summary>  
            /// <param name="libvlc_instance">VLC 全局变量</param>  
            /// <param name="libvlc_media_player">VLC MediaPlayer变量</param>  
            /// <param name="url">网络视频URL,支持http、rtp、udp等格式的URL播放</param>  
            /// <returns></returns>  
            private bool NetWork_Media_Play(libvlc_instance_t libvlc_instance, libvlc_media_player_t libvlc_media_player, string url)
            {
                IntPtr pMrl = IntPtr.Zero;
                libvlc_media_t libvlc_media = IntPtr.Zero;
    
                try
                {
                    if (url == null ||
                        libvlc_instance == IntPtr.Zero ||
                        libvlc_instance == null ||
                        libvlc_media_player == IntPtr.Zero ||
                        libvlc_media_player == null)
                    {
                        return false;
                    }
    
                    pMrl = StrToIntPtr(url);
                    if (pMrl == null || pMrl == IntPtr.Zero)
                    {
                        return false;
                    }
    
                    //播放网络文件  
                    libvlc_media = SafeNativeMethods.libvlc_media_new_location(libvlc_instance, pMrl);
    
                    if (libvlc_media == null || libvlc_media == IntPtr.Zero)
                    {
                        return false;
                    }
    
                    //将Media绑定到播放器上  
                    SafeNativeMethods.libvlc_media_player_set_media(libvlc_media_player, libvlc_media);
    
                    //释放libvlc_media资源  
                    SafeNativeMethods.libvlc_media_release(libvlc_media);
                    libvlc_media = IntPtr.Zero;
    
                    if (0 != SafeNativeMethods.libvlc_media_player_play(libvlc_media_player))
                    {
                        return false;
                    }
    
                    //休眠指定时间  
                    Thread.Sleep(500);
    
                    return true;
                }
                catch (Exception)
                {
                    //释放libvlc_media资源  
                    if (libvlc_media != IntPtr.Zero)
                    {
                        SafeNativeMethods.libvlc_media_release(libvlc_media);
                    }
                    libvlc_media = IntPtr.Zero;
    
                    return false;
                }
            }
            /// <summary>
            /// 获得视频时间
            /// </summary>
            /// <param name="libvlc_instance"></param>
            /// <param name="url"></param>
            /// <returns></returns>
            private double Duration(libvlc_instance_t libvlc_instance,string url) 
            {
                double duration_ = 0;
                libvlc_media_t libvlc_media = IntPtr.Zero;
                IntPtr pMrl = IntPtr.Zero;
                pMrl = StrToIntPtr(url);
                if (pMrl == null || pMrl == IntPtr.Zero)
                {
                    return duration_;
                }
                libvlc_media = SafeNativeMethods.libvlc_media_new_path(libvlc_instance, pMrl);
                SafeNativeMethods.libvlc_media_parse(libvlc_media);
                duration_ = SafeNativeMethods.libvlc_media_get_duration(libvlc_media);
                return duration_;
            }
    
            /// <summary>
            /// 播放本地视频
            /// </summary>
            /// <param name="libvlc_instance"></param>
            /// <param name="libvlc_media_player"></param>
            /// <param name="url"></param>
            /// <returns></returns>
            private bool Local_Media_Play(libvlc_instance_t libvlc_instance, libvlc_media_player_t libvlc_media_player, string url)
            {
                IntPtr pMrl = IntPtr.Zero;
                libvlc_media_t libvlc_media = IntPtr.Zero;
    
                try
                {
                    if (url == null ||
                        libvlc_instance == IntPtr.Zero ||
                        libvlc_instance == null ||
                        libvlc_media_player == IntPtr.Zero ||
                        libvlc_media_player == null)
                    {
                        return false;
                    }
    
                    pMrl = StrToIntPtr(url);
                    if (pMrl == null || pMrl == IntPtr.Zero)
                    {
                        return false;
                    }
    
                    //播放本地视频  
                    libvlc_media = SafeNativeMethods.libvlc_media_new_path(libvlc_instance, pMrl);
    
                    if (libvlc_media == null || libvlc_media == IntPtr.Zero)
                    {
                        return false;
                    }
    
                    //将Media绑定到播放器上  
                    SafeNativeMethods.libvlc_media_player_set_media(libvlc_media_player, libvlc_media);
    
                    //释放libvlc_media资源  
                    SafeNativeMethods.libvlc_media_release(libvlc_media);
                    libvlc_media = IntPtr.Zero;
    
                    if (0 != SafeNativeMethods.libvlc_media_player_play(libvlc_media_player))
                    {
                        return false;
                    }
    
                    //休眠指定时间  
                    Thread.Sleep(500);
    
                    return true;
                }
                catch (Exception)
                {
                    //释放libvlc_media资源  
                    if (libvlc_media != IntPtr.Zero)
                    {
                        SafeNativeMethods.libvlc_media_release(libvlc_media);
                    }
                    libvlc_media = IntPtr.Zero;
    
                    return false;
                }
            }
    
            /// <summary>  
            /// 暂停或恢复视频  
            /// </summary>  
            /// <param name="libvlc_media_player">VLC MediaPlayer变量</param>  
            /// <returns></returns>  
            private bool MediaPlayer_Pause(libvlc_media_player_t libvlc_media_player)
            {
                try
                {
                    if (libvlc_media_player == IntPtr.Zero ||
                        libvlc_media_player == null)
                    {
                        return false;
                    }
    
                    if (SafeNativeMethods.libvlc_media_player_can_pause(libvlc_media_player))
                    {
                        SafeNativeMethods.libvlc_media_player_pause(libvlc_media_player);
    
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                catch (Exception)
                {
                    return false;
                }
            }
    
            /// <summary>  
            /// 停止播放  
            /// </summary>  
            /// <param name="libvlc_media_player">VLC MediaPlayer变量</param>  
            /// <returns></returns>  
            private bool MediaPlayer_Stop(libvlc_media_player_t libvlc_media_player)
            {
                try
                {
                    if (libvlc_media_player == IntPtr.Zero ||
                        libvlc_media_player == null)
                    {
                        return false;
                    }
    
                    SafeNativeMethods.libvlc_media_player_stop(libvlc_media_player);
    
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
            /// <summary>  
            /// VLC MediaPlayer是否在播放  
            /// </summary>  
            /// <param name="libvlc_media_player">VLC MediaPlayer变量</param>  
            /// <returns></returns>  
            private bool MediaPlayer_IsPlaying(libvlc_media_player_t libvlc_media_player)
            {
                try
                {
                    if (libvlc_media_player == IntPtr.Zero ||
                        libvlc_media_player == null)
                    {
                        return false;
                    }
    
                    return SafeNativeMethods.libvlc_media_player_is_playing(libvlc_media_player);
                }
                catch (Exception)
                {
                    return false;
                }
            }
    
            /// <summary>  
            /// 录制快照  
            /// </summary>  
            /// <param name="libvlc_media_player">VLC MediaPlayer变量</param>  
            /// <param name="path">快照要存放的路径</param>  
            /// <param name="name">快照保存的文件名称</param>  
            /// <returns></returns>  
            private bool TakeSnapShot(libvlc_media_player_t libvlc_media_player, string path, string name)
            {
                try
                {
                    string snap_shot_path = null;
    
                    if (libvlc_media_player == IntPtr.Zero ||
                        libvlc_media_player == null)
                    {
                        return false;
                    }
    
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
    
                    snap_shot_path = path + "\\" + name;
    
                    if (0 == SafeNativeMethods.libvlc_video_take_snapshot(libvlc_media_player, 0, snap_shot_path.ToCharArray(), 0, 0))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                catch (Exception)
                {
                    return false;
                }
            }
    
            /// <summary>  
            /// 获取信息  
            /// </summary>  
            /// <param name="libvlc_media_player"></param>  
            /// <returns></returns>  
            private bool GetMedia(libvlc_media_player_t libvlc_media_player)
            {
                libvlc_media_t media = IntPtr.Zero;
    
                try
                {
                    if (libvlc_media_player == IntPtr.Zero ||
                        libvlc_media_player == null)
                    {
                        return false;
                    }
    
                    media = SafeNativeMethods.libvlc_media_player_get_media(libvlc_media_player);
                    if (media == IntPtr.Zero || media == null)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                catch (Exception)
                {
                    return false;
                }
            }
    
            /// <summary>  
            /// 获取已经显示的图片数  
            /// </summary>  
            /// <param name="libvlc_media_player"></param>  
            /// <returns></returns>  
            private int GetDisplayedPictures(libvlc_media_player_t libvlc_media_player)
            {
                libvlc_media_t media = IntPtr.Zero;
                libvlc_media_stats_t media_stats = new libvlc_media_stats_t();
                try
                {
                    if (libvlc_media_player == IntPtr.Zero ||
                        libvlc_media_player == null)
                    {
                        return 0;
                    }
    
                    media = SafeNativeMethods.libvlc_media_player_get_media(libvlc_media_player);
                    if (media == IntPtr.Zero || media == null)
                    {
                        return 0;
                    }
    
                    if (1 == SafeNativeMethods.libvlc_media_get_stats(media, ref media_stats))
                    {
                        return media_stats.i_displayed_pictures;
                    }
                    else
                    {
                        return 0;
                    }
                }
                catch (Exception)
                {
                    return 0;
                }
            }
    
            /// <summary>  
            /// 设置全屏  
            /// </summary>  
            /// <param name="libvlc_media_player"></param>  
            /// <param name="isFullScreen"></param>  
            private bool SetFullScreen(libvlc_media_player_t libvlc_media_player, int isFullScreen)
            {
                try
                {
                    if (libvlc_media_player == IntPtr.Zero ||
                        libvlc_media_player == null)
                    {
                        return false;
                    }
    
                    SafeNativeMethods.libvlc_set_fullscreen(libvlc_media_player, isFullScreen);
    
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
            /// <summary>
            /// 恢复播放
            /// </summary>
            private void Play(libvlc_media_player_t libvlc_mediaplayer) 
            {
                 if(libvlc_mediaplayer != IntPtr.Zero)
                 {
                     SafeNativeMethods.libvlc_media_player_play(libvlc_mediaplayer);
                 }
            }
            //将string []转换为IntPtr  
            private static IntPtr StrToIntPtr(string[] args)
            {
                try
                {
                    IntPtr ip_args = IntPtr.Zero;
    
                    PointerToArrayOfPointerHelper argv = new PointerToArrayOfPointerHelper();
                    argv.pointers = new IntPtr[11];
    
                    for (int i = 0; i < args.Length; i++)
                    {
                        argv.pointers[i] = Marshal.StringToHGlobalAnsi(args[i]);
                    }
    
                    int size = Marshal.SizeOf(typeof(PointerToArrayOfPointerHelper));
                    ip_args = Marshal.AllocHGlobal(size);
                    Marshal.StructureToPtr(argv, ip_args, false);
    
                    return ip_args;
                }
                catch (Exception)
                {
                    return IntPtr.Zero;
                }
            }
    
            //将string转换为IntPtr  
            private static IntPtr StrToIntPtr(string url)
            {
                try
                {
                    if (string.IsNullOrEmpty(url))
                    {
                        return IntPtr.Zero;
                    }
    
                    IntPtr pMrl = IntPtr.Zero;
                    byte[] bytes = Encoding.UTF8.GetBytes(url);
    
                    pMrl = Marshal.AllocHGlobal(bytes.Length + 1);
                    Marshal.Copy(bytes, 0, pMrl, bytes.Length);
                    Marshal.WriteByte(pMrl, bytes.Length, 0);
    
                    return pMrl;
                }
                catch (Exception)
                {
                    return IntPtr.Zero;
                }
            }
            #endregion
    
            #region 导入库函数
            [SuppressUnmanagedCodeSecurity]
            internal static class SafeNativeMethods
            {
                // 创建一个libvlc实例,它是引用计数的  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern libvlc_instance_t libvlc_new(int argc, IntPtr argv);
    
                // 释放libvlc实例  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern void libvlc_release(libvlc_instance_t libvlc_instance);
    
                //获取libvlc的版本  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern String libvlc_get_version();
    
                //从视频来源(例如http、rtsp)构建一个libvlc_meida  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern libvlc_media_t libvlc_media_new_location(libvlc_instance_t libvlc_instance, IntPtr path);
    
                //从本地文件路径构建一个libvlc_media  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern libvlc_media_t libvlc_media_new_path(libvlc_instance_t libvlc_instance, IntPtr path);
    
                //释放libvlc_media  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern void libvlc_media_release(libvlc_media_t libvlc_media_inst);
    
                // 创建一个空的播放器  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern libvlc_media_player_t libvlc_media_player_new(libvlc_instance_t libvlc_instance);
    
                //从libvlc_media构建播放器  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern libvlc_media_player_t libvlc_media_player_new_from_media(libvlc_media_t libvlc_media);
    
                //释放播放器资源  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern void libvlc_media_player_release(libvlc_media_player_t libvlc_mediaplayer);
    
                // 将视频(libvlc_media)绑定到播放器上  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern void libvlc_media_player_set_media(libvlc_media_player_t libvlc_media_player, libvlc_media_t libvlc_media);
    
                // 设置图像输出的窗口  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern void libvlc_media_player_set_hwnd(libvlc_media_player_t libvlc_mediaplayer, Int32 drawable);
    
                //播放器播放  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern int libvlc_media_player_play(libvlc_media_player_t libvlc_mediaplayer);
    
                //播放器暂停  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern void libvlc_media_player_pause(libvlc_media_player_t libvlc_mediaplayer);
    
                //播放器停止  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern void libvlc_media_player_stop(libvlc_media_player_t libvlc_mediaplayer);
    
                // 解析视频资源的媒体信息(如时长等)  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern void libvlc_media_parse(libvlc_media_t libvlc_media);
    
                // 返回视频的时长(必须先调用libvlc_media_parse之后,该函数才会生效)  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern Int64 libvlc_media_get_duration(libvlc_media_t libvlc_media);
    
                // 当前播放时间  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern Int64 libvlc_media_player_get_time(libvlc_media_player_t libvlc_mediaplayer);
    
                // 设置播放时间  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern void libvlc_media_player_set_time(libvlc_media_player_t libvlc_mediaplayer, Int64 time);
    
                // 获取音量  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern int libvlc_audio_get_volume(libvlc_media_player_t libvlc_media_player);
    
                //设置音量  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern void libvlc_audio_set_volume(libvlc_media_player_t libvlc_media_player, int volume);
    
                // 设置全屏  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern void libvlc_set_fullscreen(libvlc_media_player_t libvlc_media_player, int isFullScreen);
    
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern int libvlc_get_fullscreen(libvlc_media_player_t libvlc_media_player);
    
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern void libvlc_toggle_fullscreen(libvlc_media_player_t libvlc_media_player);
    
                //判断播放时是否在播放  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern bool libvlc_media_player_is_playing(libvlc_media_player_t libvlc_media_player);
    
                //判断播放时是否能够Seek  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern bool libvlc_media_player_is_seekable(libvlc_media_player_t libvlc_media_player);
    
                //判断播放时是否能够Pause  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern bool libvlc_media_player_can_pause(libvlc_media_player_t libvlc_media_player);
    
                //判断播放器是否可以播放  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern int libvlc_media_player_will_play(libvlc_media_player_t libvlc_media_player);
    
                //进行快照  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern int libvlc_video_take_snapshot(libvlc_media_player_t libvlc_media_player, int num, char[] filepath, int i_width, int i_height);
    
                //获取Media信息  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern libvlc_media_t libvlc_media_player_get_media(libvlc_media_player_t libvlc_media_player);
    
                //获取媒体信息  
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern int libvlc_media_get_stats(libvlc_media_t libvlc_media, ref libvlc_media_stats_t lib_vlc_media_stats);
                [DllImport(@"libvlc.DLL", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
                internal static extern void libvlc_video_set_aspect_ratio(libvlc_media_player_t libvlc_media_player,char[] aspect);
            }
            #endregion
        }  
    }
    
    

    需要的这个可以直接复制,然后可以写一个测试类,这里我是用WINFORM页面测试的。可以自己去测试。
    比如要播放网络流视频 vlcplayer() vlc = new vlcplayer();vlc.playUrl(“路劲”,this.panel.hand());vlc.Aspect(“4:3”);//这个是设置屏幕比的。

     /// <summary>
            /// 根据屏幕自适应
            /// </summary>
            /// <param name="tags">屏幕占比</param>
            private void FullScreenChange(string tags) 
            {
                Action action = () => {
                    vlc2.Aspect(tags);
                };
                action.Invoke();
            }
    

    如果要拖动窗口,可以这样。其他的方法我都打注释,应该还是很好理解的。 好了 留给自己以后忘记了学习,还有这个延迟怎么搞… 最后 还是要下载一个VLC播放器,安装好,找到路径,把plugins文件夹,libvlc.dll,libvlccore.dll 复制一份到DEBUG文件下

    展开全文
  • c# VLC 播放视频

    2020-07-10 23:30:14
    一个用C# 集成vlc库 做的视频播放器,简单实用,可运行。
  • C#VLC视频播放器组件

    2020-06-17 13:51:30
    这里我把VLC视频调用组件给弄成了一个可以调用的功能窗体,只需要调用里面一个参数就能实现播放视频,实例里面有如何将此视频播放器嵌入到另一个窗体的代码,代码里面也有详细备注功能用途,外观本人也没有太多时间...
  • C# VLC视频直播 rtsp

    2020-07-10 10:31:49
    VLC开发包,直接直播视频播放,推流的地址,直接进行rtmp,rtsp,hls,http等在线直播。
  • c# vlc播放 h264数据

    2018-02-01 07:26:21
    (https://img-ask.csdn.net/upload/201606/27/1467012976_407856.jpg) ,在vlc播放器中可以通过串流 udp://@:8080 以及设置去复用h264 播放,现在想在c#中解码这种实时码流,带关键帧以及sps pps的码流, 如果用vlc ...
  • c# 使用VLC 播放器时,事件被阻塞,无法直接使用鼠标事件,甚是不便。 解决方法如下:  _myVlcControl.MediaPlayer.BeginInit();  _myVlcControl.MediaPlayer.CreateControl();  _myVlcControl.MediaPlayer....
    c# 使用VLC 播放器时,事件被阻塞,无法直接使用鼠标事件,甚是不便。

    解决方法:

    既然Winform的视频控件事件被阻塞,那我们就在Winform的控件上面添加一个透明的可接受鼠标事件的控件即可。


                _myVlcControl.MediaPlayer.BeginInit();
                _myVlcControl.MediaPlayer.CreateControl(); // 在播放器顶层添加一个可接受鼠标事件的透明控件
                _myVlcControl.MediaPlayer.VlcLibDirectoryNeeded += OnVlcControlNeedsLibDirectory;
                _myVlcControl.MediaPlayer.TimeChanged += MediaPlayer_TimeChanged;
                _myVlcControl.MediaPlayer.EndInit();


    -------------------------------------------------------------------------------------------------


       _myVlcControl.MediaPlayer.Play(new Uri(StrPath));

                        System.Windows.Forms.Panel panelDoubleClick = new System.Windows.Forms.Panel();
                        panelDoubleClick.Dock = DockStyle.Fill;
                        panelDoubleClick.BackColor = System.Drawing.Color.Transparent; // 背景透明
                        panelDoubleClick.MouseClick += panelDoubleClick_MouseClick;


                        _myVlcControl.MediaPlayer.Controls.Clear();
                        _myVlcControl.MediaPlayer.Controls.Add(panelDoubleClick);
                        panelDoubleClick.BringToFront(); // 置顶

        void panelClick_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
            {

                PausePlay();

    }











    展开全文
  • 使用的是VLC 3.0 string[] mediaOptions = new string[] { "input-repeat=x" }; x为循环次数 vlcControl1.SetMedia(new FileInfo("xxx.mp4"), mediaOptions);//本地视频 说是VLC 2.2.8说是设置为-1 可以一直循环...
  • VLCPlayer视频播放器。 支持本地播放,支持网络URL。支持全屏,截图。 基于VLCPlayer。 附带基本代码。 下载地址:http://pan.baidu.com/s/1nvjNvID 转载于:https://www.cnblogs.com/zhangwc/p/5881610.html...
  • C#调用2个以上的VLC Player后,要Dispose都会无回应,要如何才能正确地释放资源 ![图片说明](https://img-ask.csdn.net/upload/201907/18/1563433451_959701.png)
  • c# vlc播放h264码流问题

    2016-06-24 08:18:27
    我想要实现 c#下 调用vlc播放 h264裸流,如图 ![图片说明](https://img-ask.csdn.net/upload/201606/24/1466755829_788272.jpg) 这个裸流在vlc播放器中可以播放,做串流udp://@:8080以及h264去复用即可播放 我在c# ...
  • c#调用vlc 实现播放器

    2020-07-01 15:20:52
    c#调用vlc 实现播放器,可以播放本地视频,也可以播放网络链接。参考数位大佬的代码集结而成。运行环境为vs2012+.net4.0
  • C#版的VLC简单播放器

    2020-07-09 23:30:58
    基于VLCC#播放器源码 实现的功能: 1:打开播放的音视频文件((1)菜单栏“文件”->“打开”,(2)工具栏(下面)“打开”(3)播放器右键->打开) 2:暂停,继续播放,停止音视频文件 3:进度条和右下角文本框显示播放...
  • C#下的VLC插件

    2020-06-03 23:32:46
    C#使用VLC插件,2.1.112版本,支持winform和wpf,包含示例程序
  • C# 使用VLC播放本地视频的时候,播放久了出现这个问题 ![图片说明](https://img-ask.csdn.net/upload/201605/19/1463648116_514982.png)
  • 使用VLC 插件播放RTSP 视频流,可以实现多个视频流播放
  • 调用vlc的dll,通过VLC的API来获取视频文件的时间长度信息,完整源代码,vs2008工程,可编译和...需要注意的是使用的VLC 32位版本,C#工程必须设置生成32位软件。如果想用64位的,那么请使用64位的VLC版本的dll文件。
  • vlcC#的使用方法

    2016-04-19 10:48:16
    vlcc#中的使用,本人新手只会怎么使用,文笔也不好见谅。
1 2 3 4 5 ... 20
收藏数 2,644
精华内容 1,057