Multimedia

How can you play a .au file?


(Submitted by Nelson Yu)
There are two main ways to play an .au file in an applet(in a stand-alone application you will need to use the undocumentated sun.* classes or write your own audio handler).

1) Play the audio directly

play(URL)
play(URL, string)

//  say audio file is located at http://java.sun.com/ 
// which is the documentation base
play(getDocumentBase(), "myLittleAudio.au");
otherwise if its located in a 'audio' directory you will need create a new url i.e
URL u = new URL(getDocumentBase().toString() + "/audio");
2) Get the audio clip then play it later(or have it loop)

getAudioClip(URL)
getAudioClip(URL, string)

used in the same manner as above, but instead it will return an AudioClip(which is an interface) in much the same way as getAppletContext() returns an AppletContext even though AppletContext is an interface.

getAudioClip(getDocumentBase(), "myLittleAudio.au").loop();
(Submitted by William S. Clark)
This will play an .au file:

import java.io.InputStream;
import java.net.*;
import java.applet.*;
import java.awt.Graphics;
import java.awt.Color;

public class Message extends java.applet.Applet {
  private String file;
  private AudioClip source;

  public void init() {
    setBackground(new Color(0));
    file=getParameter("FILE");
    source=getAudioClip(getDocumentBase(),file);
  }
  
  public void start() {
    if(source!=null) source.play();
  }

  public void stop() {
    if(source!=null) source.stop();
  }

}
(Submitted by Steve Alexander)
Using the AudioClip class and several Applet-specific methods, it is quite easy to retrieve and play an ".au" audio file.

The code sample below is not robust (exception handling and null-checking are not present) but it is a simple example of the basic process involved in getting an audio object, and playing that file.

The key objects and methods used are AudioClip, loop() and stop(). Another method not used here but perhaps of some value is the play() method which plays an audio clip one time.

import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.*;

public class PlayAudio extends Applet
{

    AudioClip myAudio;
    Button b_play;
    Button b_stop;
    String textString;

     public void init()
     {
        resize(300, 100);

        b_play = new Button("Play audio");
        b_stop = new Button("Stop audio");

        myAudio = getAudioClip(getDocumentBase(), "computer.au");

        add(b_play);
        add(b_stop);
     }

     public void start()
     {
     }

     public void paint(Graphics g)
     {
        g.setColor(Color.blue);
        g.drawString(textString, 100,75);
     }

    public boolean action(Event e, Object arg)
    {
        if(e.target instanceof Button)
        {
            if("Play audio" == arg)
            {
                myAudio.loop();
                textString = "Playing audio...";
            }
            if("Stop audio" == arg)
            {
                myAudio.stop();
                textString = "Not playing audio...";
            }
         }
         repaint();
         return true;
     }
}

How can you play a .wav file?


(Submitted by Hui Zhao Wang, and others)
To convert .wav to .au files, check out GoldWave 2.14 (not the latest version which writes invalid .au files). It's available from :

http://www.cs.mun.ca/~chris3/goldwave/


How can you play a .midi file?


(Submitted by Mike Hippolyte)
The Java MIDI software is at http://www.interport.net/~mash/javamidi.html and a keyboard applet that uses Java MIDI is at http://www.interport.net/~mash/midikeyboard.html.
(Submitted by Jeff Harrington)
You can use Csound, a digital audio compiler, to convert MIDI files to .wav files. From .wav files you can use Sox or another converter program. Csound is available here. I've got a demo of Csound audio and a Java applet at my site.

How can you play a .mov file?



How can you play a .mpeg file?



How many sound channels do I have in Java?



How does one (use Toolkit.sync() to?) flush the buffer of things to be drawn and hence bring the display up to date?


(Submitted by Adam Moss)
getToolkit().sync(). However, in a tight loop there seems to be a high performance hit on Windows95, particularly in terms of event-passing.

How do I play a .avi file?



How do I get an applet to sleep until an image has loaded?


(Submitted by John Zukowski)
MediaTracker tracker;

