Chapter 3-Multimedia Programming

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 21

Nawaraj Paudel Page 1

Chapter 3
Multimedia Programming
Working with 2D Graphics
Java 2D API provides the facilities to draw a wide range of two dimensional geometric
primitives, such as lines, curves, rectangles, and ellipses, as well as a mechanism for ren-
dering virtually any geometric shape. We can use two classes (Graphics and Graphic-
s2D) for this rendering.

The Graphics Class


To do the 2D graphics programming by using Graphics class we need to import the
java.awt package. Graphics class has methods to draw lines, rectangles, ellipses, and
so on. But those drawing operations are very limited. For example, you cannot vary the
line thickness and you cannot rotate the shapes. Graphics class method use integer pixel
coordinates. For drawing the graphics by using Graphics class we need to override the
paint method of JPanel class and need to write the drawing code inside that method as
given below.
import javax.swing.*;
import java.awt.*;
public class GraphicsExample extends JApplet {
public void paint(Graphics g) {
g.drawLine(10,0,200,200);
}
}
Drawing Lines
To draw lines, we use drawLine method in the Graphics class as shown below:
g.drawLine(x1, y1, x2, y2)
Where (x1, y1) = Co-ordinate of starting point of the line
(x1, y1) = Co-ordinate of end point of the line
x1, y1

x2, y2

Drawing Rectangles
To draw rectangles, we use drawRect method in the Graphics class as shown below:
g.drawRect(x1, y1, w, h);

Advanced Programming Techniques


Nawaraj Paudel Page 2

Where (x1, y1) = Co-ordinate of starting point of the line


w, h = width and height of the rectangle.
x1, y1
w

Note: If we want to draw the square we need to provide the same value for width and
height.
Drawing Filled Rectangles
To draw filled rectangles with colors, we use fillRect method in the Graphics class as
shown below:
g.setColor(Color.red);
g.fillRect(x1, y1, w, h);
In this case red color is filled inside the rectangle as below.
x1, y1
w

Drawing Cleared Rectangles


To draw a cleared rectangle in an area that is already filled with some color we use
clearRect method in the Graphics class as below:
g.clearRect(x1, y1, w, h);
It draws a rectangle with cleared background.
Drawing Round Edges Rectangles
To draw a round edged rectangle we use the drawRoundRect method as shown below:
g.drawRoundRect(x1, y1, w, h, a, b);
Where (x1, y1) = coordinate of top-left corner of the rectangle.
w, h = width and height of the rectangle.
a, b = degree of roundness in x and y direction respectively.

Advanced Programming Techniques


Nawaraj Paudel Page 3

Drawing Ovals
To draw an empty oval we use the drawOval method as given below:
g.drawOval(x1, y1, w, h);
Where (x1, y1) = Co-ordinate of to-left point of the enclosing rectangle
w, h = width and height of the enclosing rectangle.
x1, y1
w

This method finds the co-ordinates of middle points of the rectangle and draws the oval
by joining these middle points. The enclosing rectangle is not drawn.
To draw a filled oval we use the fillOval method as shown below:
g.setColor(Color.blue);
g.fillOval(x1, y1, w, h);
x1, y1
w

To draw a circle we provide same value of width and height for the enclosing rectangle,
that is, enclosing rectangle must be a square.
Drawing Arcs
To draw an empty arc we use the drawArc method as given below:
g.drawArc(x, y, w, h, SA, AA);
Where:
x, y = coordinates of top left coordinates of enclosing rectangle
w, h = width and height of enclosing rectangle
SA = starting arc angle
AA = arc angle

Advanced Programming Techniques


Nawaraj Paudel Page 4

To draw the filled arcs we use fillArc method as below:


