java jmf山寨QQ视频聊天实例源码介绍



java jmf山寨QQ视频聊天实例源码介绍。由于做山寨QQ视频聊天的需要,做了一个视频通信窗口组件。现在分享一下供大家学习……

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

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

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

效果图如下:

 

 

 

三个类 源代码如下:

 

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

http://www.iteye.com/topic/1098698