image = getImage (getDocumentBase(), "image.jpg");

tracker = new MediaTracker (this);
tracker.addImage (image, 0);
// waitForAll will block the ENTIRE applet
try { tracker.waitForAll();} catch (Exception e) {}
(Submitted by Bryan Smith)
The java.awt.MediaTracker class can be used to suspend applet execution until an image or series of images has been loaded, as in the following code segment:
public class ImageLoadingApplet extends Applet
{
    Image img;

    MediaTracker img_tracker;
    ...

    public void init()
    {
        img_tracker = new MediaTracker(this);

        // Start loading image and register it
        // with the MediaTracker object.
        img = getImage(getCodeBase, "images/img.gif");
        img_tracker.add(img,0);

        // Wait until image loaded before proceeding.
        try
        {
            img_tracker.waitForID(0);
        }
        catch (InterruptedException e)
        {
            // exception handling
        }

        ...
    }
...
}
A more in-depth example of the use of MediaTracker is in Sun's API documentation at: http://java.sun.com/JDK-1.0/api/java.awt.MediaTracker.html.
(Submitted by Guohua Li)
Check out my homepage. I have source code there: http://enuxsa.eas.asu.edu/~guohua.

How can I display a GIF or JPEG-image coming from a byte[]-buffer?


(Submitted by Jeff Marin)
MemoryImageSource has six constructors, all of which take either an array of int of BYTE. Just remember, after you create an instance of MemoryImageSource, to actually create an image you must do the following:
Image m_RotImage = createImage(
	new MemoryImageSource(m_width, m_height, pix_dest, 0, m_width));

How do I load an Image into a standalone Java application panel (i.e. one that does not have a base URL)?


(Submitted by Anujit Sarkar)
import java.awt.*;
import java.awt.image.*;

public class ImageWindow extends Frame 
{
	Image im=null;

	public ImageWindow()
	{
	}
    
	public void createImage()
	{
		im = getToolkit().getImage("b01.gif");
	}

	public void paint(Graphics g)
	{
		update(g);
	}

	public void update(Graphics g)
	{
		g.drawImage(im, 0, 0, this);
	}

	public boolean handleEvent(Event evt)
	{
		if (evt.id == Event.WINDOW_DESTROY) 
		{
			System.exit(0);
		}
		return super.handleEvent(evt);
	}

	public static void main(String args[]) 
	{
		ImageWindow window = new ImageWindow();
		window.createImage();
		window.setTitle("Java StandAlone Application");
		window.pack();
		window.resize(500,300);
		window.show();
	}
}
(Submitted by Kelvin Ho)
The following is a sample program which can load an image into an application.
import java.awt.*;

public class Holder extends Frame
{
    Holder ()
    {
        MyPicture pic = new MyPicture ();
        add (pic);
        resize (500,500);
    }
    
    public boolean handleEvent(Event evt) 
    {
        if (evt.id == Event.WINDOW_ICONIFY) {//DOESN'T seem to be necessary
            hide();
            return true;
        }
        if (evt.id == Event.WINDOW_DESTROY) {
            System.exit(0);
        }
        return super.handleEvent(evt);
    }
     
    public static void main (String args[])
    {
        Holder window = new Holder ();
        window.setTitle("Java's Duke");
        window.pack();
        window.show();
    }
}

class MyPicture extends Panel
{
    Image img;

    MyPicture ()
    {
        super ();
        resize (100, 100);
        img = Toolkit.getDefaultToolkit().getImage("T1.gif");
        repaint ();
    }

    public void paint (Graphics g)
    {
        g.drawImage(img, 10, 10, this);
    }
}
(Submitted by David Gibbons)
This is a "hack" to get around a bug in 1.0beta2 Java that will not allow image loading from a java application with the getImage method.

add:

  import sun.awt.image.FileImageSource  // the sun classes are included
                                       // in the current sdk