g.setColor(Color.orange);
g.fillArc(x, y, w, h, SA, AA);
Drawing Polygons
To draw polygons we use Polygon class in addition with addPoint method as shown
below:
Polygon p= new Polygon( );
p.addPoint(20,20);
p.addPoint(80,20);
p.addPoint(80,90);
p.addPoint(45,120);
p.addPoint(20,90);
g.drawPolygon(p);
End point and start point are automatically connected by line
We can also use the following format of drawPolygon method:
g.drawPolyline(x, y, int n);
Where
x = array of x co-ordinates
y = array of y co-ordinates
n = number of points
For example,
int []x = {10,10,60};
int []y = {10,30,70};
g.drawPolygon(x,y,3);
to draw filled polygons, we use fillPolygon method instead of drawPolygon. For
example,
Polygon p=new Polygon();
p.addPoint(20,20);
p.addPoint(80,20);
p.addPoint(80,90);
p.addPoint(45,120);
p.addPoint(20,90);

Advanced Programming Techniques


Nawaraj Paudel Page 5

g.setColor(Color.blue);
g.fillPolygon(p);
OR
int []x = {10,10,60};
int []y = {0,30,70};
g.setColor(Color.blue);
g.fillPolygon(x,y,3);
If we do not want to connect the start and end point of the polygon we use drawPolyLine
method as follows:
g.drawPolyline(x, y, int n);
Where
x = set of x co-ordinates
y = set of y co-ordinates
n = number of points
For example,
int []x = {10,10,60};
int []y = {10,30,70};
g.drawPolyline(x,y,3);
Clipping an Area
We can restrict the drawing area by using clipping operation. By using clipping we can
view the small areas from the large object. For example we can get half of the oval by
limiting the drawing area. We can clip an area by using following methods:
g.clipRect(x, y, w, h);
g.setClip(x, y, w, h);
These methods intersect the current clip with the specified rectangle. The resulting
clipping area is the intersection of the current clipping area and the specified rectangle.
For example,
g.clipRect(50,75,150,50);
g.fillOval(50,50,150,100);
We can find the clipping bound by using getClipBounds method as below:
Rectangle r = g.getClipBounds( );

Advanced Programming Techniques


Nawaraj Paudel Page 6

Setting the Drawing Color


As shown before, we can use the setColor method for changing the drawing color in two
different ways as follows:
g.setColor(color name);
For example,
g.setColor(Color.magenta);
OR
g.setColor(object of color class)
For example,
g.setColor(new Color(200,100,150));
Here three numbers are the values of red, green and blue colors respectively. Values
range from 0 to 255.
Text and Fonts
We specify a font by its font face name (or font name for short). A font face name is
composed of a font family name, such as “Helvetica,” and an optional suffix such as
“Bold.” For example, the font faces “Helvetica” and “Helvetica Bold” are both
considered to be part of the family named “Helvetica.” To find out which fonts are
available on a particular computer, call the getAvailableFontFamilyNames
method of the GraphicsEnvironment class. The method returns an array of
strings that contains the names of all available fonts. To obtain an instance of the
GraphicsEnvironment class that describes the graphics environment of the user's
system, use the static getLocalGraphicsEnvironment method. Thus, the
following program gives you a printout of the names of all fonts on your system:
import java.awt.*;
public class ListFonts
{
public static void main(String[] args)
{
GraphicsEnvironment ge=
GraphicsEnvironment.getLocalGraphicsEnvironment()
String[] fontNames=ge.getAvailableFontFamilyNames();
for (int i = 0; i < fontNames.length; i++)
System.out.println(fontNames[i]);
}
}
To draw characters in a font, you must first create an object of the class Font. You
specify the font name, the font style, and the point size. Here is an example of how you
construct a Font object.
Font f = new Font ("Helvetica", Font.BOLD, 14);
You specify the style (plain, bold, italic, or bold italic) by setting the second Font
constructor argument to one of the following values:

Advanced Programming Techniques


Nawaraj Paudel Page 7

