Title: Multimedia in Java
1Multimedia in Java
- Weve already spent a good deal of time dealing
with computer graphics, so we now focus on
animation and sound - To perform animation, we basically want to call
repaint( ) every few milliseconds - how does our program know when a few milliseconds
elapse? - there is a Timer class available set it for 20
milliseconds and every 20 milliseconds, the Timer
generates an ActionEvent - we them implement an ActionListener to handle the
event through an actionPerformed method - in the case of animation, the actionPerformed
method may only have to add 1 to the x or y
coordinate of the item we are drawing, and then
call repaint( ) - To handle sound, we have to cheat in a way
because sound is only available through Applets
or through a special IO library written by Sun,
we will so both approaches
2Timer class
- A Timer object is instantiated by
- Timer t new Timer(duration, handler)
- duration is the time (in milliseconds) that
elapses between Timer-generated events, such as
20 or 50 - handler is the object that handles the
Timer-generated events we will usually just use
this and implement actionPerformed in our class
whenever possible (this may not be easy if we
also implement an ActionListener in this class to
handle JButtons - import java.awt.event.
- add implements ActionListener to our class
header - instantiate the Timer as t new Timer(10, this)
but use whatever value you want for the
duration, 10 or 20 would be adequate for most
applications - start the timer by using t.start( )
- if we need to stop the timer, we use t.stop( )
- Thats about all there is to it!
3TimerSkeleton
import javax.swing. import java.awt.event. pu
blic class TimerSkeleton implements
ActionListener private Timer t // other
instance data go here as needed public
TimerSkeleton( ) t new Timer(10,
this) t.start( ) // other initialization
operations go here as needed // other
methods go here as needed public void
actionPerformed(ActionEvent e) // whatever
you want to happen when the Timer pulses go
here
4What Should actionPerformed Do?
- This depends on why you are using a Timer
- to move an object in a Graphics panel (e.g., a
ball) - alter the x and y coordinates and call repaint( )
- for a Game
- calculate where game objects (say a spacecraft or
a missile) have moved and redraw them - this may require the user of an array of x and an
array of y values to store the various objects,
or multiple variables such as myX, myY, yourX,
yourY, or both (the arrays might store the X and
Y coordinates of missiles launched from one to
the other) - for Animation
- if our item being drawn is represented by an
array of different figures - then just increment the array index and repaint(
) - we will see an example of a StickFigure, but this
could also be done by having a series of jpg or
gif files all pre-loaded into an array of Images
5Moving a Game Object
- Imagine that your class draws on a JPanel an
ImageIcon (say of a spaceship) - Currently, the spaceship is located at
coordinates x, y - The following actionPerformed method will
randomly move the spaceship on the screen - This assumes that x and y are class variables so
that you could do g.drawImage(image, x, y, this)
in repaint( )
public void actionPerformed(ActionEvent e)
int dx generator.nextInt( ) 2 //
generate a from -1 to 1 int dy
generator.nextInt( ) 2 // generate a from
-1 to 1 x dx // move the piece in a
random x direction y dy // move the
piece in a random y direction repaint(
) // assume repaint does drawImage at x, y
6Full Example Code
public TimerExample( ) t new Timer(10,
this) t.start( ) x 150 y 150
repaint( ) public void actionPerformed(ActionEv
ent ev) int distanceX generator.nextInt( ))
2 int distanceY generator.nextInt( ))
2 x distanceX y distanceY repaint(
) public void paintComponent(Graphics
g) super.paintComponent(g) g.setColor(Color.r
ed) g.fillOval(x, y, 5, 5)
At each Timer Event, randomly move the object (a
red circle) up/down/left/right by 0 or 1
unit Note we could make it more realistic by
generating a random int from 1-9 and move it in
one of 8 directions or leave it stationary (1
upper left, or subtract 1 from x and y, 2
straight up, etc)
7Handling Multiple ActionEvents
private static class ExamplePanel extends JPanel
implements ActionListener private Timer
t private JButton b public ExamplePanel(
) t new Timer(1000, this) t.start()
b new JButton("Button") b.addActionListen
er(this) add(b) public void
actionPerformed(ActionEvent e) if(e.getSour
ce( ) t) System.out.println("Timer
pulsed") else if(e.getSource( )
b) System.out.println("Button
pressed")
8Moving Multiple Items
- How would a game like Asteroids work?
- We need to keep track of the ltx, ygt coordinates
of multiple values, just like we did with our
paint program - So we create an array of x, y, dx and dy int
values - private int x, y, dx, dy // dx, dy velocity
of x, y - private int num // number of items in the arrays
- actionPerformed now manipulates all items in the
array and paintComponent draws them all
If xi or yi reaches a boundary (0 or max
X/Y) then change dx or dy to be the opposite
(multiply by -1)
public void actionPerformed(ActionEvent e)
for(int i0iltnumi) xidxi
yidyi
9Sound/Music
- Just as Java has a facility for displaying an
image using the ImageIcon class, you can also
play sounds/music - This facility is only available through the
Applet class or through an IO class created by
Sun - The harder way
- Import java.applet.
- Create a nested inner class that extends Applet,
include an instance data of type AudioClip and in
the Applet constructor, instantiate an Applet
object - aClip Applet.newAudioClip(getClass(
).getResource(filename)) - Add an accessor method to your Applet to return
the audio clip - The slightly easier way
- Import java.io. and sun.audio.
- Create objects of types InputStream and
AudioStream and then tell the AudioPlayer class
to play your AudioStream
10AudioClip Example
import java.applet. // needed to generate an
AudioClip public class AudioExample2 public
static void main(String args) AClip a
new AClip() // create an Applet AudioClip c
a.getClip() // use the Applet to generate an
AudioClip c.play( ) // play the
AudioClip private static class AClip
extends Applet // Applet as an inner class
used to // generate AudioClip
objects private static AudioClip a
// Our AudioClip public AClip() //
constructor a Applet.newAudioClip(g
etClass( ).getResource("chimes.wav"))
// getClass( ) returns the file location of
this class // getResource returns the actual
item, in this case a wav file public
AudioClip getClip() // accessor
return a
11Another Audio Example
import java.io. // use this to create an
InputStream import sun.audio. // another class
that can be used to play audio public class
AudioExample2 public static void main(String
args) try // create an
AudioStream of the wav file InputStream in
new FileInputStream("chimes.wav") AudioStream
as new AudioStream(in) // play the
AudioStream AudioPlayer.player.start(as)
// use the following instead to play the
wav file repeatedly in a continuous
loop //AudioData data as.getData() //Cont
inuousAudioDataStream cas // new
ContinuousAudioDataStream (data)
//AudioPlayer.player.start(cas)
catch(IOException ex) // any code here will be
used if trying the audio player doesnt
work!