C # Windows form application play small video

Source: Internet
Author: User
<span id="Label3"></p><span style="font-size:14px;"><span style="font-size:14px;">1. Download Direcly-show lib DLL<br>Click to open link<br><br>2. DxPlay.cs (can be found in the download example):<br><br><br></span></span><pre code_snippet_id="1991460" snippet_file_name="blog_20161117_1_5298852" name="code" class="csharp"> public class dxplay:idisposable {enum graphstate {Stopped, Paused, Running, Exiting} #region Member variables//File name we are playing private str ing m_sfilename; Graph builder Interfaces Private IFILTERGRAPH2 m_filtergraph; Private IMediaControl m_mediactrl; Private Imediaevent m_mediaevent; Used to grab current snapshots Isamplegrabber m_sampgrabber = null; Grab Once. Used to create bitmap private int m_videowidth; private int m_videoheight; private int m_stride; private int m_imagesize; In bytes//event used by Media event thread private ManualResetEvent m_mre; Current state of the graph (can change async) volatile private graphstate m_state = graphstate.stopped; #if DEBUG "Connect to remote graph" from GraphEdit dsrotentry m_dsrot; #endif #endregion//Release Everything. public void Dispose () {closeinterfaces (); } ~dxplay () {closeinterfaces (); }//event that was called when a clip finishs playing public Event dxplayevent stopplay; public delegate void Dxplayevent (Object sender); Play an AVI file into a window. Allow for Snapshots. (control to Show-video in, Avi file-to-play public dxplay (control hwin, string FileName) {try {int hr; IntPtr hevent; Save off the file name M_sfilename = FileName; Set up the graph setupgraph (hwin, FileName); Get the event handle the graph would use a signal//when events occur hr = M_mediaevent. Geteventhandle (out hevent); Dserror.throwexceptionforhr (hr); WraP The graph event with a manualresetevent M_mre = new ManualResetEvent (false); #if using_net11 M_mre. Handle = hevent; #else m_mre. Safewaithandle = new Microsoft.Win32.SafeHandles.SafeWaitHandle (hevent, true); #endif//Create a new thread To wait for events Thread t = new Thread (the new ThreadStart (this). eventwait)); T.name = "Media Event Thread"; T.start (); } catch {Dispose (); Throw }}//Wait for events to Happen. This approach uses waiting in an event Handle. The nice thing about doing it's this a-to-do aren ' t in the Windows message//loop, and don ' t has to Worr Y about re-entrency or taking too long. Plus, being//a class As we are, we don't have access to the message loop. alternately, you can receive your events as Windows Messages. See//Imediaeventex.setnotifywindow. private void eventwait () {//returned when GetEvent was called but There is no events const int e_abort = unchecked ((int) 0x80004004); int hr; INTPTR p1, p2; EventCode ec; Do {//Wait for an event m_mre. WaitOne ( -1, true); Avoid contention for M_state lock (this) {//If We is not shutting D own if (m_state! = Graphstate.exiting) {//Read the event For (hr = m_mediaevent.getevent (out-ec, out-p1, out p2, 0); HR >= 0; hr = m_mediaevent.getevent (out-ec, out-p1, out p2, 0)) { Write the event name to the debug window Debug.WriteLine (ec. ToString ()); If the clip is finished playing if (ec = = Eventcode.complete) { Call Stop () to set state stop (); Throw event If (stopplay! = Null) { Stopplay (this); }}/Release any resources the message allocated hr = M_mediaevent.freeeventparams (ec, p1, p2); Dserror.throwexceptionforhr (hr); }//If the error is exited the loop wasn ' t due to running out of events I F (hr! = e_abort) {dserror.throwexceptionforhr (hr); }} Else {//We are Shutt ing down break; }}} while (true); }//Return the currently playing file name public string FileName {get { Return m_sfilename; }}//start playing public void start () {//If we aren ' t already playing (or shut Ting Down) if (m_state = = Graphstate.stopped | | m_state = = Graphstate.paused) {int h r = M_mediactrl.run (); Dserror.throwexceptionforhr (hr); M_state = graphstate.running; }}//Pause the Capture Graph. public void Pause () {//if We are playing if (m_state = = Graphstate.running) { int hr = M_mediactrl.pause (); Dserror.throwexceptionforhr (hr); M_state = graphstate.paused; }}//Pause the Capture Graph. public void Stop () {//Can only stop when playing or paused if (m_state = = Graphstate.runnin G | | M_state = = Graphstate.paused) {int hr = M_mediactrl.stop (); Dserror.throwexceptionforhr (hr); M_state = graphstate.stopped; }}//Reset the clip back to the beginning public void Rewind () {int hr; Imediaposition imp = m_filtergraph as imediaposition; hr = Imp.put_currentposition (0); }//Grab a snapshot of the most recent image Played. Returns A Pointer to the raw pixel Data. Caller must release this memory With//marshal.freecotaskmem if it is no longer needed. Public IntPtr SnapShot () {int hr; IntPtr IP = intptr.zero; int ibuffsize = 0; Read the buffer size hr = M_sampgrabber.getcurrentbuffer (ref ibuffsize, ip); Dserror.throwexceptionforhr (hr); Debug.Assert (ibuffsize = = m_imagesize, "unexpected buffer size"); Allocate the buffer and read it IP = marshal.alloccotaskmem (ibuffsize); hr = M_sampgrabber.getcurrentbuffer (ref ibuffsize, ip); Dserror.throwexceptionforhr (hr); Return ip; }//Convert a point to the raw pixel data to A. NET bitmap public bitmap iptobmp (IntPtr Ip) { We know the Bits per Pixel is a (3 bytes) because we forced it//to was with Sampgrabber.setmediatype () int ibufsize = m_videowidth * M_videoheight * 3; return new Bitmap (m_videowidth, m_videoheight,-m_stride, Pix elformat.format24bpprgb, (IntPtr) (ip. ToInt32 () + ibufsize- m_stride)); }//Build the capture graph for Grabber and Renderer.</summary>//(Control to show video in, Filenam E to Play) private void Setupgraph (Control hwin, string FileName) {int hr; Get the Graphbuilder object m_filtergraph = new Filtergraph () as IFilterGraph2; Get a ICaptureGraphBuilder2 to help build the graph ICaptureGraphBuilder2 icgb2 = new CaptureGraphBuilder2 () As ICaptureGraphBuilder2; Try {//Link the ICaptureGraphBuilder2 to the IFILTERGRAPH2 hr = icgb2. Setfiltergraph (m_filtergraph); Dserror.throwexceptionforhr (hr); #if DEBUG//allows you-to-view the graph with GraphEdit File/connect M_dsrot = new Dsrotentry (m_filtergraph), #endif//Add the filters necessary to render the File. This function would//work with a number of difFerent file Types. Ibasefilter Sourcefilter = null; hr = M_filtergraph.addsourcefilter (filename, filename, out sourcefilter); Dserror.throwexceptionforhr (hr); Get the Samplegrabber interface m_sampgrabber = (isamplegrabber) new Samplegrabber (); Ibasefilter Basegrabflt = (ibasefilter) m_sampgrabber; Configure the Sample Grabber configuresamplegrabber (m_sampgrabber); Add it to the filter hr = M_filtergraph.addfilter (basegrabflt, "ds.net Grabber"); Dserror.throwexceptionforhr (hr); Connect The pieces together, use the default renderer hr = icgb2. Renderstream (null, null, sourcefilter, basegrabflt, null); Dserror.throwexceptionforhr (hr); Now and the graph is built, read the dimensions of the bitmaps we'll be getting savesizeinfo (m_sampgrab ber); Configure the Video Window ivideowindow Videowindow = m_filtergraph as ivideowindow; Configurevideowindow (videowindow, hwin); Grab some other interfaces m_mediaevent = M_filtergraph as imediaevent; M_mediactrl = M_filtergraph as imediacontrol; } finally {if (icgb2! = Null) {marshal.releasecom Object (icgb2); ICGB2 = null; }} #if DEBUG//Double Check to make sure we aren ' t releasing Something//important. Gc. Collect (); Gc. WaitForPendingFinalizers (); #endif}//Configure The video window private void Configurevideowindow (I Videowindow videowindow, Control hwin) {int hr; Set the output Window hr = Videowindow.put_owner (hwin.handle); Dserror.throwexCeptionforhr (hr); Set the window style hr = Videowindow.put_windowstyle ((windowstyle.child | Windowstyle.clipchildren | windowstyle.clipsiblings)); Dserror.throwexceptionforhr (hr); Make the window visible hr = videowindow.put_visible (oabool.true); Dserror.throwexceptionforhr (hr); Position the playing location Rectangle rc = hwin.clientrectangle; hr = videowindow.setwindowposition (0, 0, rc. right, rc. Bottom); Dserror.throwexceptionforhr (hr); }//Set the options on the sample grabber private void Configuresamplegrabber (isamplegrabber Sampgrabber) {ammediatype media; int hr; Set the media type to video/rbg24 media = new Ammediatype (); Media.majortype = mediatype.video; Media.subtype = mediasubtype.rgb24; Media.formattype = formattype.videoinfo; hr = SampGrabber.setmediatype (media); Dserror.throwexceptionforhr (hr); Dsutils.freeammediatype (media); Media = null; Configure the Samplegrabber hr = Sampgrabber.setbuffersamples (true); Dserror.throwexceptionforhr (hr); }//Save the size parameters for use in SnapShot private void Savesizeinfo (isamplegrabber Sampgrabber) {int hr; Get the media type from the samplegrabber ammediatype media = new Ammediatype (); hr = Sampgrabber.getconnectedmediatype (media); Dserror.throwexceptionforhr (hr); Try {if (media.formattype! = Formattype.videoinfo) | | (media.formatptr = = Intptr.zero)) {throw new NotSupportedException ("Unknown Grabber Media Format"); }//Get the struct Videoinfoheader videoinfoheader = new Videoinfoheader (); Marshal.PtrToStructure (media.formatptr, videoinfoheader); Grab the size info m_videowidth = videoInfoHeader.BmiHeader.Width; M_videoheight = videoInfoHeader.BmiHeader.Height; M_stride = videoinfoheader.bmiheader.imagesize/m_videoheight; M_imagesize = videoInfoHeader.BmiHeader.ImageSize; } finally {dsutils.freeammediatype (media); Media = null; }}//Shut down capture private void closeinterfaces () {int hr; Lock (this) {if (m_state! = Graphstate.exiting) {m_state = G raphstate.exiting; Release the thread (if the thread was started) if (m_mre! = null) { M_mre. Set (); }} If (m_mediactrl! = NuLl) {//Stop the graph hr = M_mediactrl.stop (); M_mediactrl = null; } If (m_sampgrabber! = Null) {marshal.releasecomobject (m_sampgrabber); M_sampgrabber = null; } #if DEBUG If (m_dsrot! = Null) {m_dsrot.dispose (); } #endif If (m_filtergraph! = Null) {marshal.releasecomobject (m_filtergra ph); M_filtergraph = null; }} GC. Collect (); } }</pre><br><br><br><br>3. Load the player into the specified panel, This example needs to be looped, so the auto start () in Stopplay<br><br><br><pre code_snippet_id="1991460" snippet_file_name="blog_20161117_2_6825588" name="code" class="csharp">Private Dxplay m_play; private void Loadvideointopanel () {try {var pathbase = path.getdirectoryname (application.executablepath); var path = Path.Combine (pathbase, bgvideo); Open the file, provide a handle to play it in m_play = new Dxplay (_videobackground, path); M_play. Start (); Let us know if the file is finished playing m_play. Stopplay + = sender + {//Rewind clip to Beginning-to-allow dxplay.start-to-work Aga In. M_play. Rewind (); M_play. Start (); }; } catch (Exception Ex) {_log. Error ("Video Playing error ==>" + ex.) Message + "\ r \ n" + Ex. StackTrace); } }</pre><br><br><br><br><p><p> C # Windows form application play a small video </p> </p></span>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.