Font.PLAIN
Font.BOLD
Font.ITALIC
Font.BOLD + Font.ITALIC
To use a font that you have created, you must select it using setFont
method. Its general form is:
void setFont(Font fontObj)
For example,
Font f = new Font ("Helvetica", Font.BOLD, 44);
setFont(f);
g.drawString("Hello",100,100);
To obtain information about the currently selected font, we use getFont
method. Its general form is:
Font getFont()

The Graphics2D Class


The Graphics2D class in java.awt package was released with JDK 1.2 and extends the
Graphics class to provide more sophisticated control over geometry, coordinate
transformations, color management, and text layout. Beginning with JDK 1.2, this is the
fundamental class for rendering two-dimensional shapes, text and images. Because it
extends the Graphics class, the capabilities of the Graphics class that existed in earlier
versions of the JDK continue to be available.
The Java 2D library organizes geometric shapes in an object-oriented fashion. In
particular, there are classes to represent lines (Line2D), rectangles (Rectangle2D) and
ellipses (Ellipse2d) in java.awt.geom package.
These classes all implement the Shape interface. To draw a shape, you first create
an object of a class that implements the Shape interface and then call the draw method
of the Graphics2D class. For example, to draw a rectangle, we can write a program as
follows:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class GraphicsExample extends JApplet {
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
Rectangle2D floatRect = new Rectangle2D.Float (10, 15.5F,
22.5F, 20.0F);
g2d.draw(floatRect);
}
}
By using the Java 2D library, you keep your options open – you can later enhance your
drawings with some of the many tools that the Java 2D library supplies. Graphics class
method used integer pixel coordinates; the Java 2D shapes use floating-point coordinates.

Advanced Programming Techniques


Nawaraj Paudel Page 8

In many cases, it is a great convenience because it allows you to specify your shapes in
coordinates that are meaningful to you (such as millimeters or inches) and then translate
to pixels. The designers of the 2D library have supplied two versions of each shape class:
one with float coordinates and one with double coordinates.
Rectangle2D Class
This is an abstract class with two concrete subclasses, which are also static inner classes:
Rectangle2D.Float and Rectangle2D.Double.

Fig: Rectangle classes


When we construct a Rectangle2D.Float object, we supply the coordinates as float
numbers. For a Rectangle2D.Double object, we supply them as double numbers.
For example,
Rectangle2D.Float floatRect = new Rectangle2D.Float (10.0F,
25.0F, 22.5F, 20.0F);
Rectangle2D.Double doubleRect = new Rectangle2D.Double
(10.0, 25.0, 22.5, 20.0);
We can also simply use Rectangle2D variables to hold the rectangle references.
Rectangle2D floatRect = new Rectangle2D.Float (10.0F, 25.0F,
22.5F, 20.0F);
Rectangle2D doubleRect = new Rectangle2D.Double (10.0, 25.0,
22.5, 20.0);
We can also draw rectangles providing two diagonal corner points of a
rectangle as follows:
Rectangle2D rect = new Rectangle2D.Double();
rect.setFrameFromDiagonal(px, py, qx, qy);
Or, even better, if you know the corner points as Point2D objects p and q,
rect.setFrameFromDiagonal(p, q);
Point2D Class
There is a Point2D class with subclasses Point2D.Float and Point2D.Double.
Here is how to make a point object.
Point2D p = new Point2D.Double (10, 20);

Advanced Programming Techniques


Nawaraj Paudel Page 9

