JavaMedia.java
Upload User: cdlibang
Upload Date: 2016-07-17
Package Size: 774k
Code Size: 19k
Category:

2D Graphic

Development Platform:

Java

  1. /*
  2.  * @(#)JavaMedia.java 1.21 99/08/16
  3.  *
  4.  * Copyright (c) 1998, 1999 by Sun Microsystems, Inc. All Rights Reserved.
  5.  * 
  6.  * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
  7.  * modify and redistribute this software in source and binary code form,
  8.  * provided that i) this copyright notice and license appear on all copies of
  9.  * the software; and ii) Licensee does not utilize the software in a manner
  10.  * which is disparaging to Sun.
  11.  * 
  12.  * This software is provided "AS IS," without a warranty of any kind. ALL
  13.  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
  14.  * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
  15.  * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
  16.  * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
  17.  * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
  18.  * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
  19.  * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
  20.  * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
  21.  * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
  22.  * POSSIBILITY OF SUCH DAMAGES.
  23.  * 
  24.  * This software is not designed or intended for use in on-line control of
  25.  * aircraft, air traffic, aircraft navigation or aircraft communications; or in
  26.  * the design, construction, operation or maintenance of any nuclear
  27.  * facility. Licensee represents and warrants that it will not use or
  28.  * redistribute the Software for such purposes.
  29.  */
  30. package demos.Mix;
  31. import java.applet.*;
  32. import java.awt.*;
  33. import java.awt.event.*;
  34. import javax.swing.*;
  35. import javax.swing.event.*;
  36. import javax.swing.border.*;
  37. import java.awt.image.BufferedImage;
  38. import java.net.URL;
  39. import java.util.Hashtable;
  40. import java.util.Enumeration;
  41. import CustomControls;
  42. import Java2DemoApplet;
  43. import DemoImages;
  44. /* UNCOMMENT TO USE JMF
  45. import javax.media.*;
  46. import com.sun.media.*;
  47. END UNCOMMENT*/
  48. /**
  49.    JavaMedia example to show effects of sound and jmf with 2D animation.
  50.    Java Media Framework 1.02 extension or later required.
  51.    http://java.sun.com/products/java-media/jmf/index.html
  52.    Running requires editing this file to comment out some source and uncomment 
  53.    the JMF specific source.
  54.        Look for the UNCOMMENT TO USE JMF text.
  55.        Look for the REMOVE TO USE JMF text
  56.    For media use the Sample1.mov & Sample2.mpg in the JMF/samples/media 
  57.    directory and then copy the two sample files to the Java2D/media directory.
  58.    Setup to use JMF.
  59.    After editing this file :
  60.        Extract the contents of Java2Demo.jar, run this command from the 
  61.        Java2D directory :
  62.            jar xvf Java2Demo.jar
  63.        For win32 :
  64.            javac srcdemosMixJavaMedia.java -d .
  65.        For solaris :
  66.            javac src/demos/Mix/JavaMedia.java -d .
  67.    Run without the Java2Demo.jar JarFile context :
  68.            java demos.Mix.JavaMedia
  69.            java DemoGroup Mix
  70.            java Java2Demo 
  71. */
  72. public class JavaMedia extends JPanel implements ChangeListener, CustomControls, Runnable {
  73.     ImageIcon stopIcon, startIcon, loopIcon, loopingIcon;
  74.     String playType[] = {"mix1", "mix2", "rmf"};
  75.     String playList[][] = {
  76.                 {"sfx-medley.rmf", "trippygaia1.mid", "spacemusic.au"},
  77.                 {"bong.wav", "bark.aiff", "trance.rmf"},
  78.                 {"ambient.rmf", "classical.rmf", "modern-rock.rmf"}};
  79.     JavaSound jsound[] = new JavaSound[9];
  80.     private Font f1 = new Font("serif", Font.BOLD + Font.ITALIC, 18);
  81.     private Hashtable jmftable = new Hashtable(2);
  82.     private Thread thread;
  83.     private JTabbedPane tabbedPane;
  84.     public JavaMedia() {
  85.         setLayout(new BorderLayout());
  86.         setBackground(Color.gray);
  87.         stopIcon = new ImageIcon(DemoImages.getImage("stop2.gif",this));
  88.         startIcon = new ImageIcon(DemoImages.getImage("start2.gif",this));
  89.         loopIcon = new ImageIcon(DemoImages.getImage("loop.gif",this));
  90.         loopingIcon = new ImageIcon(DemoImages.getImage("looping.gif",this));
  91.         tabbedPane = new JTabbedPane();
  92.         tabbedPane.setBorder(new BevelBorder(BevelBorder.RAISED));
  93.         tabbedPane.setFont(new Font("Times New Roman", Font.PLAIN, 10));
  94.         Color c[] = {Color.cyan, Color.yellow, Color.pink};
  95.         for (int i = 0, k = 0; i < playType.length; i++) {
  96.             JPanel jp = new JPanel(new GridLayout(0,1));
  97.             for (int j = 0; j < playList[i].length; j++) {
  98.                 jp.add(jsound[k++] = new JavaSound(playList[i][j],c[j%3]));
  99.             }
  100.             tabbedPane.addTab(playType[i], jp);
  101.         }
  102.         JMF jmf = new JMF("Sample1.mov");
  103.         jmftable.put("mov", jmf);
  104.         tabbedPane.addTab("mov", jmf);
  105.         jmftable.put("mpg", jmf = new JMF("Sample2.mpg"));
  106.         tabbedPane.addTab("mpg", jmf);
  107.         tabbedPane.addChangeListener(this);
  108.         add(tabbedPane);
  109.         JPanel jp1 = new JPanel(new GridLayout(0,1));
  110.         String s1[] = { "J", "A", "V", "A" };
  111.         for (int i = 0; i < s1.length; i++) {
  112.             jp1.add(addLabel(s1[i]));
  113.         }
  114.         add("West", jp1);
  115.         JPanel jp2 = new JPanel(new GridLayout(0,1));
  116.         String s2[] = { "M", "E", "D", "I", "A" };
  117.         for (int i = 0; i < s2.length; i++) {
  118.             jp2.add(addLabel(s2[i]));
  119.         }
  120.         add("East", jp2);
  121.         addMouseListener(new MouseAdapter() {
  122.             public void mouseClicked(MouseEvent e) {
  123.                 if (thread == null) start(); else stop();
  124.             }
  125.         });
  126.     }
  127.     public String[] getCustomControlsConstraints() {
  128.         return new String[] { BorderLayout.NORTH };
  129.     }
  130.     public Component[] getCustomControls() {
  131.         // do nothing panel
  132.         JPanel p = new JPanel();
  133.         p.setVisible(false);
  134.         return new Component[] { (Component) p };
  135.     }
  136.     public void customControlsThread(int state) {
  137.         if (state == CustomControls.START) {
  138.             start();
  139.         } else if (state == CustomControls.STOP) {
  140.             stop();
  141.         }
  142.     }
  143.     public void start() {
  144.         if (thread != null) {
  145.             return;
  146.         }
  147.         thread = new Thread(this);
  148.         thread.setPriority(Thread.MIN_PRIORITY);
  149.         thread.setName("Mix.JavaMedia Thread");
  150.         thread.start();
  151.     }
  152.     public synchronized void stop() {
  153.         if (thread != null) {
  154.             thread.interrupt();
  155.         }
  156.         thread = null;
  157.     }
  158.     public void run() {
  159.         Thread me = Thread.currentThread();
  160.         try { thread.sleep(333); } catch (Exception e) { return; }
  161.         while (thread == me) {
  162.             for (int i = 0; i < tabbedPane.getTabCount() && thread == me; i++) {
  163.                 Object obj = tabbedPane.getComponent(i);
  164.                 tabbedPane.setSelectedIndex(i);
  165.                 if (obj instanceof Panel) {
  166. /* UNCOMMENT TO USE JMF
  167.                     JMF jmf = (JMF) jmftable.get(tabbedPane.getTitleAt(i));
  168.                     while (!jmf.rewoundToggle) {
  169.                         try {
  170.                             thread.sleep(250);
  171.                         } catch (InterruptedException e) {  break; }
  172.                     }
  173.                     jmf.stop();
  174.                     jmf.rewoundToggle = false;
  175. END UNCOMMENT*/
  176.                 } else if (obj instanceof JPanel) {
  177.                     JPanel p = (JPanel) obj;
  178.                     for (int j = 0; j < p.getComponentCount() && thread == me; j++) {
  179.                         JavaSound js = (JavaSound) p.getComponent(j);
  180.                         js.loopB.doClick();
  181.                         try {
  182.                             thread.sleep(7777);
  183.                         } catch (InterruptedException e) { }
  184.                         js.startStopB.doClick();
  185.                     }
  186.                 }
  187.             }
  188.         }
  189.         thread = null;
  190.     }
  191.     public JLabel addLabel(String s) {
  192.         JLabel l = new JLabel(" " + s + " ");
  193.         l.setForeground(Color.gray);
  194.         l.setFont(f1);
  195.         return l;
  196.     }
  197.     public void stateChanged(ChangeEvent e) {
  198. /* UNCOMMENT TO USE JMF
  199.         for (Enumeration enum = jmftable.elements(); enum.hasMoreElements();) {
  200.             ((JMF) enum.nextElement()).stop();
  201.         }
  202.         JTabbedPane tabbedPane = (JTabbedPane) e.getSource();
  203.         int index = tabbedPane.getSelectedIndex();
  204.         String title = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
  205.         if (title == "mov" || title == "mpg") {
  206.             stopJavaSound();
  207.             ((JMF) jmftable.get(title)).start();
  208.         } 
  209. END UNCOMMENT */
  210.     }
  211.     public void stopJavaSound() {
  212.         for (int i = 0; i < jsound.length; i++) {
  213.             if (jsound[i].audioState != jsound[i].STOP ) {
  214.                 jsound[i].stopAudio();
  215.             }
  216.         }
  217.     }
  218.     public URL getURL(String dir, String name) {
  219.         URL url = null;
  220.         if (Java2DemoApplet.applet != null) {
  221.             try { 
  222.                 url = new URL(Java2DemoApplet.applet.getCodeBase(), dir + name);
  223.             } catch (Exception ex) { ex.printStackTrace(); }
  224.         } else {
  225.             try {
  226.                 dir = System.getProperty("user.dir") + "/" + dir;
  227.                 url = new URL("file:" + dir + name);
  228.             } catch (Exception ex) { ex.printStackTrace(); }
  229.         }
  230.         return url;
  231.     }
  232.     public static void main(String args[]) {
  233.         JFrame f = new JFrame("Java2D Demo - JavaMedia");
  234.         f.addWindowListener(new WindowAdapter() {
  235.             public void windowClosing(WindowEvent e) {System.exit(0);}
  236.         });
  237.         final JavaMedia demo = new JavaMedia();
  238.         f.getContentPane().add("Center", demo);
  239.         f.pack();
  240.         Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
  241.         int WIDTH = 310;
  242.         int HEIGHT = 280;
  243.         f.setLocation(screenSize.width/2 - WIDTH/2,
  244.                           screenSize.height/2 - HEIGHT/2);
  245.         f.setSize(WIDTH, HEIGHT);
  246.         f.show();
  247.         for (int i = 0; i < args.length; i++) {
  248.             if (args[i].startsWith("-run")) {
  249.                 demo.start();
  250.             }
  251.         }
  252.     }
  253.     public class JavaSound extends JPanel implements ActionListener {
  254.         AudioClip clip = null;
  255.         JButton startStopB, loopB;
  256.         Timer timer = null;
  257.         final int STOP = 0;
  258.         final int PLAY = 1;
  259.         final int LOOP = 2;
  260.         int audioState = STOP;
  261.         public JavaSound(String name, Color color) {
  262.             clip = Applet.newAudioClip(getURL("media/", name));
  263.             EmptyBorder eb = new EmptyBorder(2,5,2,5);
  264.             SoftBevelBorder sbb = new SoftBevelBorder(SoftBevelBorder.RAISED);
  265.             setBorder(new CompoundBorder(eb, sbb));
  266.             setLayout(new BorderLayout());
  267.     
  268.             JPanel p = new JPanel(new BorderLayout());
  269.             p.setBackground(Color.gray);
  270.             p.setLayout(new BorderLayout());
  271.             JLabel l = new JLabel(name);
  272.             l.setHorizontalAlignment(l.CENTER);
  273.             l.setFont(new Font("serif",Font.BOLD, 14));
  274.             l.setForeground(color);
  275.             p.add("North", l);
  276.     
  277.             JPanel p1 = new JPanel(new FlowLayout());
  278.             p1.setBackground(Color.gray);
  279.             startStopB = new JButton(startIcon);
  280.             startStopB.setPreferredSize(new Dimension(30, 20));
  281.             startStopB.setMargin(new Insets(0,0,0,0));
  282.             startStopB.addActionListener(this);
  283.             p1.add(startStopB);
  284.     
  285.             loopB = new JButton(loopIcon);
  286.             loopB.setMargin(new Insets(0,0,0,0));
  287.             loopB.setPreferredSize(new Dimension(30, 20));
  288.             loopB.addActionListener(this);
  289.             p1.add(loopB);
  290.     
  291.             timer = new Timer(this, clip, color);
  292.             p1.add(timer);
  293.     
  294.             p.add(p1);
  295.             JToolBar toolbar = new JToolBar();
  296.             toolbar.setBackground(Color.gray);
  297.             toolbar.add(p);
  298.             add(toolbar);
  299.         }
  300.     
  301.     
  302.         public JButton addButton(ImageIcon ii) {
  303.             JButton b = new JButton(ii);
  304.             b.addActionListener(this);
  305.             return b;
  306.         }
  307.     
  308.         public void stopAudio() {
  309.             audioState = STOP;
  310.             clip.stop();
  311.             loopB.setIcon(loopIcon);
  312.             startStopB.setIcon(startIcon);
  313.             timer.stop();
  314.         }
  315.     
  316.         public void playAudio() {
  317.             clip.play();
  318.             startStopB.setIcon(stopIcon);
  319.             audioState = PLAY;
  320.             timer.start();
  321.         }
  322.     
  323.     
  324.         public void actionPerformed(ActionEvent evt) {
  325.             if (evt.getSource().equals(loopB)) {
  326.                 clip.loop();
  327.                 audioState = LOOP;
  328.                 timer.start();
  329.                 loopB.setIcon(loopingIcon);
  330.                 startStopB.setIcon(stopIcon);
  331.             } else if (audioState >= PLAY) {
  332.                 stopAudio();
  333.             } else {
  334.                 playAudio();
  335.             }
  336.         }
  337.     
  338.     
  339.     
  340.         /**
  341.          * Render the elapsed seconds of the clip during playback.
  342.          */
  343.         public class Timer extends JComponent implements Runnable {
  344.     
  345.             private AudioClip clip;
  346.             private boolean cbStop = true;
  347.             private JavaMedia jm; 
  348.             private JavaSound js;
  349.             private BufferedImage bimg;
  350.             private Thread thread;
  351.             private int theSeconds;
  352.             private int w, h;
  353.             private Font font = new Font("Dialog", Font.BOLD, 12);
  354.             private Color color;
  355.     
  356.     
  357.             public Timer(JavaSound js, AudioClip clip, Color color) {
  358.                 this.js = js;
  359.                 this.clip = clip;
  360.                 this.color = color;
  361.                 setBackground(Color.black);
  362.                 setPreferredSize(new Dimension(30, 20));
  363.             }
  364.     
  365.             public void start() {
  366.                 thread = new Thread(this);
  367.                 thread.setPriority(Thread.MIN_PRIORITY);
  368.                 thread.setName("Mix.JavaMedia.JavaSound.Timer");
  369.                 thread.start();
  370.                 theSeconds = 0;
  371.             }
  372.     
  373.             public synchronized void stop() {
  374.                 thread = null;
  375.                 notifyAll();
  376.             }
  377.     
  378.     
  379.             public void run() {
  380.     
  381.                 while (js.audioState != js.STOP) {
  382.                     repaint();
  383.                     try {
  384.                         for (int i=0; i < 10 && js.audioState != js.STOP; i++) {
  385.                             Thread.sleep(95);  // 95x10=950ms; almost a second
  386.                         }
  387.                     } catch(InterruptedException e){ break;}
  388.                     if (theSeconds++ > 99) {
  389.                         theSeconds = 0;
  390.                     }
  391.                 }
  392.                 if (js.audioState != js.STOP) {
  393.                     js.stopAudio();
  394.                 }
  395.                 theSeconds = 0;
  396.                 repaint();
  397.             }
  398.     
  399.     
  400.             public void paint(Graphics g) {
  401.                 if (bimg == null) {
  402.                     bimg = (BufferedImage) createImage(30, 20);
  403.                 }
  404.                 int w = bimg.getWidth();
  405.                 int h = bimg.getHeight();
  406.                 Graphics2D big = bimg.createGraphics();
  407.                 big.setBackground(Color.black);
  408.                 big.clearRect(0,0,w,h);
  409.                 big.setFont(font);
  410.                 big.setColor(color);
  411.                 big.drawString(String.valueOf(theSeconds), 8,15);
  412.                 big.setColor(Color.gray);
  413.                 big.drawLine(0,0, 0,h-1);
  414.                 big.drawLine(0,0, w-1,0);
  415.                 big.setColor(Color.white);
  416.                 big.drawLine(w-1,0, w-1,h-1);
  417.                 big.drawLine(0,h-1, w-1,h-1);
  418.                 g.drawImage(bimg, 0, 0, this);
  419.                 big.dispose();
  420.             }
  421.         }  // End Timer class
  422.     }  // End JavaSound class
  423. // REMOVE TO USE JMF
  424.     public class JMF extends JScrollPane {
  425.         public JMF(String name) {
  426.             String fs = System.getProperty("file.separator");
  427.             String s = "Java Media Frameworkn" +
  428.                 "http://java.sun.com/products/java-media/jmfnn" +
  429.                 "Usage Instructions in n" +
  430.                 "Java2D" + fs + "src" + fs + "demos" + fs + 
  431.                 "Mix" + fs + "JavaMedia.javan";
  432.     JTextArea textarea = new JTextArea(s);
  433.             textarea.setFont(new Font("serif", Font.PLAIN, 10));
  434.             textarea.setEditable(false);
  435.     getViewport().add(textarea);
  436.         }
  437.     }
  438. // REMOVE TO HERE
  439. /* UNCOMMENT TO USE JMF
  440.     public class JMF extends Panel implements ControllerListener {
  441.         
  442.         Player player;
  443.         boolean rewoundToggle;
  444.     
  445.         public JMF(String name) {
  446.             setLayout(new BorderLayout());
  447.             URL url = getURL("media/", name);
  448.             if (url != null) {
  449.                 try {
  450.                     player = Manager.createPlayer(url);
  451.                 } catch (Exception e) {
  452.                     System.err.println("Can't create Manager because: " + e);
  453.                 }
  454.                 player.addControllerListener(this);
  455.             } else {
  456.                 String fs = System.getProperty("file.separator");
  457.                 String s = "Couldn't locate : n" +
  458.                 "Java2D" + fs + "demos" + fs + "Mix" + fs + name;
  459.         JTextArea textarea = new JTextArea(s);
  460.                 textarea.setFont(new Font("serif", Font.PLAIN, 10));
  461.                 textarea.setEditable(false);
  462.         JScrollPane scroller = new JScrollPane();
  463.         scroller.getViewport().add(textarea);
  464.         add(scroller);
  465.             }
  466.         }
  467.     
  468.         public void start() {
  469.             invalidate();
  470.             if (player != null) {
  471.                 player.start();
  472.             }
  473.             validate();
  474.         }
  475.         public void stop() {
  476.             if (player != null && player.getState() == player.Started) {
  477.                 player.stop();
  478.                 player.deallocate();
  479.             }
  480.         }
  481.         public synchronized void controllerUpdate(ControllerEvent event) {
  482.             // If we're getting messages from a dead player, just leave
  483.             if (player == null)
  484.                 return;
  485.             // When the player is Realized, get the visual 
  486.             // and control components and add them to the Panel
  487.             if (event instanceof RealizeCompleteEvent) {
  488.                 add(player.getVisualComponent());
  489.                 add("South", player.getControlPanelComponent());
  490.                 validate();
  491.             } else if (event instanceof EndOfMediaEvent) {
  492.                 // We've reached the end of the media; rewind & start over
  493.                 rewoundToggle = true;
  494.                 player.setMediaTime(new Time(0));
  495.                 player.start();
  496.             } else if (event instanceof ControllerErrorEvent) {
  497.                 player = null;
  498.             }
  499.         }
  500.     } // End JMF class
  501. END UNCOMMENT */
  502. } // End JavaMedia class