• JMF视频音频通信( 图+源码 )


    转自:  http://mzhx-com.iteye.com/blog/1098698

    最近由于做山寨QQ视频聊天的需要,做了一个视频通信窗口组件。现在分享一下供大家学习……

    原创文章,转载请标明出处!谢谢!

    工程文件下载地址:http://download.csdn.net/source/3378150

    本文地址: http://mzhx-com.iteye.com/blog/1098698

      效果图如下:

    三个类 源代码如下:

    Java代码 复制代码 收藏代码
    1. package vidioPlay;  
    2.  
    3. import java.awt.Dimension;  
    4. import java.io.IOException;  
    5. import java.net.InetAddress;  
    6. import java.util.Vector;  
    7.  
    8. import javax.media.CaptureDeviceInfo;  
    9. import javax.media.Codec;  
    10. import javax.media.Control;  
    11. import javax.media.Controller;  
    12. import javax.media.ControllerClosedEvent;  
    13. import javax.media.ControllerEvent;  
    14. import javax.media.ControllerListener;  
    15. import javax.media.Format;  
    16. import javax.media.IncompatibleSourceException;
    17. import javax.media.Manager;  
    18. import javax.media.MediaLocator;  
    19. import javax.media.NoProcessorException;  
    20. import javax.media.Owned;  
    21. import javax.media.Player;  
    22. import javax.media.Processor;  
    23. import javax.media.cdm.CaptureDeviceManager;  
    24. import javax.media.control.QualityControl;  
    25. import javax.media.control.TrackControl;  
    26. import javax.media.format.AudioFormat;  
    27. import javax.media.format.VideoFormat;  
    28. import javax.media.protocol.ContentDescriptor;  
    29. import javax.media.protocol.DataSource;  
    30. import javax.media.protocol.PushBufferDataSource;  
    31. import javax.media.protocol.PushBufferStream;  
    32. import javax.media.protocol.SourceCloneable;  
    33. import javax.media.rtp.RTPManager;  
    34. import javax.media.rtp.SendStream;  
    35. import javax.media.rtp.SessionAddress;  
    36. import javax.media.rtp.rtcp.SourceDescription;  
    37. import javax.swing.JFrame;  
    38.  
    39. publicclass MediaTransmit {  
    40.  
    41.     private String ipAddress;  
    42.     privateint portBase;  
    43.     private MediaLocator audioLocator = null, vedioLocator = null;  
    44.     private Processor audioProcessor = null;  
    45.     private Processor videoProcessor = null;  
    46.     private DataSource audioDataLocal = null, videoDataLocal = null;  
    47.     private DataSource audioDataOutput = null, videoDataOutput = null;  
    48.     private RTPManager rtpMgrs[];  
    49.     private DataSource mediaData = null;  
    50.     private DataSource dataLocalClone = null;  
    51.  
    52.     private PlayPane playFrame;  
    53.  
    54.     public MediaTransmit(String ipAddress, String pb) {  
    55.         this.ipAddress = ipAddress;  
    56.         Integer integer = Integer.valueOf(pb);  
    57.         if (integer != null) {  
    58.             this.portBase = integer.intValue();  
    59.         }  
    60.         // /////////////////////////////////////////////  
    61.         playFrame = new PlayPane();  
    62.         JFrame jf = new JFrame("视频实例");  
    63.  
    64.         jf.add(playFrame);  
    65.         jf.pack();  
    66.         jf.setLocationRelativeTo(null);  
    67.         jf.setDefaultCloseOperation(3);  
    68.         jf.setVisible(true);  
    69.         // ////////////////////////////////////////////  
    70.         Vector<CaptureDeviceInfo> video = CaptureDeviceManager  
    71.                 .getDeviceList(new VideoFormat(null));  
    72.         Vector<CaptureDeviceInfo> audio = CaptureDeviceManager  
    73.                 .getDeviceList(new AudioFormat(AudioFormat.LINEAR, 44100, 16, 2));  
    74.         // MediaLocator mediaLocator = new  
    75.         // MediaLocator("file:/C:/纯音乐 - 忧伤还是快乐.mp3");  
    76.         if (audio != null && audio.size() > 0) {  
    77.             audioLocator = ((CaptureDeviceInfo) audio.get(0)).getLocator();  
    78.             if ((audioProcessor = createProcessor(audioLocator)) != null) {  
    79.                 audioDataLocal = mediaData;  
    80.                 audioDataOutput = audioProcessor.getDataOutput();  
    81.             }  
    82.         } else {  
    83.             System.out.println("******错误:没有检测到您的音频采集设备!!!");  
    84.         }  
    85.         // /////////////////////////////////////////////////////////  
    86.         if (video != null && video.size() > 0) {  
    87.             vedioLocator = ((CaptureDeviceInfo) video.get(0)).getLocator();  
    88.             if ((videoProcessor = createProcessor(vedioLocator)) != null) {  
    89.                 videoDataLocal = mediaData;  
    90.                 videoDataOutput = videoProcessor.getDataOutput();  
    91.             }  
    92.         } else {  
    93.             System.out.println("******错误:没有检测到您的视频设备!!!");  
    94.         }  
    95.         // /////////////////////////////////////////////////////////  
    96.         final DataSource[] dataSources = new DataSource[2];  
    97.         dataSources[0] = audioDataLocal;  
    98.         dataSources[1] = videoDataLocal;  
    99.         try {  
    100.             DataSource dsLocal = Manager.createMergingDataSource(dataSources);  
    101.             playFrame.localPlay(dsLocal);  
    102.         } catch (IncompatibleSourceException e) {  
    103.             e.printStackTrace();  
    104.             return;  
    105.         }  
    106.         // ////////////////////////////////////////////////远程传输  
    107.         dataSources[1] = audioDataOutput;  
    108.         dataSources[0] = videoDataOutput;  
    109.  
    110.         try {  
    111. DataSource dsoutput = Manager.createMergingDataSource(dataSources);
    112.             createTransmitter(dsoutput);  
    113.         } catch (IncompatibleSourceException e) {  
    114.             e.printStackTrace();  
    115.             return;  
    116.         }  
    117.         audioProcessor.start();  
    118.         videoProcessor.start();  
    119.     }  
    120.  
    121.     private Processor createProcessor(MediaLocator locator) {  
    122.         Processor processor = null;  
    123.         if (locator == null)  
    124.             returnnull;  
    125.         // 通过设备定位器得到数据源,  
    126.         try {  
    127.             mediaData = Manager.createDataSource(locator);  
    128.             // 创建可克隆数据源  
    129.             mediaData = Manager.createCloneableDataSource(mediaData);  
    130.             // 克隆数据源,用于传输到远程  
    131.             dataLocalClone = ((SourceCloneable) mediaData).createClone();  
    132.         } catch (Exception e) {  
    133.             e.printStackTrace();  
    134.             returnnull;  
    135.         }  
    136.         try {  
    137.             processor = javax.media.Manager.createProcessor(dataLocalClone);  
    138.  
    139.         } catch (NoProcessorException npe) {  
    140.             npe.printStackTrace();  
    141.             returnnull;  
    142.         } catch (IOException ioe) {  
    143.             returnnull;  
    144.         }  
    145.         boolean result = waitForState(processor, Processor.Configured);  
    146.         if (result == false)  
    147.             returnnull;  
    148.  
    149.         TrackControl[] tracks = processor.getTrackControls();  
    150.         if (tracks == null || tracks.length < 1)  
    151.             returnnull;  
    152.         ContentDescriptor cd = new ContentDescriptor(ContentDescriptor.RAW_RTP);  
    153.         processor.setContentDescriptor(cd);  
    154.         Format supportedFormats[];  
    155.         Format chosen;  
    156.         boolean atLeastOneTrack = false;  
    157.         for (int i = 0; i < tracks.length; i++) {  
    158.             if (tracks[i].isEnabled()) {  
    159.                 supportedFormats = tracks[i].getSupportedFormats();  
    160.                 if (supportedFormats.length > 0) {  
    161.                     if (supportedFormats[0] instanceof VideoFormat) {  
    162.                         chosen = checkForVideoSizes(tracks[i].getFormat(),  
    163.                                 supportedFormats[0]);  
    164.                     } else 
    165.                         chosen = supportedFormats[0];  
    166.                     tracks[i].setFormat(chosen);  
    167.                     System.err  
    168.                             .println("Track " + i + " is set to transmit as:");  
    169.                     System.err.println("  " + chosen);  
    170.                     atLeastOneTrack = true;  
    171.                 } else 
    172.                     tracks[i].setEnabled(false);  
    173.             } else 
    174.                 tracks[i].setEnabled(false);  
    175.         }  
    176.  
    177.         if (!atLeastOneTrack)  
    178.             returnnull;  
    179.         result = waitForState(processor, Controller.Realized);  
    180.         if (result == false)  
    181.             returnnull;  
    182.         setJPEGQuality(processor, 0.5f);  
    183.  
    184.         return processor;  
    185.     }  
    186.  
    187.     private String createTransmitter(DataSource dataOutput) {  
    188.         PushBufferDataSource pbds = (PushBufferDataSource) dataOutput;  
    189.         PushBufferStream pbss[] = pbds.getStreams();  
    190.         System.out.println("pbss.length:" + pbss.length);  
    191.         rtpMgrs = new RTPManager[pbss.length];  
    192.         SendStream sendStream;  
    193.         int port;  
    194.         // SourceDescription srcDesList[];  
    195.  
    196.         for (int i = 0; i < pbss.length; i++) {  
    197.             try {  
    198.                 rtpMgrs[i] = RTPManager.newInstance();  
    199.  
    200.                 port = portBase + 2 * i;  
    201.                 SessionAddress localAddr = new SessionAddress(  
    202.                         InetAddress.getLocalHost(), port);  
    203.                 SessionAddress destAddr = new SessionAddress(  
    204.                         InetAddress.getByName(ipAddress), port);  
    205.                 rtpMgrs[i].initialize(localAddr);  
    206.                 rtpMgrs[i].addTarget(destAddr);  
    207.                 System.out.println("Created RTP session: " 
    208.                         + InetAddress.getLocalHost() + " " + port);  
    209.                 sendStream = rtpMgrs[i].createSendStream(dataOutput, i);  
    210.                 sendStream.start();  
    211.             } catch (Exception e) {  
    212.                 e.printStackTrace();  
    213.                 return e.getMessage();  
    214.             }  
    215.         }  
    216.  
    217.         returnnull;  
    218.     }  
    219.     Format checkForVideoSizes(Format original, Format supported) {  
    220.  
    221.         int width, height;  
    222.         Dimension size = ((VideoFormat) original).getSize();  
    223.         Format jpegFmt = new Format(VideoFormat.JPEG_RTP);  
    224.         Format h263Fmt = new Format(VideoFormat.H263_RTP);  
    225.  
    226.         if (supported.matches(jpegFmt)) {  
    227.             width = (size.width % 8 == 0 ? size.width  
    228.                     : (int) (size.width / 8) * 8);  
    229.             height = (size.height % 8 == 0 ? size.height  
    230.                     : (int) (size.height / 8) * 8);  
    231.         } elseif (supported.matches(h263Fmt)) {  
    232.             if (size.width < 128) {  
    233.                 width = 128;  
    234.                 height = 96;  
    235.             } elseif (size.width < 176) {  
    236.                 width = 176;  
    237.                 height = 144;  
    238.             } else {  
    239.                 width = 352;  
    240.                 height = 288;  
    241.             }  
    242.         } else {  
    243.             return supported;  
    244.         }  
    245.  
    246.         return (new VideoFormat(null, new Dimension(width, height),  
    247.                 Format.NOT_SPECIFIED, null, Format.NOT_SPECIFIED))  
    248.                 .intersects(supported);  
    249.     }  
    250.     void setJPEGQuality(Player p, float val) {  
    251.  
    252.         Control cs[] = p.getControls();  
    253.         QualityControl qc = null;  
    254.         VideoFormat jpegFmt = new VideoFormat(VideoFormat.JPEG);  
    255.         for (int i = 0; i < cs.length; i++) {  
    256.  
    257.             if (cs[i] instanceof QualityControl && cs[i] instanceof Owned) {  
    258.                 Object owner = ((Owned) cs[i]).getOwner();  
    259.                 if (owner instanceof Codec) {  
    260.                     Format fmts[] = ((Codec) owner)  
    261.                             .getSupportedOutputFormats(null);  
    262.                     for (int j = 0; j < fmts.length; j++) {  
    263.                         if (fmts[j].matches(jpegFmt)) {  
    264.                             qc = (QualityControl) cs[i];  
    265.                             qc.setQuality(val);  
    266.                             System.err.println("- Setting quality to " + val  
    267.                                     + " on " + qc);  
    268.                             break;  
    269.                         }  
    270.                     }  
    271.                 }  
    272.                 if (qc != null)  
    273.                     break;  
    274.             }  
    275.         }  
    276.     }  
    277.     private Integer stateLock = new Integer(0);  
    278.     privateboolean failed = false;  
    279.  
    280.     Integer getStateLock() {  
    281.         return stateLock;  
    282.     }  
    283.  
    284.     void setFailed() {  
    285.         failed = true;  
    286.     }  
    287.  
    288.     privatesynchronizedboolean waitForState(Processor p, int state) {  
    289.         p.addControllerListener(new StateListener());  
    290.         failed = false;  
    291.         if (state == Processor.Configured) {  
    292.             p.configure();  
    293.         } elseif (state == Processor.Realized) {  
    294.             p.realize();  
    295.         }  
    296.         while (p.getState() < state && !failed) {  
    297.             synchronized (getStateLock()) {  
    298.                 try {  
    299.                     getStateLock().wait();  
    300.                 } catch (InterruptedException ie) {  
    301.                     returnfalse;  
    302.                 }  
    303.             }  
    304.         }  
    305.  
    306.         if (failed)  
    307.             returnfalse;  
    308.         else 
    309.             returntrue;  
    310.     }  
    311.     class StateListener implements ControllerListener {  
    312.  
    313.         publicvoid controllerUpdate(ControllerEvent ce) {  
    314.  
    315.             if (ce instanceof ControllerClosedEvent)  
    316.                 setFailed();  
    317.  
    318.             if (ce instanceof ControllerEvent) {  
    319.                 synchronized (getStateLock()) {  
    320.                     getStateLock().notifyAll();  
    321.                 }  
    322.             }  
    323.         }  
    324.     }  
    325.     publicstaticvoid main(String[] args) {  
    326.         String[] strs = { "localhost", "9994" };  
    327.         new MediaTransmit(strs[0], strs[1]);  
    328.     }  
    package vidioPlay;
    
    import java.awt.Dimension;
    import java.io.IOException;
    import java.net.InetAddress;
    import java.util.Vector;
    
    import javax.media.CaptureDeviceInfo;
    import javax.media.Codec;
    import javax.media.Control;
    import javax.media.Controller;
    import javax.media.ControllerClosedEvent;
    import javax.media.ControllerEvent;
    import javax.media.ControllerListener;
    import javax.media.Format;
    import javax.media.IncompatibleSourceException;
    import javax.media.Manager;
    import javax.media.MediaLocator;
    import javax.media.NoProcessorException;
    import javax.media.Owned;
    import javax.media.Player;
    import javax.media.Processor;
    import javax.media.cdm.CaptureDeviceManager;
    import javax.media.control.QualityControl;
    import javax.media.control.TrackControl;
    import javax.media.format.AudioFormat;
    import javax.media.format.VideoFormat;
    import javax.media.protocol.ContentDescriptor;
    import javax.media.protocol.DataSource;
    import javax.media.protocol.PushBufferDataSource;
    import javax.media.protocol.PushBufferStream;
    import javax.media.protocol.SourceCloneable;
    import javax.media.rtp.RTPManager;
    import javax.media.rtp.SendStream;
    import javax.media.rtp.SessionAddress;
    import javax.media.rtp.rtcp.SourceDescription;
    import javax.swing.JFrame;
    
    public class MediaTransmit {
    
    	private String ipAddress;
    	private int portBase;
    	private MediaLocator audioLocator = null, vedioLocator = null;
    	private Processor audioProcessor = null;
    	private Processor videoProcessor = null;
    	private DataSource audioDataLocal = null, videoDataLocal = null;
    	private DataSource audioDataOutput = null, videoDataOutput = null;
    	private RTPManager rtpMgrs[];
    	private DataSource mediaData = null;
    	private DataSource dataLocalClone = null;
    
    	private PlayPane playFrame;
    
    	public MediaTransmit(String ipAddress, String pb) {
    		this.ipAddress = ipAddress;
    		Integer integer = Integer.valueOf(pb);
    		if (integer != null) {
    			this.portBase = integer.intValue();
    		}
    		// /////////////////////////////////////////////
    		playFrame = new PlayPane();
    		JFrame jf = new JFrame("视频实例");
    
    		jf.add(playFrame);
    		jf.pack();
    		jf.setLocationRelativeTo(null);
    		jf.setDefaultCloseOperation(3);
    		jf.setVisible(true);
    		// ////////////////////////////////////////////
    		Vector<CaptureDeviceInfo> video = CaptureDeviceManager
    				.getDeviceList(new VideoFormat(null));
    		Vector<CaptureDeviceInfo> audio = CaptureDeviceManager
    				.getDeviceList(new AudioFormat(AudioFormat.LINEAR, 44100, 16, 2));
    		// MediaLocator mediaLocator = new
    		// MediaLocator("file:/C:/纯音乐 - 忧伤还是快乐.mp3");
    		if (audio != null && audio.size() > 0) {
    			audioLocator = ((CaptureDeviceInfo) audio.get(0)).getLocator();
    			if ((audioProcessor = createProcessor(audioLocator)) != null) {
    				audioDataLocal = mediaData;
    				audioDataOutput = audioProcessor.getDataOutput();
    			}
    		} else {
    			System.out.println("******错误:没有检测到您的音频采集设备!!!");
    		}
    		// /////////////////////////////////////////////////////////
    		if (video != null && video.size() > 0) {
    			vedioLocator = ((CaptureDeviceInfo) video.get(0)).getLocator();
    			if ((videoProcessor = createProcessor(vedioLocator)) != null) {
    				videoDataLocal = mediaData;
    				videoDataOutput = videoProcessor.getDataOutput();
    			}
    		} else {
    			System.out.println("******错误:没有检测到您的视频设备!!!");
    		}
    		// /////////////////////////////////////////////////////////
    		final DataSource[] dataSources = new DataSource[2];
    		dataSources[0] = audioDataLocal;
    		dataSources[1] = videoDataLocal;
    		try {
    			DataSource dsLocal = Manager.createMergingDataSource(dataSources);
    			playFrame.localPlay(dsLocal);
    		} catch (IncompatibleSourceException e) {
    			e.printStackTrace();
    			return;
    		}
    		// ////////////////////////////////////////////////远程传输
    		dataSources[1] = audioDataOutput;
    		dataSources[0] = videoDataOutput;
    
    		try {
    			DataSource dsoutput = Manager.createMergingDataSource(dataSources);
    			createTransmitter(dsoutput);
    		} catch (IncompatibleSourceException e) {
    			e.printStackTrace();
    			return;
    		}
    		audioProcessor.start();
    		videoProcessor.start();
    	}
    
    	private Processor createProcessor(MediaLocator locator) {
    		Processor processor = null;
    		if (locator == null)
    			return null;
    		// 通过设备定位器得到数据源,
    		try {
    			mediaData = Manager.createDataSource(locator);
    			// 创建可克隆数据源
    			mediaData = Manager.createCloneableDataSource(mediaData);
    			// 克隆数据源,用于传输到远程
    			dataLocalClone = ((SourceCloneable) mediaData).createClone();
    		} catch (Exception e) {
    			e.printStackTrace();
    			return null;
    		}
    		try {
    			processor = javax.media.Manager.createProcessor(dataLocalClone);
    
    		} catch (NoProcessorException npe) {
    			npe.printStackTrace();
    			return null;
    		} catch (IOException ioe) {
    			return null;
    		}
    		boolean result = waitForState(processor, Processor.Configured);
    		if (result == false)
    			return null;
    
    		TrackControl[] tracks = processor.getTrackControls();
    		if (tracks == null || tracks.length < 1)
    			return null;
    		ContentDescriptor cd = new ContentDescriptor(ContentDescriptor.RAW_RTP);
    		processor.setContentDescriptor(cd);
    		Format supportedFormats[];
    		Format chosen;
    		boolean atLeastOneTrack = false;
    		for (int i = 0; i < tracks.length; i++) {
    			if (tracks[i].isEnabled()) {
    				supportedFormats = tracks[i].getSupportedFormats();
    				if (supportedFormats.length > 0) {
    					if (supportedFormats[0] instanceof VideoFormat) {
    						chosen = checkForVideoSizes(tracks[i].getFormat(),
    								supportedFormats[0]);
    					} else
    						chosen = supportedFormats[0];
    					tracks[i].setFormat(chosen);
    					System.err
    							.println("Track " + i + " is set to transmit as:");
    					System.err.println("  " + chosen);
    					atLeastOneTrack = true;
    				} else
    					tracks[i].setEnabled(false);
    			} else
    				tracks[i].setEnabled(false);
    		}
    
    		if (!atLeastOneTrack)
    			return null;
    		result = waitForState(processor, Controller.Realized);
    		if (result == false)
    			return null;
    		setJPEGQuality(processor, 0.5f);
    
    		return processor;
    	}
    
    	private String createTransmitter(DataSource dataOutput) {
    		PushBufferDataSource pbds = (PushBufferDataSource) dataOutput;
    		PushBufferStream pbss[] = pbds.getStreams();
    		System.out.println("pbss.length:" + pbss.length);
    		rtpMgrs = new RTPManager[pbss.length];
    		SendStream sendStream;
    		int port;
    		// SourceDescription srcDesList[];
    
    		for (int i = 0; i < pbss.length; i++) {
    			try {
    				rtpMgrs[i] = RTPManager.newInstance();
    
    				port = portBase + 2 * i;
    				SessionAddress localAddr = new SessionAddress(
    						InetAddress.getLocalHost(), port);
    				SessionAddress destAddr = new SessionAddress(
    						InetAddress.getByName(ipAddress), port);
    				rtpMgrs[i].initialize(localAddr);
    				rtpMgrs[i].addTarget(destAddr);
    				System.out.println("Created RTP session: "
    						+ InetAddress.getLocalHost() + " " + port);
    				sendStream = rtpMgrs[i].createSendStream(dataOutput, i);
    				sendStream.start();
    			} catch (Exception e) {
    				e.printStackTrace();
    				return e.getMessage();
    			}
    		}
    
    		return null;
    	}
    	Format checkForVideoSizes(Format original, Format supported) {
    
    		int width, height;
    		Dimension size = ((VideoFormat) original).getSize();
    		Format jpegFmt = new Format(VideoFormat.JPEG_RTP);
    		Format h263Fmt = new Format(VideoFormat.H263_RTP);
    
    		if (supported.matches(jpegFmt)) {
    			width = (size.width % 8 == 0 ? size.width
    					: (int) (size.width / 8) * 8);
    			height = (size.height % 8 == 0 ? size.height
    					: (int) (size.height / 8) * 8);
    		} else if (supported.matches(h263Fmt)) {
    			if (size.width < 128) {
    				width = 128;
    				height = 96;
    			} else if (size.width < 176) {
    				width = 176;
    				height = 144;
    			} else {
    				width = 352;
    				height = 288;
    			}
    		} else {
    			return supported;
    		}
    
    		return (new VideoFormat(null, new Dimension(width, height),
    				Format.NOT_SPECIFIED, null, Format.NOT_SPECIFIED))
    				.intersects(supported);
    	}
    	void setJPEGQuality(Player p, float val) {
    
    		Control cs[] = p.getControls();
    		QualityControl qc = null;
    		VideoFormat jpegFmt = new VideoFormat(VideoFormat.JPEG);
    		for (int i = 0; i < cs.length; i++) {
    
    			if (cs[i] instanceof QualityControl && cs[i] instanceof Owned) {
    				Object owner = ((Owned) cs[i]).getOwner();
    				if (owner instanceof Codec) {
    					Format fmts[] = ((Codec) owner)
    							.getSupportedOutputFormats(null);
    					for (int j = 0; j < fmts.length; j++) {
    						if (fmts[j].matches(jpegFmt)) {
    							qc = (QualityControl) cs[i];
    							qc.setQuality(val);
    							System.err.println("- Setting quality to " + val
    									+ " on " + qc);
    							break;
    						}
    					}
    				}
    				if (qc != null)
    					break;
    			}
    		}
    	}
    	private Integer stateLock = new Integer(0);
    	private boolean failed = false;
    
    	Integer getStateLock() {
    		return stateLock;
    	}
    
    	void setFailed() {
    		failed = true;
    	}
    
    	private synchronized boolean waitForState(Processor p, int state) {
    		p.addControllerListener(new StateListener());
    		failed = false;
    		if (state == Processor.Configured) {
    			p.configure();
    		} else if (state == Processor.Realized) {
    			p.realize();
    		}
    		while (p.getState() < state && !failed) {
    			synchronized (getStateLock()) {
    				try {
    					getStateLock().wait();
    				} catch (InterruptedException ie) {
    					return false;
    				}
    			}
    		}
    
    		if (failed)
    			return false;
    		else
    			return true;
    	}
    	class StateListener implements ControllerListener {
    
    		public void controllerUpdate(ControllerEvent ce) {
    
    			if (ce instanceof ControllerClosedEvent)
    				setFailed();
    
    			if (ce instanceof ControllerEvent) {
    				synchronized (getStateLock()) {
    					getStateLock().notifyAll();
    				}
    			}
    		}
    	}
    	public static void main(String[] args) {
    		String[] strs = { "localhost", "9994" };
    		new MediaTransmit(strs[0], strs[1]);
    	}
    }
    
    Java代码 复制代码 收藏代码
    1. package vidioPlay;  
    2.  
    3. import java.awt.BorderLayout;  
    4. import java.awt.Component;  
    5. import java.awt.Dimension;  
    6. import java.awt.Panel;  
    7. import java.net.InetAddress;  
    8. import java.util.Vector;  
    9.  
    10. import javax.media.ControllerErrorEvent;  
    11. import javax.media.ControllerEvent;  
    12. import javax.media.ControllerListener;  
    13. import javax.media.Player;  
    14. import javax.media.RealizeCompleteEvent;  
    15. import javax.media.bean.playerbean.MediaPlayer;  
    16. import javax.media.control.BufferControl;  
    17. import javax.media.format.FormatChangeEvent;  
    18. import javax.media.protocol.DataSource;  
    19. import javax.media.rtp.Participant;  
    20. import javax.media.rtp.RTPControl;  
    21. import javax.media.rtp.RTPManager;  
    22. import javax.media.rtp.ReceiveStream;  
    23. import javax.media.rtp.ReceiveStreamListener;  
    24. import javax.media.rtp.SessionListener;  
    25. import javax.media.rtp.event.ByeEvent;  
    26. import javax.media.rtp.event.NewParticipantEvent;  
    27. import javax.media.rtp.event.NewReceiveStreamEvent;  
    28. import javax.media.rtp.event.ReceiveStreamEvent;  
    29. import javax.media.rtp.event.RemotePayloadChangeEvent;  
    30. import javax.media.rtp.event.SessionEvent;  
    31. import javax.media.rtp.event.StreamMappedEvent;  
    32. import javax.swing.JFrame;  
    33.  
    34. import net.sf.fmj.media.rtp.RTPSocketAdapter;  
    35.  
    36.  
    37. publicclass MediaReceive implements ReceiveStreamListener, SessionListener,  
    38.         ControllerListener {  
    39.     String sessions[] = null;  
    40.     RTPManager mgrs[] = null;  
    41.  
    42.     boolean dataReceived = false;  
    43.     Object dataSync = new Object();  
    44.     private PlayPane playFrame;  
    45.  
    46.     public MediaReceive(String sessions[]) {  
    47.         this.sessions = sessions;  
    48.     }  
    49.  
    50.     protectedvoid initialize() {  
    51.         playFrame = new PlayPane();  
    52.         JFrame jf = new JFrame("视频实例");  
    53.  
    54.         jf.add(playFrame);  
    55.         jf.pack();  
    56.         jf.setLocationRelativeTo(null);  
    57.         jf.setDefaultCloseOperation(3);  
    58.         jf.setVisible(true);  
    59.         try {  
    60.             // 每一个session对应一个RTPManager  
    61.             mgrs = new RTPManager[sessions.length];  
    62.             // 创建播放窗口的向量vector  
    63.  
    64.             SessionLabel session = null;  
    65.  
    66.             // Open the RTP sessions.  
    67.             // 针对每一个会话对象进行ip、port和ttl的解析  
    68.             for (int i = 0; i < sessions.length; i++) {  
    69.  
    70.                 // Parse the session addresses.  
    71.                 // 进行会话对象的解析,得到ip、port和ttl  
    72.                 try {  
    73.                     session = new SessionLabel(sessions[i]);  
    74.                 } catch (IllegalArgumentException e) {  
    75.                     System.err  
    76.                             .println("Failed to parse the session address given: " 
    77.                                     + sessions[i]);  
    78.                     // return false;  
    79.                 }  
    80.  
    81.                 System.err.println("  - Open RTP session for: addr: " 
    82.                         + session.addr + " port: " + session.port + " ttl: " 
    83.                         + session.ttl);  
    84.                 // 这对本条会话对象创建RTPManager  
    85.                 mgrs[i] = (RTPManager) RTPManager.newInstance();  
    86.                 mgrs[i].addSessionListener(this);  
    87.                 mgrs[i].addReceiveStreamListener(this);  
    88.  
    89.                 // Initialize the RTPManager with the RTPSocketAdapter  
    90.                 // 将本机ip和端口号加入RTP会话管理  
    91.                 System.out.println("session.addr:" + session.addr);  
    92.                 mgrs[i].initialize(new RTPSocketAdapter(InetAddress  
    93.                         .getByName(session.addr), session.port, session.ttl));  
    94.                 BufferControl bc = (BufferControl) mgrs[i]  
    95.                         .getControl("javax.media.control.BufferControl");  
    96.                 if (bc != null)  
    97.                     bc.setBufferLength(350);  
    98.             }  
    99.  
    100.         } catch (Exception e) {  
    101.             e.printStackTrace();  
    102.         }  
    103.     }  
    104.  
    105.     /**
    106.      * Close the players and the session managers.
    107.      */ 
    108.     protectedvoid close() {  
    109.  
    110.         // close the RTP session.  
    111.         for (int i = 0; i < mgrs.length; i++) {  
    112.             if (mgrs[i] != null) {  
    113.                 mgrs[i].removeTargets("Closing session from AVReceive3");  
    114.                 mgrs[i].dispose();  
    115.                 mgrs[i] = null;  
    116.             }  
    117.         }  
    118.     }  
    119.  
    120.     /**
    121.      * SessionListener.
    122.      */ 
    123.     @SuppressWarnings("deprecation")  
    124.     publicsynchronizedvoid update(SessionEvent evt) {  
    125.  
    126.         if (evt instanceof NewParticipantEvent) {  
    127.             Participant p = ((NewParticipantEvent) evt).getParticipant();  
    128.             System.err.println("  - A new participant had just joined: " + p);  
    129.         }  
    130.     }  
    131.  
    132.     /**
    133.      * ReceiveStreamListener
    134.      */ 
    135.     publicsynchronizedvoid update(ReceiveStreamEvent evt) {  
    136.  
    137.         RTPManager mgr = (RTPManager) evt.getSource();  
    138.         Participant participant = evt.getParticipant(); // could be null.  
    139.         ReceiveStream stream = evt.getReceiveStream(); // could be null.  
    140.  
    141.         if (evt instanceof RemotePayloadChangeEvent) {  
    142.  
    143.             System.err.println("  - Received an RTP PayloadChangeEvent.");  
    144.             System.err.println("Sorry, cannot handle payload change.");  
    145.             // System.exit(0);  
    146.  
    147.         }  
    148.  
    149.         elseif (evt instanceof NewReceiveStreamEvent) {  
    150.             System.out.println("evt instanceof NewReceiveStreamEvent");  
    151.             try {  
    152.                 stream = ((NewReceiveStreamEvent) evt).getReceiveStream();  
    153.                 final DataSource data = stream.getDataSource();  
    154.  
    155.                 // Find out the formats.  
    156.                 RTPControl ctl = (RTPControl) data  
    157.                         .getControl("javax.media.rtp.RTPControl");  
    158.                 if (ctl != null) {  
    159.                     System.err.println("  - Recevied new RTP stream: " 
    160.                             + ctl.getFormat());  
    161.                 } else 
    162.                     System.err.println("  - Recevied new RTP stream");  
    163.  
    164.                 if (participant == null)  
    165.                     System.err  
    166.                             .println("      The sender of this stream had yet to be identified.");  
    167.                 else {  
    168.                     System.err.println("      The stream comes from: " 
    169.                             + participant.getCNAME());  
    170.                 }  
    171.  
    172.                 // create a player by passing datasource to the Media Manager  
    173.                 new Thread() {  
    174.                     publicvoid run() {  
    175.                         playFrame.remotePlay(data);  
    176.                     }  
    177.                 }.start();  
    178.                 // Player p = javax.media.Manager.createPlayer(data);  
    179.                 // if (p == null)  
    180.                 // return;  
    181.                 //  
    182.                 // p.addControllerListener(this);  
    183.                 // p.realize();  
    184.                 // PlayerWindow pw = new PlayerWindow(p, stream);  
    185.                 // playerWindows.addElement(pw);  
    186.  
    187.                 // Notify intialize() that a new stream had arrived.  
    188.                 synchronized (dataSync) {  
    189.                     dataReceived = true;  
    190.                     dataSync.notifyAll();  
    191.                 }  
    192.  
    193.             } catch (Exception e) {  
    194.                 System.err.println("NewReceiveStreamEvent exception " 
    195.                         + e.getMessage());  
    196.                 return;  
    197.             }  
    198.  
    199.         }  
    200.  
    201.         elseif (evt instanceof StreamMappedEvent) {  
    202.             System.out.println("evt instanceof StreamMappedEvent");  
    203.             stream = ((StreamMappedEvent) evt).getReceiveStream();  
    204.             if (stream != null && stream.getDataSource() != null) {  
    205.                 DataSource ds = stream.getDataSource();  
    206.                 // Find out the formats.  
    207.                 RTPControl ctl = (RTPControl) ds  
    208.                         .getControl("javax.media.rtp.RTPControl");  
    209.                 System.err.println("  - The previously unidentified stream ");  
    210.                 if (ctl != null)  
    211.                     System.err.println("      " + ctl.getFormat());  
    212.                 System.err.println("      had now been identified as sent by: " 
    213.                         + participant.getCNAME());  
    214.                 System.out.println("ds == null" + (ds == null));  
    215.             }  
    216.         }  
    217.  
    218.         elseif (evt instanceof ByeEvent) {  
    219.  
    220.             System.err.println("  - Got \"bye\" from: " 
    221.                     + participant.getCNAME());  
    222.  
    223.         }  
    224.  
    225.     }  
    226.  
    227.     /**
    228.      * ControllerListener for the Players.
    229.      */ 
    230.     publicsynchronizedvoid controllerUpdate(ControllerEvent ce) {  
    231.  
    232.         Player p = (Player) ce.getSourceController();  
    233.  
    234.         if (p == null)  
    235.             return;  
    236.  
    237.     }  
    238.  
    239.     /**
    240.      * A utility class to parse the session addresses.
    241.      */ 
    242.     class SessionLabel {  
    243.  
    244.         public String addr = null;  
    245.         publicint port;  
    246.         publicint ttl = 1;  
    247.  
    248.         SessionLabel(String session) throws IllegalArgumentException {  
    249.  
    250.             int off;  
    251.             String portStr = null, ttlStr = null;  
    252.  
    253.             if (session != null && session.length() > 0) {  
    254.                 while (session.length() > 1 && session.charAt(0) == '/') {  
    255.                     session = session.substring(1);  
    256.                 }  
    257.                 off = session.indexOf('/');  
    258.                 if (off == -1) {  
    259.                     if (!session.equals(""))  
    260.                         addr = session;  
    261.                 } else {  
    262.                     addr = session.substring(0, off);  
    263.                     session = session.substring(off + 1);  
    264.                     off = session.indexOf('/');  
    265.                     if (off == -1) {  
    266.                         if (!session.equals(""))  
    267.                             portStr = session;  
    268.                     } else {  
    269.                         portStr = session.substring(0, off);  
    270.                         session = session.substring(off + 1);  
    271.                         off = session.indexOf('/');  
    272.                         if (off == -1) {  
    273.                             if (!session.equals(""))  
    274.                                 ttlStr = session;  
    275.                         } else {  
    276.                             ttlStr = session.substring(0, off);  
    277.                         }  
    278.                     }  
    279.                 }  
    280.             }  
    281.  
    282.             if (addr == null)  
    283.                 thrownew IllegalArgumentException();  
    284.  
    285.             if (portStr != null) {  
    286.                 try {  
    287.                     Integer integer = Integer.valueOf(portStr);  
    288.                     if (integer != null)  
    289.                         port = integer.intValue();  
    290.                 } catch (Throwable t) {  
    291.                     thrownew IllegalArgumentException();  
    292.                 }  
    293.             } else 
    294.                 thrownew IllegalArgumentException();  
    295.  
    296.             if (ttlStr != null) {  
    297.                 try {  
    298.                     Integer integer = Integer.valueOf(ttlStr);  
    299.                     if (integer != null)  
    300.                         ttl = integer.intValue();  
    301.                 } catch (Throwable t) {  
    302.                     thrownew IllegalArgumentException();  
    303.                 }  
    304.             }  
    305.         }  
    306.     }  
    307.       
    308.  
    309.     publicstaticvoid main(String argv[]) {  
    310.         String[] strs = { "125.221.165.126/9994", "125.221.165.126/9996" };  
    311.         MediaReceive avReceive = new MediaReceive(strs);  
    312.         avReceive.initialize();  
    313.  
    314.     }  
    package vidioPlay;
    
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Panel;
    import java.net.InetAddress;
    import java.util.Vector;
    
    import javax.media.ControllerErrorEvent;
    import javax.media.ControllerEvent;
    import javax.media.ControllerListener;
    import javax.media.Player;
    import javax.media.RealizeCompleteEvent;
    import javax.media.bean.playerbean.MediaPlayer;
    import javax.media.control.BufferControl;
    import javax.media.format.FormatChangeEvent;
    import javax.media.protocol.DataSource;
    import javax.media.rtp.Participant;
    import javax.media.rtp.RTPControl;
    import javax.media.rtp.RTPManager;
    import javax.media.rtp.ReceiveStream;
    import javax.media.rtp.ReceiveStreamListener;
    import javax.media.rtp.SessionListener;
    import javax.media.rtp.event.ByeEvent;
    import javax.media.rtp.event.NewParticipantEvent;
    import javax.media.rtp.event.NewReceiveStreamEvent;
    import javax.media.rtp.event.ReceiveStreamEvent;
    import javax.media.rtp.event.RemotePayloadChangeEvent;
    import javax.media.rtp.event.SessionEvent;
    import javax.media.rtp.event.StreamMappedEvent;
    import javax.swing.JFrame;
    
    import net.sf.fmj.media.rtp.RTPSocketAdapter;
    
    
    public class MediaReceive implements ReceiveStreamListener, SessionListener,
    		ControllerListener {
    	String sessions[] = null;
    	RTPManager mgrs[] = null;
    
    	boolean dataReceived = false;
    	Object dataSync = new Object();
    	private PlayPane playFrame;
    
    	public MediaReceive(String sessions[]) {
    		this.sessions = sessions;
    	}
    
    	protected void initialize() {
    		playFrame = new PlayPane();
    		JFrame jf = new JFrame("视频实例");
    
    		jf.add(playFrame);
    		jf.pack();
    		jf.setLocationRelativeTo(null);
    		jf.setDefaultCloseOperation(3);
    		jf.setVisible(true);
    		try {
    			// 每一个session对应一个RTPManager
    			mgrs = new RTPManager[sessions.length];
    			// 创建播放窗口的向量vector
    
    			SessionLabel session = null;
    
    			// Open the RTP sessions.
    			// 针对每一个会话对象进行ip、port和ttl的解析
    			for (int i = 0; i < sessions.length; i++) {
    
    				// Parse the session addresses.
    				// 进行会话对象的解析,得到ip、port和ttl
    				try {
    					session = new SessionLabel(sessions[i]);
    				} catch (IllegalArgumentException e) {
    					System.err
    							.println("Failed to parse the session address given: "
    									+ sessions[i]);
    					// return false;
    				}
    
    				System.err.println("  - Open RTP session for: addr: "
    						+ session.addr + " port: " + session.port + " ttl: "
    						+ session.ttl);
    				// 这对本条会话对象创建RTPManager
    				mgrs[i] = (RTPManager) RTPManager.newInstance();
    				mgrs[i].addSessionListener(this);
    				mgrs[i].addReceiveStreamListener(this);
    
    				// Initialize the RTPManager with the RTPSocketAdapter
    				// 将本机ip和端口号加入RTP会话管理
    				System.out.println("session.addr:" + session.addr);
    				mgrs[i].initialize(new RTPSocketAdapter(InetAddress
    						.getByName(session.addr), session.port, session.ttl));
    				BufferControl bc = (BufferControl) mgrs[i]
    						.getControl("javax.media.control.BufferControl");
    				if (bc != null)
    					bc.setBufferLength(350);
    			}
    
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    
    	/**
    	 * Close the players and the session managers.
    	 */
    	protected void close() {
    
    		// close the RTP session.
    		for (int i = 0; i < mgrs.length; i++) {
    			if (mgrs[i] != null) {
    				mgrs[i].removeTargets("Closing session from AVReceive3");
    				mgrs[i].dispose();
    				mgrs[i] = null;
    			}
    		}
    	}
    
    	/**
    	 * SessionListener.
    	 */
    	@SuppressWarnings("deprecation")
    	public synchronized void update(SessionEvent evt) {
    
    		if (evt instanceof NewParticipantEvent) {
    			Participant p = ((NewParticipantEvent) evt).getParticipant();
    			System.err.println("  - A new participant had just joined: " + p);
    		}
    	}
    
    	/**
    	 * ReceiveStreamListener
    	 */
    	public synchronized void update(ReceiveStreamEvent evt) {
    
    		RTPManager mgr = (RTPManager) evt.getSource();
    		Participant participant = evt.getParticipant(); // could be null.
    		ReceiveStream stream = evt.getReceiveStream(); // could be null.
    
    		if (evt instanceof RemotePayloadChangeEvent) {
    
    			System.err.println("  - Received an RTP PayloadChangeEvent.");
    			System.err.println("Sorry, cannot handle payload change.");
    			// System.exit(0);
    
    		}
    
    		else if (evt instanceof NewReceiveStreamEvent) {
    			System.out.println("evt instanceof NewReceiveStreamEvent");
    			try {
    				stream = ((NewReceiveStreamEvent) evt).getReceiveStream();
    				final DataSource data = stream.getDataSource();
    
    				// Find out the formats.
    				RTPControl ctl = (RTPControl) data
    						.getControl("javax.media.rtp.RTPControl");
    				if (ctl != null) {
    					System.err.println("  - Recevied new RTP stream: "
    							+ ctl.getFormat());
    				} else
    					System.err.println("  - Recevied new RTP stream");
    
    				if (participant == null)
    					System.err
    							.println("      The sender of this stream had yet to be identified.");
    				else {
    					System.err.println("      The stream comes from: "
    							+ participant.getCNAME());
    				}
    
    				// create a player by passing datasource to the Media Manager
    				new Thread() {
    					public void run() {
    						playFrame.remotePlay(data);
    					}
    				}.start();
    				// Player p = javax.media.Manager.createPlayer(data);
    				// if (p == null)
    				// return;
    				//
    				// p.addControllerListener(this);
    				// p.realize();
    				// PlayerWindow pw = new PlayerWindow(p, stream);
    				// playerWindows.addElement(pw);
    
    				// Notify intialize() that a new stream had arrived.
    				synchronized (dataSync) {
    					dataReceived = true;
    					dataSync.notifyAll();
    				}
    
    			} catch (Exception e) {
    				System.err.println("NewReceiveStreamEvent exception "
    						+ e.getMessage());
    				return;
    			}
    
    		}
    
    		else if (evt instanceof StreamMappedEvent) {
    			System.out.println("evt instanceof StreamMappedEvent");
    			stream = ((StreamMappedEvent) evt).getReceiveStream();
    			if (stream != null && stream.getDataSource() != null) {
    				DataSource ds = stream.getDataSource();
    				// Find out the formats.
    				RTPControl ctl = (RTPControl) ds
    						.getControl("javax.media.rtp.RTPControl");
    				System.err.println("  - The previously unidentified stream ");
    				if (ctl != null)
    					System.err.println("      " + ctl.getFormat());
    				System.err.println("      had now been identified as sent by: "
    						+ participant.getCNAME());
    				System.out.println("ds == null" + (ds == null));
    			}
    		}
    
    		else if (evt instanceof ByeEvent) {
    
    			System.err.println("  - Got \"bye\" from: "
    					+ participant.getCNAME());
    
    		}
    
    	}
    
    	/**
    	 * ControllerListener for the Players.
    	 */
    	public synchronized void controllerUpdate(ControllerEvent ce) {
    
    		Player p = (Player) ce.getSourceController();
    
    		if (p == null)
    			return;
    
    	}
    
    	/**
    	 * A utility class to parse the session addresses.
    	 */
    	class SessionLabel {
    
    		public String addr = null;
    		public int port;
    		public int ttl = 1;
    
    		SessionLabel(String session) throws IllegalArgumentException {
    
    			int off;
    			String portStr = null, ttlStr = null;
    
    			if (session != null && session.length() > 0) {
    				while (session.length() > 1 && session.charAt(0) == '/') {
    					session = session.substring(1);
    				}
    				off = session.indexOf('/');
    				if (off == -1) {
    					if (!session.equals(""))
    						addr = session;
    				} else {
    					addr = session.substring(0, off);
    					session = session.substring(off + 1);
    					off = session.indexOf('/');
    					if (off == -1) {
    						if (!session.equals(""))
    							portStr = session;
    					} else {
    						portStr = session.substring(0, off);
    						session = session.substring(off + 1);
    						off = session.indexOf('/');
    						if (off == -1) {
    							if (!session.equals(""))
    								ttlStr = session;
    						} else {
    							ttlStr = session.substring(0, off);
    						}
    					}
    				}
    			}
    
    			if (addr == null)
    				throw new IllegalArgumentException();
    
    			if (portStr != null) {
    				try {
    					Integer integer = Integer.valueOf(portStr);
    					if (integer != null)
    						port = integer.intValue();
    				} catch (Throwable t) {
    					throw new IllegalArgumentException();
    				}
    			} else
    				throw new IllegalArgumentException();
    
    			if (ttlStr != null) {
    				try {
    					Integer integer = Integer.valueOf(ttlStr);
    					if (integer != null)
    						ttl = integer.intValue();
    				} catch (Throwable t) {
    					throw new IllegalArgumentException();
    				}
    			}
    		}
    	}
    	
    
    	public static void main(String argv[]) {
    		String[] strs = { "125.221.165.126/9994", "125.221.165.126/9996" };
    		MediaReceive avReceive = new MediaReceive(strs);
    		avReceive.initialize();
    
    	}
    }
    
    Java代码 复制代码 收藏代码
    1. package vidioPlay;  
    2.  
    3. import java.awt.BorderLayout;  
    4. import java.awt.Color;  
    5. import java.awt.Component;  
    6. import java.awt.Dimension;  
    7. import java.awt.FlowLayout;  
    8. import java.awt.Graphics;  
    9. import java.awt.Rectangle;  
    10. import java.awt.event.ActionEvent;  
    11. import java.awt.event.ActionListener;  
    12. import java.io.IOException;  
    13.  
    14. import javax.media.ControllerEvent;  
    15. import javax.media.ControllerListener;  
    16. import javax.media.DataSink;  
    17. import javax.media.NoPlayerException;  
    18. import javax.media.Player;  
    19. import javax.media.Processor;  
    20. import javax.media.protocol.DataSource;  
    21. import javax.swing.ImageIcon;  
    22. import javax.swing.JButton;  
    23. import javax.swing.JPanel;  
    24.  
    25. publicclass PlayPane extends JPanel {  
    26.     private ImageIcon videoReqIcon = new ImageIcon("videoReq.jpg");  
    27.     private ImageIcon VideolocalIcon = new ImageIcon("localVideo.jpg");  
    28.     privateboolean isViewBigPlaying = false;  
    29.     privateboolean isViewSmallPlaying = false;  
    30.     private JPanel viewBigPane;  
    31.     private JPanel viewSmallPane;  
    32.     private JPanel controlPane;  
    33.  
    34.     private JButton closeButton;  
    35.  
    36.     privateboolean localPlay = false;  
    37.     privateboolean remotePlay = false;  
    38.  
    39.     private DataSource localData;  
    40.     private DataSource remoteData;  
    41.  
    42.     privateboolean isViewRun = true;  
    43.     privateboolean isShow = true;  
    44.     //  
    45.     private Player localPlayer = null;  
    46.     private Player remotePlayer = null;  
    47.     //  
    48.     private Processor videotapeProcessor = null;  
    49.     private Player videotapePlayer = null;  
    50.     private DataSink videotapeFileWriter;  
    51.  
    52.     public PlayPane() {  
    53.         this.setLayout(new BorderLayout());  
    54.         // 视图面板  
    55.         viewBigPane = new JPanel() {  
    56.             publicvoid paintComponent(Graphics g) {  
    57.                 super.paintComponent(g);  
    58.                 if (!isViewBigPlaying) {  
    59.                     g.drawImage(videoReqIcon.getImage(), 1, 1,  
    60.                             videoReqIcon.getIconWidth(),  
    61.                             videoReqIcon.getIconHeight(), null);  
    62.  
    63.                     g.drawRect(getSmallPlayRec().x - 1,  
    64.                             getSmallPlayRec().y - 1,  
    65.                             getSmallPlayRec().width + 1,  
    66.                             getSmallPlayRec().height + 1);  
    67.                 } else {  
    68.  
    69.                 }  
    70.             }  
    71.         };  
    72.         viewBigPane.setBackground(Color.black);  
    73.         this.add(viewBigPane, BorderLayout.CENTER);  
    74.         viewBigPane.setLayout(null);  
    75.         // ///////////////////////////////  
    76.         viewSmallPane = new JPanel() {  
    77.             publicvoid paintComponent(Graphics g) {  
    78.                 super.paintComponent(g);  
    79.                 if (!isViewSmallPlaying) {  
    80.                     g.drawImage(VideolocalIcon.getImage(), 0, 0, null);  
    81.                 } else {  
    82.  
    83.                 }  
    84.             }  
    85.         };  
    86.         viewSmallPane.setBounds(getSmallPlayRec());  
    87.         viewBigPane.add(viewSmallPane);  
    88.         viewSmallPane.setLayout(null);  
    89.  
    90.         // 控制面板组件  
    91.         closeButton = new JButton("挂断");  
    92.         controlPane = new JPanel();  
    93.         controlPane.setLayout(new FlowLayout(FlowLayout.RIGHT, 0, 0));  
    94.         controlPane.add(closeButton);  
    95.         this.add(controlPane, BorderLayout.SOUTH);  
    96.         closeButton.addActionListener(new ActionListener() {  
    97.             publicvoid actionPerformed(ActionEvent e) {  
    98.                 if (localPlayer != null) {  
    99.                     localPlayer.stop();  
    100.                 }  
    101.                 if (remotePlayer != null) {  
    102.                     remotePlayer.stop();  
    103.                 }  
    104.                 if (videotapePlayer != null) {  
    105.                     videotapePlayer.stop();  
    106.                 }  
    107.                 if (videotapeProcessor != null) {  
    108.                     videotapeProcessor.stop();  
    109.                 }  
    110.                 if (videotapeFileWriter != null) {  
    111.                     try {  
    112.                         videotapeFileWriter.stop();  
    113.                         videotapeFileWriter.close();  
    114.                     } catch (IOException e1) {  
    115.                     }  
    116.                 }  
    117.             }  
    118.  
    119.         });  
    120.         // this.setMinimumSize(new Dimension(videoReqIcon.getIconWidth()+2,  
    121.         // 241));  
    122.         // this.setPreferredSize(new Dimension(videoReqIcon.getIconWidth()+2,  
    123.         // 241));  
    124.  
    125.     }  
    126.  
    127.     public Dimension getMinimumSize() {  
    128.         System.out  
    129.                 .println("controlPane.getHeight():" + controlPane.getHeight());  
    130.         returnnew Dimension(videoReqIcon.getIconWidth() + 2,  
    131.                 videoReqIcon.getIconHeight() + controlPane.getHeight());  
    132.     }  
    133.  
    134.     public Dimension getPreferredSize() {  
    135.         System.out  
    136.                 .println("controlPane.getHeight():" + controlPane.getHeight());  
    137.         returnnew Dimension(videoReqIcon.getIconWidth() + 2,  
    138.                 videoReqIcon.getIconHeight()  
    139.                         + controlPane.getPreferredSize().height);  
    140.     }  
    141.  
    142.     publicvoid localPlay(DataSource dataSource) {  
    143.         this.setLocalData(dataSource);  
    144.         try {  
    145.             localPlayer = javax.media.Manager.createPlayer(dataSource);  
    146.  
    147.             localPlayer.addControllerListener(new ControllerListener() {  
    148.                 publicvoid controllerUpdate(ControllerEvent e) {  
    149.  
    150.                     if (e instanceof javax.media.RealizeCompleteEvent) {  
    151.                         Component comp = null;  
    152.                         comp = localPlayer.getVisualComponent();  
    153.                         if (comp != null) {  
    154.                             // 将可视容器加到窗体上  
    155.                             comp.setBounds(0, 0, VideolocalIcon.getIconWidth(),  
    156.                                     VideolocalIcon.getIconHeight());  
    157.                             viewSmallPane.add(comp);  
    158.                         }  
    159.                         viewBigPane.validate();  
    160.                     }  
    161.                 }  
    162.             });  
    163.             localPlayer.start();  
    164.             localPlay = true;  
    165.         } catch (NoPlayerException e1) {  
    166.             e1.printStackTrace();  
    167.         } catch (IOException e1) {  
    168.             e1.printStackTrace();  
    169.         }  
    170.     }  
    171.  
    172.     private Rectangle getSmallPlayRec() {  
    173.         int bigShowWidth = videoReqIcon.getIconWidth();  
    174.         int bigShowHeight = videoReqIcon.getIconHeight();  
    175.         int smallShowWidth = VideolocalIcon.getIconWidth();  
    176.         int smallShowHeight = VideolocalIcon.getIconHeight();  
    177.         returnnew Rectangle(bigShowWidth - smallShowWidth - 2, bigShowHeight  
    178.                 - smallShowHeight - 2, smallShowWidth, smallShowHeight);  
    179.     }  
    180.  
    181.     publicvoid remotePlay(DataSource dataSource) {  
    182.         this.setLocalData(dataSource);  
    183.         remotePlay = true;  
    184.         try {  
    185.             remotePlayer = javax.media.Manager.createPlayer(dataSource);  
    186.  
    187.             remotePlayer.addControllerListener(new ControllerListener() {  
    188.                 publicvoid controllerUpdate(ControllerEvent e) {  
    189.  
    190.                     if (e instanceof javax.media.RealizeCompleteEvent) {  
    191.                         Component comp;  
    192.                         if ((comp = remotePlayer.getVisualComponent()) != null) {  
    193.                             // 将可视容器加到窗体上  
    194.                             comp.setBounds(1, 1, videoReqIcon.getIconWidth(),  
    195.                                     videoReqIcon.getIconHeight());  
    196.                             viewBigPane.add(comp);  
    197.                         }  
    198.                         viewBigPane.validate();  
    199.                     }  
    200.                 }  
    201.             });  
    202.             remotePlayer.start();  
    203.             remotePlay = true;  
    204.         } catch (NoPlayerException e1) {  
    205.             e1.printStackTrace();  
    206.         } catch (IOException e1) {  
    207.             e1.printStackTrace();  
    208.         }  
    209.     }  
    210.  
    211.     publicvoid closeViewUI() {  
    212.         isShow = false;  
    213.     }  
    214.  
    215.     publicboolean isViewRunning() {  
    216.         return isViewRun;  
    217.     }  
    218.  
    219.     publicboolean isShowing() {  
    220.         return isShow;  
    221.     }  
    222.  
    223.     publicvoid localReady() {  
    224.         localPlay = true;  
    225.     }  
    226.  
    227.     publicvoid remoteReady() {  
    228.         remotePlay = true;  
    229.     }  
    230.  
    231.     publicboolean isRemotePlay() {  
    232.         return remotePlay;  
    233.     }  
    234.  
    235.     publicvoid setRemotePlay(boolean remotePlay) {  
    236.         this.remotePlay = remotePlay;  
    237.     }  
    238.  
    239.     public DataSource getRemoteData() {  
    240.         return remoteData;  
    241.     }  
    242.  
    243.     publicvoid setRemoteData(DataSource remoteData) {  
    244.         this.remoteData = remoteData;  
    245.     }  
    246.  
    247.     publicboolean isLocalPlay() {  
    248.         return localPlay;  
    249.     }  
    250.  
    251.     publicvoid setLocalPlay(boolean localPlay) {  
    252.         this.localPlay = localPlay;  
    253.     }  
    254.  
    255.     public DataSource getLocalData() {  
    256.         return localData;  
    257.     }  
    258.  
    259.     publicvoid setLocalData(DataSource localData) {  
    260.         this.localData = localData;  
    261.     }  
    262.  
    package vidioPlay;
    
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import java.awt.Rectangle;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    
    import javax.media.ControllerEvent;
    import javax.media.ControllerListener;
    import javax.media.DataSink;
    import javax.media.NoPlayerException;
    import javax.media.Player;
    import javax.media.Processor;
    import javax.media.protocol.DataSource;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    
    public class PlayPane extends JPanel {
    	private ImageIcon videoReqIcon = new ImageIcon("videoReq.jpg");
    	private ImageIcon VideolocalIcon = new ImageIcon("localVideo.jpg");
    	private boolean isViewBigPlaying = false;
    	private boolean isViewSmallPlaying = false;
    	private JPanel viewBigPane;
    	private JPanel viewSmallPane;
    	private JPanel controlPane;
    
    	private JButton closeButton;
    
    	private boolean localPlay = false;
    	private boolean remotePlay = false;
    
    	private DataSource localData;
    	private DataSource remoteData;
    
    	private boolean isViewRun = true;
    	private boolean isShow = true;
    	//
    	private Player localPlayer = null;
    	private Player remotePlayer = null;
    	//
    	private Processor videotapeProcessor = null;
    	private Player videotapePlayer = null;
    	private DataSink videotapeFileWriter;
    
    	public PlayPane() {
    		this.setLayout(new BorderLayout());
    		// 视图面板
    		viewBigPane = new JPanel() {
    			public void paintComponent(Graphics g) {
    				super.paintComponent(g);
    				if (!isViewBigPlaying) {
    					g.drawImage(videoReqIcon.getImage(), 1, 1,
    							videoReqIcon.getIconWidth(),
    							videoReqIcon.getIconHeight(), null);
    
    					g.drawRect(getSmallPlayRec().x - 1,
    							getSmallPlayRec().y - 1,
    							getSmallPlayRec().width + 1,
    							getSmallPlayRec().height + 1);
    				} else {
    
    				}
    			}
    		};
    		viewBigPane.setBackground(Color.black);
    		this.add(viewBigPane, BorderLayout.CENTER);
    		viewBigPane.setLayout(null);
    		// ///////////////////////////////
    		viewSmallPane = new JPanel() {
    			public void paintComponent(Graphics g) {
    				super.paintComponent(g);
    				if (!isViewSmallPlaying) {
    					g.drawImage(VideolocalIcon.getImage(), 0, 0, null);
    				} else {
    
    				}
    			}
    		};
    		viewSmallPane.setBounds(getSmallPlayRec());
    		viewBigPane.add(viewSmallPane);
    		viewSmallPane.setLayout(null);
    
    		// 控制面板组件
    		closeButton = new JButton("挂断");
    		controlPane = new JPanel();
    		controlPane.setLayout(new FlowLayout(FlowLayout.RIGHT, 0, 0));
    		controlPane.add(closeButton);
    		this.add(controlPane, BorderLayout.SOUTH);
    		closeButton.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				if (localPlayer != null) {
    					localPlayer.stop();
    				}
    				if (remotePlayer != null) {
    					remotePlayer.stop();
    				}
    				if (videotapePlayer != null) {
    					videotapePlayer.stop();
    				}
    				if (videotapeProcessor != null) {
    					videotapeProcessor.stop();
    				}
    				if (videotapeFileWriter != null) {
    					try {
    						videotapeFileWriter.stop();
    						videotapeFileWriter.close();
    					} catch (IOException e1) {
    					}
    				}
    			}
    
    		});
    		// this.setMinimumSize(new Dimension(videoReqIcon.getIconWidth()+2,
    		// 241));
    		// this.setPreferredSize(new Dimension(videoReqIcon.getIconWidth()+2,
    		// 241));
    
    	}
    
    	public Dimension getMinimumSize() {
    		System.out
    				.println("controlPane.getHeight():" + controlPane.getHeight());
    		return new Dimension(videoReqIcon.getIconWidth() + 2,
    				videoReqIcon.getIconHeight() + controlPane.getHeight());
    	}
    
    	public Dimension getPreferredSize() {
    		System.out
    				.println("controlPane.getHeight():" + controlPane.getHeight());
    		return new Dimension(videoReqIcon.getIconWidth() + 2,
    				videoReqIcon.getIconHeight()
    						+ controlPane.getPreferredSize().height);
    	}
    
    	public void localPlay(DataSource dataSource) {
    		this.setLocalData(dataSource);
    		try {
    			localPlayer = javax.media.Manager.createPlayer(dataSource);
    
    			localPlayer.addControllerListener(new ControllerListener() {
    				public void controllerUpdate(ControllerEvent e) {
    
    					if (e instanceof javax.media.RealizeCompleteEvent) {
    						Component comp = null;
    						comp = localPlayer.getVisualComponent();
    						if (comp != null) {
    							// 将可视容器加到窗体上
    							comp.setBounds(0, 0, VideolocalIcon.getIconWidth(),
    									VideolocalIcon.getIconHeight());
    							viewSmallPane.add(comp);
    						}
    						viewBigPane.validate();
    					}
    				}
    			});
    			localPlayer.start();
    			localPlay = true;
    		} catch (NoPlayerException e1) {
    			e1.printStackTrace();
    		} catch (IOException e1) {
    			e1.printStackTrace();
    		}
    	}
    
    	private Rectangle getSmallPlayRec() {
    		int bigShowWidth = videoReqIcon.getIconWidth();
    		int bigShowHeight = videoReqIcon.getIconHeight();
    		int smallShowWidth = VideolocalIcon.getIconWidth();
    		int smallShowHeight = VideolocalIcon.getIconHeight();
    		return new Rectangle(bigShowWidth - smallShowWidth - 2, bigShowHeight
    				- smallShowHeight - 2, smallShowWidth, smallShowHeight);
    	}
    
    	public void remotePlay(DataSource dataSource) {
    		this.setLocalData(dataSource);
    		remotePlay = true;
    		try {
    			remotePlayer = javax.media.Manager.createPlayer(dataSource);
    
    			remotePlayer.addControllerListener(new ControllerListener() {
    				public void controllerUpdate(ControllerEvent e) {
    
    					if (e instanceof javax.media.RealizeCompleteEvent) {
    						Component comp;
    						if ((comp = remotePlayer.getVisualComponent()) != null) {
    							// 将可视容器加到窗体上
    							comp.setBounds(1, 1, videoReqIcon.getIconWidth(),
    									videoReqIcon.getIconHeight());
    							viewBigPane.add(comp);
    						}
    						viewBigPane.validate();
    					}
    				}
    			});
    			remotePlayer.start();
    			remotePlay = true;
    		} catch (NoPlayerException e1) {
    			e1.printStackTrace();
    		} catch (IOException e1) {
    			e1.printStackTrace();
    		}
    	}
    
    	public void closeViewUI() {
    		isShow = false;
    	}
    
    	public boolean isViewRunning() {
    		return isViewRun;
    	}
    
    	public boolean isShowing() {
    		return isShow;
    	}
    
    	public void localReady() {
    		localPlay = true;
    	}
    
    	public void remoteReady() {
    		remotePlay = true;
    	}
    
    	public boolean isRemotePlay() {
    		return remotePlay;
    	}
    
    	public void setRemotePlay(boolean remotePlay) {
    		this.remotePlay = remotePlay;
    	}
    
    	public DataSource getRemoteData() {
    		return remoteData;
    	}
    
    	public void setRemoteData(DataSource remoteData) {
    		this.remoteData = remoteData;
    	}
    
    	public boolean isLocalPlay() {
    		return localPlay;
    	}
    
    	public void setLocalPlay(boolean localPlay) {
    		this.localPlay = localPlay;
    	}
    
    	public DataSource getLocalData() {
    		return localData;
    	}
    
    	public void setLocalData(DataSource localData) {
    		this.localData = localData;
    	}
    
    }
    

    之后操作如下:

    1、安装JMF软件(如果不想安装,就请阅读我转载一篇文章):

    2、新建工程将源代码加入工程src下

    3、导入第三方包jmf.jar,和fmj.jar(如果网上找不到,请加入该群83945749)

    4、运行的时候先运行MediaTransmit类,后运行MediaReceive类

    I'm falling off the sky all alone.The courage inside is gonna break the fall. Nothing can dim my light within. I am That I am 程序 = 数据结构 + 算法
  • 相关阅读:
    【JAVA基础】private 的使用
    【nginx】配置文件(模块、反向代理、负载均衡、动静分离)
    【Nginx】命令行安装
    【UNIAPP】websocte实现,功能:指定房间聊天,匿名进入 功能,文字与图片
    【前端JS】input对象图片在线转base64
    【UNIAPP】上传视频,进度条的前台与后端
    【IO阻塞异步】协程使用异步,异步爬虫,异步数据库操作
    【装饰器】原理以及基础使用
    可编程网络DataPath 及XDP
    gitlab 代码协作流程
  • 原文地址:https://www.cnblogs.com/IamThat/p/2943287.html
Copyright © 2020-2023  润新知