The Point2D class is very useful - it is more object-oriented to work with Point2D
objects than with separate x- and y- values. Many constructors and methods accept
Point2D parameters. It is suggested that you use Point2D objects when you can – they
usually make geometric computations easier to understand.
Ellipse2D Class
For drawing the elliptical shapes we need to provide the coordinates of bounding
rectangles. Then Elliptical shapes are drawn by jointing the mid points of the sides of the
rectangle. It is similar to Graphics class. For example,
Ellipse2D e = new Ellipse2D.Double (150, 200, 100, 50);
constructs an ellipse that is bounded by a rectangle with the top-left corner at (150, 200),
Width 100 and height 50.
RoundRectangle2D Class
For drawing the round edges rectangular shapes we need to provide the top left corner,
width and height, and the x- and y-dimension of the corner area that should be rounded.
For example,
RoundRectangle2D r = new RoundRectangle2D.Double(150, 200, 100, 50, 20, 20);
produces a rounded rectangle with circles of radius 20 at each of the corners.
Arc2D Class
To construct an arc, you specify the bounding box, followed by the start angle and the
angle swept out by the arc and the closure type, one of Arc2D.OPEN, Arc2D.PIE, or
Arc2D.CHORD. Its general form is:
Arc2D a = new Arc2D.Double (x, y, width, height, startAngle, arcAngle, closureType);
OR
Arc2D a = new Arc2D.Float (x, y, width, height, startAngle, arcAngle, closureType);
For Example
Arc2D a = new Arc2D.Double(10, 10, 200, 200, 45, 180, Arc2D.CHORD);

Following figure describes the arc types

Advanced Programming Techniques


Nawaraj Paudel Page 10

QuadCurve2D Class
The Java 2D package supplies quadratic curves. Quadratic curves are specified by two
end points and one control point. Moving the control points changes the shape of the
curves. Its general form is:
QuadCurve2D q = new QuadCurve2D.Double(startX, startY, controlX, controlY, endX,
endY);
For example,
QuadCurve2D q = new QuadCurve2D.Float(10,10,50,300,200,200);

CubicCurve2D Class
The Java 2D package supplies cubic curves. Cubic curves are specified by two end points
and two control point. Moving the control points changes the shape of the curves. Its

Advanced Programming Techniques


Nawaraj Paudel Page 11

general form is:


CubicCurve2D c = new CubicCurve2D.Double(startX, startY, control1X, control1Y,
control2X, control2Y, endX, endY);
For example,
CubicCurve2D q = new CubicCurve2D.Float(10,10,100,50,100,300,200,200);

Advanced Programming Techniques


Nawaraj Paudel Page 12

Drawing General Paths


You can build arbitrary sequences of line segments, quadratic curves, and cubic curves,
and store them in a GeneralPath object. You specify the first coordinate of the path with
the moveTo method. For example,
GeneralPath path = new GeneralPath();
path.moveTo(startX, startY);
Then, you extend the path by calling one of the methods lineTo, quadTo, or curveTo.
These methods extend the path by a line, a quadratic curve, or a cubic curve. To call
lineTo, supply the end point. For the two curve methods, supply the control points, then
the end point. For example,
path.lineTo(endX, endY);
path.quadTo(control1X, control1Y, endX, endY);
path.curveTo(control1X, control1Y, control2X, control2Y, endX, endY)
You can close the path by calling the closePath method. It draws a line back to the last
moveTo. For example,
path.closePath();
To make a polygon, simply call moveTo to go to the first corner point, followed by
repeated calls to lineTo to visit the other corner points. Finally, call closePath to close the
polygon.
A general path does not have to be connected. You can call moveTo at any time to
start a new path segment. For example,
GeneralPath path = new GeneralPath();
path.moveTo(10, 20);
path.lineTo(50,10);
path.moveTo(200, 20);
path.lineTo(50,100);
Finally, you can use the append method to add arbitrary Shape objects to a general path.
The second parameter of the append method is true if the new shape should be connected
to the last points on the path, false if it should not be connected. For example,
GeneralPath path = new GeneralPath();
Rectangle2D floatRect = new Rectangle2D.Float (10.0F, 25.0F, 22.5F, 20.0F);
path.moveTo(10, 20);
path.lineTo(50,10);
path.lineTo(100,10);
path.append(floatRect,true);
Setting Drawing Colors
The setPaint method of the Graphics2D class lets us select a color that is used for
all subsequent drawing operations on the graphics context or component. To draw in
multiple colors, we select a color, draw, then select another color, and draw again.