create a SecurityManager class with the following methods:

  class SecMan extends SecurityManager{
      public checkRead(String s){return;}
      public checkPropertyAcess(String s){return;}
      public checkLink(String s){return;}
      public checkAccess(Thread t){return;}
      public checkAccess(ThreadGroup tg){return;}
      public checkExit(int i){return;}
  }

make this visible to the entire class:

    Image im;

somewhere like main or init insert this:

  ...
    SecMan secMan = new SecMan();
    System.setSecurityManager(secMan);
    Canvas cs = new Canvas();
    im = cs.createImage(new FileImageSource("your.gif"));
  ...

put this call in your paint:

    public void paint(Graphics p){
    ...
     g.drawImage(im, 0, 0, this);
    ...

This should do it until the problem is fixed.


How do I read and write a GIF file?


(Submitted by Beat Liechti)
Here's at least how to write a GIF from an Image:
http://www.cs.brown.edu/people/amd/java/GIFEncoder/

How do I save the contents of a panel as a .GIF file?



How do I use the multi-frame feature in ImageObserver to update a changing image?



How do I load an Image from a GIF/JPEG and have it NOT DITHERED when displayed on an 8-bit display?



How can my applet inherit the background color of the HTML page that it is on


(Submitted by Andrew Wilkinson)
One simple way is to pass the bacground color of the HTML page as a parameter into the applet.

In the HTML:

<html>
<body bgcolor="#3399CC">

<applet code=TrnsBgrnd height=200 width=250>
<param name=bgcolor value="3399CC">
</applet>

</body>
</html>
In the Java Code:
import java.applet.Applet;
import java.awt.*;

public class TrnsBgrnd extends Applet {

   Color bgcolor=null;

   public void init() {

      // Read the value of the parameter bgcolor and set the applet 
      // background to this value.

      String attr = getParameter("bgcolor");
      bgcolor = (attr != null) ? convertColor(attr) : Color.white;

      setBackground(bgcolor);

   }

   public Color convertColor(String colStr) {

      int rd = (Integer.valueOf(colStr, 16).intValue() & 0xFF0000) >> 16 ;
      int gn = (Integer.valueOf(colStr, 16).intValue() & 0xFF00) >> 8;
      int bl = Integer.valueOf(colStr, 16).intValue() & 0xFF ;

      return (new Color(rd, gn, bl));
   }

   public void paint(Graphics g) {

      // Do what every graphics processing is required.

      g.drawRect(50, 50, 150, 100);
   }
}

How can an applet set it's background color to "transparent" so that it can display text over a background image specified in the HTML BODY tag?



How do I make Java use the palette from a GIF or JPEG obtained with getImage(), instead of converting it to the default palette?



How does the ImageObserver work with an Image to get the width of an Image?



How do I know when an image has been loaded? Displayed?


(Submitted by Jim Crossley)
/*
 * To determine when an image has finished loading, use the prepareImage()
 * method of Component (of which Applet is a subclass).  This causes
 * the "image-getting" thread to call imageUpdate() whenever something
 * interesting happens, i.e. the image finishes loading.  We override
 * imageUpdate() and set a "ready" flag when we have "all of the bits".
 */
import java.applet.*;
import java.awt.*;

public class Testing extends Applet {
  Image image;
  boolean ready = false;

  public void init() {
    image = this.getImage(this.getDocumentBase(), "image.gif");
    
    // now tell the "image-getting" thread to call imageUpdate() 
    this.prepareImage(image,this); 
  }

  public boolean imageUpdate(Image img, int infoflags, int x, int y, int w, 
int h) {
    if ((infoflags & ALLBITS) != 0) {
      ready = true;
      repaint();
      return false;
    }
    else 
      return true;
  }
  
  public void paint(Graphics g) {
    if (ready)
      g.drawImage(image,0,0,this);
  }
}

How do I use the FilteredImageSource? How do I create a filter for an image?



How do I load an image in a Netscape Java applet? (Toolkit.getImage() doesn't work.)


(Submitted by the editor)
As of Netscape 2.01, you must now use:
img = getImage(getDocumentBase(), "image.gif");