// Constructor public MediaPlayer(URL mediauUrl) { setLayout(new BorderLayout()); // use a BorderLayout // Use lightweight components for Swing compatibility Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, true); try { // create a player to play the media specified in the URL Player mediaPlayer = Manager.createRealizedPlayer(mediauUrl); // get the components for the video and the playback controls Component video = mediaPlayer.getVisualComponent(); Component control = mediaPlayer.getControlPanelComponent(); if (video != null) { add(video, BorderLayout.CENTER); // place the video component in the panel } if (control != null) { add(control, BorderLayout.SOUTH); // place the control component in the panel } mediaPlayer.start(); // start playing the media clip } catch (NoPlayerException noPlayerException) { System.err.println("No media player found: " + noPlayerException); } catch (CannotRealizeException cannotRealizeException) { System.err.println("Could not realize media player: " + cannotRealizeException); } catch (IOException iOException) { System.err.println("Error reading from the source: " + iOException); } }
public MediaPanel(URL mediaURL) { setLayout(new BorderLayout()); // use a BorderLayout // Use lightweight components for Swing compatibility Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, true); try { // create a player to play the media specified in the URL Player mediaPlayer = Manager.createRealizedPlayer(mediaURL); // get the components for the video and the playback controls Component video = mediaPlayer.getVisualComponent(); Component controls = mediaPlayer.getControlPanelComponent(); if (video != null) add(video, BorderLayout.CENTER); // add video component if (controls != null) add(controls, BorderLayout.SOUTH); // add controls mediaPlayer.start(); // start playing the media clip } // end try catch (NoPlayerException noPlayerException) { System.err.println("No media player found"); } // end catch catch (CannotRealizeException cannotRealizeException) { System.err.println("Could not realize media player"); } // end catch catch (IOException iOException) { System.err.println("Error reading from the source"); } // end catch } // end MediaPanel constructor
public static void stop() { try { Thread.sleep(5000); FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl"); Buffer buf = fgc.grabFrame(); BufferToImage btoi = new BufferToImage((VideoFormat) buf.getFormat()); player.stop(); Image img = btoi.createImage(buf); int w = img.getWidth(null); int h = img.getHeight(null); BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = bi.createGraphics(); g2.drawImage(img, 0, 0, null); g2.dispose(); try { ImageIO.write(bi, "jpg", new File("C:/ii.jpg")); } catch (IOException ex) { Logger.getLogger(Capture_video.class.getName()).log(Level.SEVERE, null, ex); } } catch (InterruptedException ex) { Logger.getLogger(Capture_video.class.getName()).log(Level.SEVERE, null, ex); } }
/** Crea Ftes new form PanelFilm */ public PanelFilm(URL mediaUrl) throws IOException { initComponents(); setLayout(new BorderLayout()); Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, true); drawFilm = new JPanel(); try { mediaPlayer = Manager.createRealizedPlayer(mediaUrl); System.out.println(Manager.createRealizedPlayer(mediaUrl).toString()); video = mediaPlayer.getVisualComponent(); System.out.println(mediaPlayer.getVisualComponent()); controls = mediaPlayer.getControlPanelComponent(); if (video != null) { drawFilm.add(video, BorderLayout.CENTER); } if (controls != null) { drawFilm.add(controls, BorderLayout.SOUTH); } this.setVisible(false); drawFilm.setVisible(true); mediaPlayer.start(); } catch (NoPlayerException noPlayerException) { noPlayerException.printStackTrace(); } catch (CannotRealizeException cannotRealizeException) { cannotRealizeException.printStackTrace(); } }
public void mouseDragged(MouseEvent e) { if (lecteur != null) { if (e.getSource() == deplacement) { if (e.getModifiers() == MouseEvent.BUTTON1_MASK) { lecteur.setMediaTime( new Time( (double) (deplacement.getValue() * lecteur.getDuration().getSeconds() / 100))); } } } }
public Capture_video() { try { // List out available Devices to Capture Video. Vector<CaptureDeviceInfo> list = CaptureDeviceManager.getDeviceList(format); System.out.println(CaptureDeviceManager.getDeviceList(null).toString()); // Iterating list for (CaptureDeviceInfo temp : list) { // Checking whether the current device supports VfW // VfW = Video for Windows if (temp.getName().startsWith("vfw:")) { System.out.println("Found : " + temp.getName().substring(4)); // Selecting the very first device that supports VfW cam = temp; System.out.println("Selected : " + cam.getName().substring(4)); break; } } System.out.println("Put it on work!..."); // Getting the MediaLocator for Selected device. // MediaLocator describes the location of media content locator = cam.getLocator(); if (locator != null) { // Create a Player for Media Located by MediaLocator player = Manager.createRealizedPlayer(locator); if (player != null) { // Starting the player player.start(); // Creating a Frame to display Video f.setTitle("Test Webcam"); f.setLayout(new BorderLayout()); // Adding the Visual Component to display Video captured by Player // from URL provided by MediaLocator f.add(player.getVisualComponent(), BorderLayout.CENTER); f.pack(); f.setAlwaysOnTop(true); f.setVisible(true); } } } catch (Exception e) { e.printStackTrace(); } }
private void initWebcam() { Vector videoDevices = CaptureDeviceManager.getDeviceList(new VideoFormat(null)); if (videoDevices.size() > 0) { webcam = (CaptureDeviceInfo) videoDevices.get(0); Format[] formats = webcam.getFormats(); Format selectedFormat = null; try { for (Format f : formats) { if (f.toString().contains("640") && f.toString().contains("480")) { selectedFormat = f; break; } } } catch (Exception e) { logger.error( "Failed to get required webcam resolution (640x480). Taking default format: " + e.getMessage()); selectedFormat = formats[0]; } try { webcamPlayer = Manager.createRealizedPlayer(webcam.getLocator()); FormatControl fc = (FormatControl) webcamPlayer.getControl("javax.media.control.FormatControl"); System.out.println("Selected webcam format: " + selectedFormat.toString()); fc.setFormat(selectedFormat); webcamPlayer.start(); webcamAvailable = true; Timer timer = new Timer(); timer.schedule( new TimerTask() { @Override public void run() { frameGrabber = (FrameGrabbingControl) webcamPlayer.getControl("javax.media.control.FrameGrabbingControl"); } }, 2500); } catch (Exception e) { logger.error("Failed to get webcam feed: " + e.getMessage()); } } else { logger.error("No webcam available"); } }
public void actionPerformed(ActionEvent ae) { if (ae.getSource() == stopButton) { if (player != null) { player.stop(); // NOTE: stop() is a synchronous method ! } } else { player.stop(); // NOTE: stop() is a synchronous method ! player.close(); // waitForState(player.Closed); System.out.print("Player Closed - Exiting"); System.exit(0); } }
/** 初始化播放器 */ public void initPlayer() { try { if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.close(); mediaPlayer = null; } if (lrcThread != null) { lrcThread = null; } } catch (Exception e) { e.printStackTrace(); } }
public void captureImage() { String savepath = this.saveDirectory + "\\cam" + this.getDateFormatNow("yyyyMMdd_HHmmss-S") + ".jpg"; System.out.println("Capturing current image to " + savepath); // Grab a frame FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl"); buf = fgc.grabFrame(); // Convert it to an image btoi = new BufferToImage((VideoFormat) buf.getFormat()); img = btoi.createImage(buf); // save image saveJPG(img, savepath); // show the image // imgpanel.setImage(img); // images.add(img); images.add(savepath); if (images_lastadded.size() >= lastadded_max) { // Remove last images_lastadded.remove(images_lastadded.size() - 1); } images_lastadded.add(0, images.size() - 1); images_nevershown.add(0, images.size() - 1); forceNewImage(); }
// Play starts the track from the beginning or from the last played part public void play() { try { player.start(); } catch (Exception e) { e.printStackTrace(); } }
// Stops the music from playing public void pause() { try { player.stop(); } catch (Exception e) { e.printStackTrace(); } }
public void stateChanged(ChangeEvent e) { if (lecteur != null) { if (e.getSource() == deplacement) { deplacement.setToolTipText(toString(lecteur.getMediaTime())); } } }
/** * Setting the encoding quality to the specified value on the JPEG encoder. 0.5 is a good default. */ void setJPEGQuality(Player p, float val) { Control cs[] = p.getControls(); QualityControl qc = null; VideoFormat jpegFmt = new VideoFormat(VideoFormat.JPEG); // Loop through the controls to find the Quality control for // the JPEG encoder. for (int i = 0; i < cs.length; i++) { if (cs[i] instanceof QualityControl && cs[i] instanceof Owned) { Object owner = ((Owned) cs[i]).getOwner(); // Check to see if the owner is a Codec. // Then check for the output format. 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("- Set quality to " + val + " on " + qc); break; } } } if (qc != null) break; } } }
/** * 快进 * * @param progress */ private void seekTo(int progress) { try { if (mediaPlayer != null) { // float playedRate = (float) progress / songInfo.getDuration(); // mediaPlayer.seekTo(playedRate); // mediaPlayer.stop(); double totalTime = mediaPlayer.getDuration().getSeconds(); double rate = progress * 1.00 / songInfo.getDuration(); mediaPlayer.setMediaTime(new Time(totalTime * rate)); // mediaPlayer.start(); MediaManage.getMediaManage().setPlayStatus(MediaManage.PLAYING); } } catch (Exception e) { e.printStackTrace(); } }
public Webcam(Player _player) { f = new Frame("SwingCapture"); setLayout(new BorderLayout()); setSize(640, 480); this.player = _player; Component comp; try { if ((comp = player.getVisualComponent()) != null) { add(comp, BorderLayout.CENTER); } } catch (Exception e) { e.printStackTrace(); } f.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { f.dispose(); // playerclose(); // System.exit(0); } }); f.add("Center", this); f.pack(); f.setSize(new Dimension(640, 480)); f.setVisible(true); FormatControl formatControl = (FormatControl) player.getControl("javax.media.control.FormatControl"); // player.stop(); Component co = formatControl.getControlComponent(); if (co != null) { player.stop(); JDialog d = new JDialog(f, "Format Control", true); f.add(co); f.pack(); f.setLocationRelativeTo(f); f.setVisible(true); f.dispose(); player.start(); } }
/** 初始化播放器 */ private void initMusic() { try { if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.close(); mediaPlayer = null; SongMessage msg = new SongMessage(); msg.setSongInfo(songInfo); msg.setType(SongMessage.SERVICEPAUSEEDMUSIC); ObserverManage.getObserver().setMessage(msg); } if (lrcThread != null) { lrcThread = null; } } catch (Exception e) { e.printStackTrace(); } }
public JMFMovie(File file) { try { player = Manager.createPlayer(file.toURI().toURL()); framePositioningControl = (FramePositioningControl) player.getControl(FramePositioningControl.class.toString()); frameGrabbingControl = (FrameGrabbingControl) player.getControl(FrameGrabbingControl.class.toString()); imageConverter = new BufferToImage( (VideoFormat) ((FormatControl) player.getControl(FormatControl.class.toString())).getFormat()); player.realize(); } catch (NoPlayerException e) { throw new RuntimeException(e); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
/** * Block until the processor has transitioned to the given state. Return false if the transition * failed. This is taken from Sun's examples. */ boolean waitForState(int state) { // synchronized (waitSync) { synchronized (this) { try { while (player.getState() != state && stateTransitionOK) // waitSync.wait(); this.wait(); } catch (Exception e) { } } return stateTransitionOK; }
/** @param args */ public static void main(String[] args) { String url = "rtp://192.168.1.1:22224/audio/16"; MediaLocator mrl = new MediaLocator(url); // Create a player for this rtp session Player player = null; try { player = Manager.createPlayer(mrl); } catch (NoPlayerException e) { e.printStackTrace(); System.exit(-1); } catch (MalformedURLException e) { e.printStackTrace(); System.exit(-1); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } if (player != null) { System.out.println("Player created."); player.realize(); // wait for realizing while (player.getState() != Controller.Realized) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Starting player"); player.start(); } else { System.err.println("Player doesn't created."); System.exit(-1); } System.out.println("Exiting."); }
public void addVisualElements() { // so we now we can ask for the visual component visualComponent = player.getVisualComponent(); if (visualComponent != null) { add(visualComponent, BorderLayout.CENTER); } // and get the control panel visual component too controlPanelComponent = player.getControlPanelComponent(); if (controlPanelComponent != null) { add(controlPanelComponent, BorderLayout.SOUTH); } /* Now I'll try to get Sun's proprietary component that shows me how the JMF has plugged the application together */ if ((jmdControl = player.getControl("com.sun.media.JMD")) != null) { System.err.println("Found Sun's JMD Control"); if ((jmdVisualComponent = jmdControl.getControlComponent()) != null) { add(jmdVisualComponent, BorderLayout.NORTH); } } pack(); }
public static void main(String args[]) throws Exception { // Take the path of the audio file from command line File f = new File("C:\\Users\\Larry\\AppData\\Local\\Temp\\jgoogle_tts-588881786930740869.mp3"); // Create a Player object that realizes the audio final Player p = Manager.createRealizedPlayer(f.toURI().toURL()); // Start the music p.start(); // Create a Scanner object for taking input from cmd Scanner s = new Scanner(System.in); // Read a line and store it in st String st = s.nextLine(); // If user types 's', stop the audio if (st.equals("s")) { p.stop(); } }
public void capture(String device) { CaptureDeviceInfo deviceInfo = CaptureDeviceManager.getDevice(device); System.out.println("-----------------------------------------------------------"); System.out.println("CaptureDevice Name is " + deviceInfo.getName()); System.out.println("-----------------------------------------------------------"); System.out.println("CaptureDevice is " + deviceInfo); System.out.println("-----------------------------------------------------------"); Format[] formatsSupported = deviceInfo.getFormats(); System.out.println("Supports " + formatsSupported.length + " formats"); for (int findex = 0; findex < formatsSupported.length; findex++) { System.out.println("Unique encoding name is " + formatsSupported[findex].getEncoding()); System.out.println("Format attributes are " + formatsSupported[findex]); } System.out.println("-----------------------------------------------------------"); System.out.println("Media Locator is " + deviceInfo.getLocator()); System.out.println("***********************************************************"); try { player = Manager.createPlayer(deviceInfo.getLocator()); } catch (java.io.IOException e) { System.out.println("IOException"); } catch (javax.media.NoPlayerException npe) { System.out.println("NoPlayerException"); } player.addControllerListener(this); System.out.println("About to call start on player"); player.realize(); waitForState(player.Realized); addVisualElements(); setVisible(true); player.start(); System.out.println("Called start on player"); waitForState(player.Started); System.out.println("Player started"); }
protected void layout1024v2() { // Resolution of the camera pictures divided by 2 // 320x240, Creative camera for layout1280 size_x = 320; size_y = 240; sizeCaptureWindow_x = size_x; sizeCaptureWindow_y = size_y; imagepanels = new WebcamCaptureAndFadeImagePanel[1]; imagepanels[0] = new WebcamCaptureAndFadeImagePanel(1, 1, size_x, size_y); setLayout(new BorderLayout()); setSize((4 + 2 + 4) * size_x, (6) * size_y); add(imagepanels[0], BorderLayout.WEST); if ((comp = player.getVisualComponent()) != null) { add(comp, BorderLayout.EAST); } enable_datetext = false; enable_forceNewImage = true; enable_forceNewImageNow = true; captureWindow = false; txt_location_x = txt_location_y = 0; txt_size_x = 18; txt_size_y = size_y; number_of_frames_betweencaptures = 0 * fps; // Number of frame to wait between captures number_of_frames_before_cwopen = 0 * fps; // Number of frames to wait before we allow capturewindow to be opened number_of_frames_showimage = 600 * fps; // Number of frames to hold the image before fading to next number_of_frames_redborder = (int) 0.5 * fps; // Number of frames the red border should last, -1 to disable number_of_second_showcapturetext = 0.1; // Number of seconds to show a text after capture, 0 for none fade_per_frame = 0.50f; // Short fading }
protected void layout1280() { // Resolution of the camera pictures divided by 2 // 320x240, Creative camera for layout1280 size_x = 320 / 2; size_y = 240 / 2; sizeCaptureWindow_x = size_x * 2; sizeCaptureWindow_y = size_y * 2; imagepanels = new WebcamCaptureAndFadeImagePanel[4]; imagepanels[0] = new WebcamCaptureAndFadeImagePanel(3, 8, size_x, size_y); imagepanels[1] = new WebcamCaptureAndFadeImagePanel(2, 3, size_x, size_y); imagepanels[2] = new WebcamCaptureAndFadeImagePanel(2, 3, size_x, size_y); imagepanels[3] = new WebcamCaptureAndFadeImagePanel(3, 8, size_x, size_y); setLayout(new BorderLayout()); setSize((4 + 2 + 4) * size_x, (6) * size_y); add(imagepanels[0], BorderLayout.WEST); JPanel middle = new JPanel(new BorderLayout()); middle.add(imagepanels[1], BorderLayout.NORTH); if ((comp = player.getVisualComponent()) != null) { middle.add(comp, BorderLayout.CENTER); } middle.add(imagepanels[2], BorderLayout.SOUTH); middle.setSize(new Dimension(4 * size_x, 2 * size_y)); add(middle, BorderLayout.CENTER); add(imagepanels[3], BorderLayout.EAST); enable_datetext = false; enable_forceNewImage = false; captureWindow = false; txt_location_x = txt_location_y = 0; txt_size_x = 18; txt_size_y = size_y; }
/** * Casts the Controller to a Player, calls start(), and blocks the current thread until the player * is Started. * * @return boolean indicating whether the transition was successful. * @exception ClassCastException If the Controller is not a Player */ public boolean blockingStart() { setState(Controller.Started); Player player = (Player) controller; player.start(); return waitForState(); }
// returns the length of the track in the form of seconds public double getTime() { return player.getDuration().getSeconds(); }
// Stops the track, resets it to the beginning public void rewind() { player.stop(); player.setMediaTime(Player.RESET); }
/** * 播放歌曲 * * @param songInfo */ private void playInfoMusic(SongInfo msongInfo) { this.songInfo = msongInfo; if (songInfo == null) { SongMessage msg = new SongMessage(); msg.setType(SongMessage.SERVICEERRORMUSIC); msg.setErrorMessage(SongMessage.ERRORMESSAGEPLAYSONGNULL); ObserverManage.getObserver().setMessage(msg); return; } File songFile = new File(songInfo.getFilePath()); if (!songFile.exists()) { logger.error("播放文件不存在!"); // 下一首 SongMessage songMessage = new SongMessage(); songMessage.setType(SongMessage.NEXTMUSIC); ObserverManage.getObserver().setMessage(songMessage); return; } try { if (mediaPlayer == null) { // mediaPlayer = new MediaPlayer(); // // mediaPlayer.setDataSource(songInfo.getFilePath()); // // // // float playedRate = (float) songInfo.getPlayProgress() // // / songInfo.getDuration(); // // mediaPlayer.seekTo(playedRate); // mediaPlayer.setMediaLocator(new MediaLocator(songInfo // .getFilePath())); File file = new File(songInfo.getFilePath()); mediaPlayer = Manager.createRealizedPlayer(new MediaLocator(file.toURL())); initVolume(); mediaPlayer.prefetch(); // 获取媒体数据 double totalTime = mediaPlayer.getDuration().getSeconds(); double rate = songInfo.getPlayProgress() * 1.00 / songInfo.getDuration(); mediaPlayer.setMediaTime(new Time(totalTime * rate)); mediaPlayer.prefetch(); mediaPlayer.start(); } } catch (Exception e) { logger.error("不能播放此文件:" + songInfo.getFilePath()); e.printStackTrace(); SongMessage songMessage = new SongMessage(); songMessage.setType(SongMessage.NEXTMUSIC); ObserverManage.getObserver().setMessage(songMessage); } if (mediaPlayer != null) { mediaPlayer.addControllerListener( new ControllerListener() { @Override public void controllerUpdate(ControllerEvent e) { // 当媒体播放结束时 if (e instanceof EndOfMediaEvent) { mediaPlayer.setMediaTime(new Time(0)); mediaPlayer = null; SongMessage songMessage = new SongMessage(); songMessage.setType(SongMessage.NEXTMUSIC); ObserverManage.getObserver().setMessage(songMessage); } } }); // mediaPlayer.setOnCompletionListener(new OnCompletionListener() { // // @Override // public void onProgressChanged() { // // float playedRate = mediaPlayer.getPlayedRate(); // // long playProgress = (long) (songInfo.getDuration() * playedRate); // // if (songInfo != null) { // songInfo.setPlayProgress(playProgress); // SongMessage msg = new SongMessage(); // msg.setSongInfo(songInfo); // msg.setType(SongMessage.SERVICEPLAYINGMUSIC); // ObserverManage.getObserver().setMessage(msg); // } // } // // @Override // public void onCompletion() { // // SongMessage songMessage = new SongMessage(); // songMessage.setType(SongMessage.NEXTMUSIC); // ObserverManage.getObserver().setMessage(songMessage); // } // }); } if (lrcThread == null) { lrcThread = new Thread(new LrcRunable()); lrcThread.start(); } }
/** 初始化声音 */ protected void initVolume() { if (mediaPlayer != null) { mediaPlayer.getGainControl().setLevel((float) (Constants.volumeSize * 1.0 / 100)); } }