Advanced Programming Techniques


Nawaraj Paudel Page 13

We define colors with the Color class. The java.awt.Color class offers predefined
constants for the 13 standard colors listed in following table
Black Green red
Blue lightGray white
Cyan Magenta yellow
darkGray Orange gray
Pink
For example,
Graphics2D g2d=(Graphics2D)g;
g2d.setPaint(Color.red);
GeneralPath path = new GeneralPath();
Rectangle2D r1 = new Rectangle2D.Float (10.0F, 25.0F, 22.5F, 20.0F);
g2d.draw(r1);
We can specify a custom color by creating a Color object by its red, green, and blue
components. Using a scale of 0–255 (that is, one byte) for the redness, blueness, and
greenness, we call the Color constructor like this:
Color(int redness, int greenness, int blueness)
For example,
g.setPaint(new Color(0, 128, 128));
Filling Shapes
You can fill the interiors of closed shapes (such as rectangles or ellipses) with a color.
Simply call fill instead of draw. For example,
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(Color.red);
Rectangle2D r1 = new Rectangle2D.Float (10.0F, 25.0F, 22.5F, 20.0F);
g2d.fill(r1);

Working with 3D Graphics


We live in a 3D world. Our vision enables us to see in three dimensions – x, y, and z co-
ordinates. Many of the surfaces onto which graphics are displayed – for example, moni-
tors and printed pages – are flat. 3D-graphics programming enables us to render realistic
models of our 3D world onto a 2D-viewing surface. 3D graphics have advanced to the
point that nearly anything you can see around you can be modeled – represented numeri-
cally by shape and size – and rendered – drawn on your computer screen.
There now exist an increasing number of 3D-computer-graphics applications – from
flight simulators and medical-imaging equipment to 3D games and screen savers. Rapid
advances in computer hardware have resulted in tremendous growth in the 3D-graphics
industry. Developments in high-performance hardware led to developments in high-per-
formance 3D graphics APIs – beginning in the 1970s with Siggraph’s CORE API, contin-

Advanced Programming Techniques


Nawaraj Paudel Page 14

uing in the 1980s with SGI’s (Silicon Graphics, Inc.) OpenGL and on through today with
Microsoft’s Direct3D (part of Microsoft’s DirectX API) and Java 3D.
Java 3D is the extension to Java for displaying three dimensional graphics. Programs
written in Java 3D can be run on several different types of computer and over the inter -
net. Java 3D is a client-side Java application programming interface (API) developed at Sun Mi-
crosystems for rendering interactive 3D graphics using Java. Using Java 3D you will be able to
develop richly interactive 3D applications, ranging from immersive games to scientific visualiza-
tion applications.
The Java 3D API requires that you have the Java 2 Platform, Standard Edition and
either OpenGL or Direct3D installed on your computer – Java 3D uses OpenGL or Direc-
t3D graphics libraries to render 3D scenes. The Java 3D API is not integrated in the core
Java 2 Platform. To use the Java 3D API, you must install the appropriate Java extension
and utility packages. The Java 3D API packages differ slightly depending on which low-
level graphics libraries are installed on your computer. The version of Java 3D packages
you install depends on your operating system and graphics API.
Basic Steps
Basic steps needed to display 3D objects are:
1. Create a virtual universe to contain your scene.
2. Create a data structure to contain a group of objects.
3. Add an object to the group
4. Position the viewer so that they are looking at the object
5. Add the group of objects to the universe
For example, in the program below, Hello3d() constructor contains five lines that perform
each of these steps. The program displays a glowing cube, the viewer is looking directly
at the red face of the cube, so what you actually see is a red square on a black background
import com.sun.j3d.utils.universe.*;
import com.sun.j3d.utils.geometry.*;
import javax.media.j3d.*;
public class Hello3d {
public Hello3d() {
SimpleUniverse universe = new SimpleUniverse();
BranchGroup group = new BranchGroup();
group.addChild(new ColorCube(0.3));
universe.getViewingPlatform().setNominalViewingTransform();
universe.addBranchGraph(group);
}
public static void main( String[] args ) {
new Hello3d();
}
}
Using Light
The way the light falls on an object provides us with the shading that helps us see shapes
in three dimensions. The example below illustrates how to display a ball lit by a red light.

Advanced Programming Techniques


Nawaraj Paudel Page 15

import com.sun.j3d.utils.geometry.*;
import com.sun.j3d.utils.universe.*;
import javax.media.j3d.*;
import javax.vecmath.*;
public class Ball {
public Ball() {
// Create the universe
SimpleUniverse universe = new SimpleUniverse();

// Create a structure to contain objects


BranchGroup group = new BranchGroup();

// Add a ball to the group of objects


group.addChild(new Sphere(0.5f));

// Create a red light that shines for 100m from the origin
Color3f light1Color = new Color3f(1.8f, 0.1f, 0.1f);
BoundingSphere bounds= new BoundingSphere(new
Point3d(0.0,0.0,0.0), 100.0);
Vector3f light1Direction = new Vector3f(4.0f, -7.0f, -12.0f);
DirectionalLight light1 = new DirectionalLight(light1Color,
light1Direction);
light1.setInfluencingBounds(bounds);
group.addChild(light1);

// look towards the ball


universe.getViewingPlatform().setNominalViewingTransform();

// add the group of objects to the Universe


universe.addBranchGraph(group);
}
public static void main(String[] args) {
new Ball();
}
}
Positioning Objects
So far, the examples have created objects in the same place, the center of the universe. In
Java 3D, locations are described by using x, y, z coordinates. Increasing coordinates go
along the x-axis to the right, along the y-axis upwards, and along the z-axis out of the
screen.
This is called a “right-handed” coordinate system because the thumb and first two
fingers of your right hand can be used to represent the three directions. All the distances
are measured in meters.

Advanced Programming Techniques


Nawaraj Paudel Page 16

To place your objects in the scene, you start at point (0, 0, 0), and then move the
objects wherever you want. Moving the objects is called a “transformation”, so the
classes you use are: TransformGroup and Transform3D. You add both the object and the
Transform3D to a TransformGroup before adding the TransformGroup to the rest of your
scene. Detail steps are given below:
Step Example
1. Create a transform, a transform group and Transform transform= new
an object Transform3D();
TransformGroup tg = new
TransformGroup();
Cone cone = new Cone(0.5f, 0.5f);
2. Specify a location for the object Vector3f vector = new
Vector3f(-.2f,.1f , -.4f);
3. Set the transform to move (translate) the transform.setTranslation(vector);
object to that location
4. Add the transform to the transform group tg.setTransform(transform);
5. Add the object to the transform group tg.addChild(cone);
For example,
import com.sun.j3d.utils.geometry.*;
import com.sun.j3d.utils.universe.*;
import javax.media.j3d.*;
import javax.vecmath.*;
public class Position {
public Position() {
SimpleUniverse universe = new SimpleUniverse();

BranchGroup group = new BranchGroup();

TransformGroup tg = new TransformGroup();


Transform3D transform = new Transform3D();
Vector3f vector = new Vector3f( -.5f, .0f, .5f);
transform.setTranslation(vector);
tg.setTransform(transform);
tg.addChild(new Sphere(0.2f));
group.addChild(tg);

Color3f light1Color = new Color3f(.1f, 1.4f, .1f);


BoundingSphere bounds = new BoundingSphere(new
Point3d(0.0,0.0,0.0), 100.0);
Vector3f light1Direction = new Vector3f(4.0f, -7.0f, -12.0f);
DirectionalLight light1 = new DirectionalLight(light1Color,
light1Direction);
light1.setInfluencingBounds(bounds);
group.addChild(light1);

Advanced Programming Techniques


Nawaraj Paudel Page 17

universe.getViewingPlatform().setNominalViewingTransform();

universe.addBranchGraph(group);
}
public static void main(String[] args) {
new Position();
}
}
We can also rotate objects using TransformGroup and Transform3D. The example below
demonstrates this concept with ColorCube:
import com.sun.j3d.utils.universe.*;
import com.sun.j3d.utils.geometry.*;
import javax.media.j3d.*;
import javax.vecmath.*;
public class Hello3d {
public Hello3d() {
SimpleUniverse universe = new SimpleUniverse();

BranchGroup group = new BranchGroup();

Transform3D rotate = new Transform3D();


rotate.rotX(Math.PI/4.0d);
TransformGroup objRotate = new TransformGroup(rotate);
objRotate.addChild(new ColorCube(0.4));

group.addChild(objRotate);

universe.getViewingPlatform().setNominalViewingTransform();

universe.addBranchGraph(group);
}
public static void main( String[] args ) {
new Hello3d();
}
}

Working with Audio Clip


To be able to play audio in a program or applet, you first have to use the AudioClip
interface and instantiate an AudioClip object with it. The AudioClip interface is located
in the java.applet package. For example,
AudioClip aClip;

Advanced Programming Techniques


Nawaraj Paudel Page 18

After instantiating an AudioClip object, you have to load the actual audio file to be
played. This is achieved with the newAudioClip method - a static method of the Applet
class which takes an instance of the URL class that loads the file. For example,
aClip = Applet.newAudioClip(new URL("file:sound.wav"));
In the above example, an audio file named sound.wav is loaded as the audio file to be
played. Once the audio file is uploaded, you can use the methods of the AudioClip
interface to work with it. The AudioClip interface defines three methods: play() (play a
clip from the beginning), stop() (stop playing the clip), and loop () (play the loop
continuously).
A Complete Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.net.*;
class AudioFrame extends JFrame implements ActionListener {
private AudioClip bach;
public AudioFrame() {
super("Audio clip example");
JButton play, loop, stop;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
play = new JButton("Play");
play.addActionListener(this);
add(play);
loop = new JButton("Loop");
loop.addActionListener(this);
add(loop);
stop = new JButton("Stop");
stop.addActionListener(this);
add(stop);
try {
bach = Applet.newAudioClip(new URL("file:misery.mid"));
}
catch (MalformedURLException mfe) {
System.out.println("An error occured, please try again...");
}
setLayout(new FlowLayout());
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() == "Play") {
bach.play();
}

Advanced Programming Techniques


Nawaraj Paudel Page 19

if (e.getActionCommand() == "Loop") {
bach.loop();
}
if (e.getActionCommand() == "Stop") {
bach.stop();
}
}
}

class Play {
public static void main(String[] args){
AudioFrame AF = new AudioFrame();
}
}

Java Media Framework (JMF)


Java media framework (JMF) is a multimedia API. Using the JMF API, programmers can
create Java programs that play, edit, stream and capture many popular media types. Fea-
tures of JMF are quite extensive.
JMF supports many different media file types such as Microsoft Audio/Video Inter-
leave (.avi), Macromedia Flash 2 movies (.swf), Future Splash (.spl), MPEG Layer 3 Au-
dio (.mp3), Musical Instrument Digital Interface (MIDI; .mid or .rmi extensions), MPEG-
1 videos (.mpeg, .mpg), QuickTime (.mov), Sun Audio file format (.au extension), and
Macintosh AIFF file format (.aif or .aiff extension).

Creating a Simple Media Player


The JMF offers several mechanisms for playing media. The simplest mechanism is using
objects that implement interface Player declared in package javax.media. Package
javax.media and its subpackages contain the classes that compose the Java Media
Framework. To play a media clip you must first create a URL object that refers to it.
Then pass the URL as an argument to static method createRealizedPlayer of class
Manager to obtain a Player for the media clip. Class Manager declares utility methods
for accessing system resources to play and to manipulate media. For example,
import java.awt.*;
import java.io.*;
import java.net.*;
import javax.media.*;
import javax.swing.*;
public class MediaPlayer extends JFrame {
public MediaPlayer() {
super("Java Media Framework");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
Manager.setHint(Manager.LIGHTWEIGHT_RENDERER,true);

Advanced Programming Techniques


Nawaraj Paudel Page 20

try {
Player mediaPlayer = Manager.createRealizedPlayer(new
URL("file:Bear.mpg"));
Component video = mediaPlayer.getVisualComponent();
Component controls = mediaPlayer.getControlPanelComponent();
if(video != null)
add(video, BorderLayout.CENTER);
if(controls != null)
add(controls, BorderLayout.SOUTH);
mediaPlayer.start();
}catch( NoPlayerException noPlayerException) {
System.err.println( "No media player found");
}catch(CannotRealizeException cannotRealizeException) {
System.err.println( "Could not realize media player");
}catch(IOException iOException) {
System.err.println( "Error reading from the source");
}
pack();
setVisible(true);
}
}

public class MainMediaPlayer {


public static void main(String[]args) {
MediaPlayer mp = new MediaPlayer();
}
}
In this program, static method setHint is used to set the flag
Manager.LIGHTWEIGHT_RENDER to true. This instructs the Manager to use a
lightweight renderer that is compatible with lightweight Swing components, as opposed
to the default heavyweight renderer. Inside the try block invokes static method
createRealizedPlayer of class Manager to create and realize a Player that plays the media
file. When a Player realizes, it identifies the system resources it needs to play the media.
Depending on the file, realizing can be a resource-consuming and time-consuming
process. Method createRealizedPlayer throws three exceptions, NoPlayerException,
CannotRealizeException and IOException. A NoPlayerException indicates that the
system could not find a player that can play the file format. A CannotRealizeException
indicates that the system could not properly identify the resources a media file needs. An
IOException indicates that there was an error while reading the file. These exceptions are
handled in the catch block. Method getVisualComponent of Player to get a Component
that displays the visual (generally video) aspect of the media Method
getControlPanelComponent of Player to get a Component that provides playback and
media controls. These components are assigned to local variables video and control,
respectively. The if statements add the video and the controls if they exist. The video
Component is added to the CENTER region. The controls Component, which is added to

Advanced Programming Techniques


Nawaraj Paudel Page 21

the SOUTH region, typically provides the following controls:


1. A positioning slider to jump to certain points in the media clip.
2. A pause button.
3. A volume button that provides volume control by right clicking and a mute func-
tion by left clicking.
4. A media properties button that provides detailed media information by left click-
ing and frame rate control by right clicking.
Method start begins playing the media file.

Creating Animations
Many forms of animation are possible in Java. What all of them have in common is that
they create some kind of motion on the screen by drawing successive frames at a rela-
tively high speed. We can use different colors and sound clips during motion.
To update the screen multiple times, you need to create a new Java thread that con-
tains an animation loop. The animation loop is responsible for keeping track of the cur-
rent frame and for requesting periodic screen updates. To implement a thread, you must
either create a subclass of Thread or adhere to the Runnable interface. For example,
import java.awt.*;
import java.applet.*;
public class Animation extends Applet implements Runnable {
private Thread animator;
private static int x = 10;
public void start() {
animator = new Thread(this);
animator.start();
}
public void run() {
while (Thread.currentThread() == animator) {
repaint();
try {
Thread.sleep(100);
}catch (InterruptedException e) {
break;
}
}
}
public void stop() {
animator = null;
}
public void paint(Graphics g) {
g.drawRect(x,10,100,150);
x = x + 10;
}
}

Advanced Programming Techniques

You might also like