Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Java How to Program, Fourth Edition - Deitel H., Deitel P.pdf
Скачиваний:
58
Добавлен:
24.05.2014
Размер:
14.17 Mб
Скачать

1316

Java Media Framework and Java Sound (on CD)

Chapter 22

If the command is ShortMessage.NOTE_OFF and is within the allowable piano key range (lines 513–517), lines 520–521 change the background of the specified piano key back to white. Lines 524-525 send the ShortMessage to the synthesizer so that the note will stop sounding. Because not all NOTE_ON ShortMessages are followed by a NOTE_OFF ShortMessage as one would expect, the program needs to change the last NOTE_ON key back to its original color at the time of the next event. For that purpose method noteAction assigns a lastKeyOn value to the last piano button invoked. The lastKeyOn object initialized to –1 remains –1 if the NOTE_ON command note is out of range. This limits access only to keys in range of our simulated keyboard. When pianoTimer reaches the next event, the program changes the background of the last “pressed” piano key back to white (lines 447–449).

When the program finishes executing method noteAction, line 452 invokes MidiData method goNextEvent to transition to the next event in the track. Every time the handler’s actionPerformed method finishes loading the next event, line 455 determines whether the next event is the last event in the track by invoking MidiData method isTrackEnd, assuming that the last event is the end-of-track MetaEvent. If the next event is the last event, lines 457–459 change the background color of the last “pressed” key to white and line 461 stops the pianoTimer. Lines 463–465 re-enable buttons that were disabled during the “piano player” feature.

22.8 Internet and World Wide Web Resources

This section presents several Internet and Web resources for the Java Media Framework and other multimedia related sites.

java.sun.com/products/java-media/jmf/

The Java Media Framework home page on the Java Web site. Here you can download the latest Sun implementation of the JMF. The site also contains the documentation for the JMF.

www.nasa.gov/gallery/index.html

The NASA multimedia gallery contains a wide variety of images, audio clips and video clips that you can download and use to test your Java multimedia programs.

sunsite.sut.ac.jp/multimed/

The Sunsite Japan Multimedia Collection also provides a wide variety of images, audio clips and video clips that you can download for educational purposes.

www.anbg.gov.au/anbg/index.html

The Australian National Botanic Gardens Web site provides links to sounds of many animals. Try the

Common Birds link.

www.midi.com

Midi.com is a MIDI resource site with a MIDI search engine, links to other MIDI sites, a list of MIDIrelated books and other MIDI information.

www.streamingmedia.com

Streamingmedia.com provides many articles of the streaming media industry and technical information streaming media technology.

www.harmony-central.com/MIDI/

Harmony Central’s MIDI resources section contains many useful MIDI documents, links and forums that can be useful for a MIDI programmer.

Chapter 22

Java Media Framework and Java Sound (on CD)

1317

22.9 (Optional Case Study) Thinking About Objects: Animation and Sound in the View

This case study has focused mainly on the elevator system model. Now that we have completed our design of the model, we turn our attention to the view, which provides the visual presentation of the model. In our case study, the view—called ElevatorView—is a JPanel object containing other JPanel “child” objects, each representing a unique object in the model (e.g. a Person, a Button, the Elevator). Class ElevatorView is the largest class in the case study. In this section, we discuss the graphics and sound classes used by class ElevatorView. We present and explain the remainder of the code in this class in Appendix I.

In Section 3.7, we constructed a class diagram for our model by locating the nouns and noun phrases from the problem statement of Section 2.7. We ignored several of these nouns, because they were not associated with the model. Now, we list the nouns and nouns phrases that apply to displaying the model:

display

audio

elevator music

The noun “display” corresponds to the view, or the visual presentation of the model. As described in Section 13.17, class ElevatorView aggregates several classes comprising the view. The “audio” refers to the sound effects that our simulation generates when various actions occur—we create class SoundEffects to generate these sound effects. The phrase “elevator music” refers to the music played as the Person rides in the Ele- vator—we create class ElevatorMusic to play this music.

The view must display all objects in the model. We create class ImagePanel to represent stationary objects in the model, such as the ElevatorShaft. We create class MovingPanel, which extends ImagePanel, to represent moving objects, such as the Elevator. Lastly, we create class AnimatedPanel, which extends MovingPanel, to represent moving objects whose corresponding images change continuously, such as a Person (we use several frames of animation to show the Person walking then pressing a button). Using these classes, we present the class diagram of the view for our simulation in Fig. 22.9.

The notes indicate the roles that the classes play in the system. According to the class diagram, class ElevatorView represents the view, classes ImagePanel, MovingPanel and AnimatedPanel relate to the graphics, and classes SoundEffects and ElevatorMusic relate to the audio. Class ElevatorView contains several instances of classes ImagePanel, MovingPanel and AnimatedPanel and one instance each of classes SoundEffects and ElevatorMusic. In Appendix I, we associate each object in the model with a corresponding class in the view.

In this section, we discuss classes ImagePanel, MovingPanel and AnimatedPanel to explain the graphics and animation. We then discuss classes SoundEffects and ElevatorMusic to explain the audio functionality.

ImagePanel

The ElevatorView uses objects from JPanel subclasses to represent and display each object in the model (such as the Elevator, a Person, the ElevatorShaft, etc.).

1318

Java Media Framework and Java Sound (on CD)

Chapter 22

Class ImagePanel (Fig. 22.10) is a JPanel subclass capable of displaying an image at a given screen position. The ElevatorView uses ImagePanel objects to represent stationary objects in the model, such as the ElevatorShaft and the two Floors. Class ImagePanel contains an integer attribute—ID (line 16)—that defines a unique identifier used to track the ImagePanel in the view if necessary. This tracking is useful when several objects of the same class exist in the model, such as several Person objects. Class ImagePanel contains Point2D.Double object position (line 19) to represent the ImagePanel screen position. We will see later that MovingPanel, which extends ImagePanel, defines velocity with doubles—using type double yields a highly accurate velocity and position. We cast the position coordinates to ints to place the ImagePanel on screen (Java represents screen coordinates as ints) in method setPosition (lines 90–94). Class ImagePanel also contains an ImageIcon object called imageIcon (line 22)—method paintComponent (lines 54–60) displays imageIcon on screen. Lines 41–42 initialize imageIcon using a String parameter holding the name of the image. Lastly, class ImagePanel contains Set panelChildren (line 25) that stores any child objects of class ImagePanel (or objects of a subclass of ImagePanel). The child objects are displayed on top of their parent ImagePanel—for example, a Person riding inside the Elevator. The first method add (lines 63–67) appends an object to panelChildren. The second method add (lines 70–74) inserts an object into panelChildren at a given index. Method setIcon (lines 84–87) sets imageIcon to a new image. Objects of class AnimatedPanel use method setIcon repeatedly to change the image displayed, which causes the animation for the view—we discuss animation later in the section.

ImagePanel

1..*

 

 

 

 

 

 

ElevatorMusic

 

 

 

 

 

 

1

 

 

 

 

 

1

 

1

 

 

 

 

 

 

 

 

 

 

 

MovingPanel

 

 

 

 

ElevatorView

 

 

audio

 

 

 

 

 

 

 

 

 

 

1..*

1

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

1

 

1

 

 

 

 

 

1..*

 

 

 

 

1

 

 

 

AnimatedPanel

 

 

 

 

SoundEffects

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

graphics

view

 

Fig. 22.9 Class diagram of elevator simulation view.

Chapter 22

Java Media Framework and Java Sound (on CD)

1319

1// ImagePanel.java

2 // JPanel subclass for positioning and displaying ImageIcon

3 package com.deitel.jhtp4.elevator.view;

4

5 // Java core packages

6import java.awt.*;

7 import java.awt.geom.*;

8 import java.util.*;

9

10// Java extension packages

11import javax.swing.*;

12

13 public class ImagePanel extends JPanel {

14

15// identifier

16private int ID;

18// on-screen position

19private Point2D.Double position;

21// imageIcon to paint on screen

22private ImageIcon imageIcon;

23

24// stores all ImagePanel children

25private Set panelChildren;

26

27// constructor initializes position and image

28public ImagePanel( int identifier, String imageName )

29{

30super( null ); // specify null layout

31setOpaque( false ); // make transparent

32

33// set unique identifier

34ID = identifier;

35

36// set location

37position = new Point2D.Double( 0, 0 );

38setLocation( 0, 0 );

39

40// create ImageIcon with given imageName

41imageIcon = new ImageIcon(

42

getClass().getResource( imageName ) );

43

 

44Image image = imageIcon.getImage();

45setSize(

46

image.getWidth( this ), image.getHeight( this ) );

47

 

48// create Set to store Panel children

49panelChildren = new HashSet();

50

51 } // end ImagePanel constructor

52

Fig. 22.10 Class ImagePanel represents and displays a stationary object from the model (part 1 of 3).

1320

Java Media Framework and Java Sound (on CD)

Chapter 22

53// paint Panel to screen

54public void paintComponent( Graphics g )

55{

56super.paintComponent( g );

57

58// if image is ready, paint it to screen

59imageIcon.paintIcon( this, g, 0, 0 );

60}

61

62// add ImagePanel child to ImagePanel

63public void add( ImagePanel panel )

64{

65panelChildren.add( panel );

66super.add( panel );

67}

68

69// add ImagePanel child to ImagePanel at given index

70public void add( ImagePanel panel, int index )

71{

72panelChildren.add( panel );

73super.add( panel, index );

74}

75

76// remove ImagePanel child from ImagePanel

77public void remove( ImagePanel panel )

78{

79panelChildren.remove( panel );

80super.remove( panel );

81}

82

83// sets current ImageIcon to be displayed

84public void setIcon( ImageIcon icon )

85{

86imageIcon = icon;

87}

88

89// set on-screen position

90public void setPosition( double x, double y )

91{

92position.setLocation( x, y );

93setLocation( ( int ) x, ( int ) y );

94}

95

96// return ImagePanel identifier

97public int getID()

98{

99return ID;

100

}

101

 

102// get position of ImagePanel

103public Point2D.Double getPosition()

104{

Fig. 22.10 Class ImagePanel represents and displays a stationary object from the model (part 2 of 3).

Chapter 22

Java Media Framework and Java Sound (on CD)

1321

105return position;

106}

107

108// get imageIcon

109public ImageIcon getImageIcon()

110{

111return imageIcon;

112}

113

114// get Set of ImagePanel children

115public Set getChildren()

116{

117return panelChildren;

118}

119}

Fig. 22.10 Class ImagePanel represents and displays a stationary object from the model (part 3 of 3).

MovingPanel

Class MovingPanel (Fig. 22.11) is an ImagePanel subclass capable of changing its screen position according to its xVelocity and yVelocity (lines 20–21). The ElevatorView uses MovingPanel objects to represent moving objects from the model, such as the Elevator.

1// MovingPanel.java

2 // JPanel subclass with on-screen moving capabilities 3 package com.deitel.jhtp4.elevator.view;

4

5 // Java core packages

6import java.awt.*;

7 import java.awt.geom.*;

8 import java.util.*;

9

10// Java extension packages

11import javax.swing.*;

12

13 public class MovingPanel extends ImagePanel {

14

15// should MovingPanel change position?

16private boolean moving;

17

18// number of pixels MovingPanel moves in both x and y values

19// per animationDelay milliseconds

20private double xVelocity;

21private double yVelocity;

22

Fig. 22.11 Class MovingPanel represents and displays a moving object from the model (part 1 of 3).

1322

Java Media Framework and Java Sound (on CD)

Chapter 22

23// constructor initializes position, velocity and image

24public MovingPanel( int identifier, String imageName )

25{

26super( identifier, imageName );

27

28// set MovingPanel velocity

29xVelocity = 0;

30yVelocity = 0;

31

32 } // end MovingPanel constructor

33

34// update MovingPanel position and animation frame

35public void animate()

36{

37// update position according to MovingPanel velocity

38if ( isMoving() ) {

39

double oldXPosition = getPosition().getX();

40

double oldYPosition = getPosition().getY();

41

 

42

setPosition( oldXPosition + xVelocity,

43

oldYPosition + yVelocity );

44

}

45

 

46// update all children of MovingPanel

47Iterator iterator = getChildren().iterator();

49

while ( iterator.hasNext() ) {

50

MovingPanel panel = ( MovingPanel ) iterator.next();

51panel.animate();

52}

53} // end method animate

55// is MovingPanel moving on screen?

56public boolean isMoving()

57{

58return moving;

59}

60

61// set MovingPanel to move on screen

62public void setMoving( boolean move )

63{

64moving = move;

65}

66

67// set MovingPanel x and y velocity

68public void setVelocity( double x, double y )

69{

70xVelocity = x;

71yVelocity = y;

72}

73

Fig. 22.11 Class MovingPanel represents and displays a moving object from the model (part 2 of 3).

Chapter 22

Java Media Framework and Java Sound (on CD)

1323

74// return MovingPanel x velocity

75public double getXVelocity()

76{

77return xVelocity;

78}

79

80// return MovingPanel y velocity

81public double getYVelocity()

82{

83return yVelocity;

84}

85}

Fig. 22.11 Class MovingPanel represents and displays a moving object from the model (part 3 of 3).

Method animate (lines 35–53) moves the MovingPanel according to the current values of attributes xVelocity and yVelocity. If boolean variable moving (line 16) is true, lines 38–44 use attributes xVelocity and yVelocity to determine the next location for the MovingPanel. Lines 47–52 repeat the process for any children. In our simulation, ElevatorView invokes method animate and method paintComponent of class ImagePanel every 50 milliseconds. These rapid, successive calls move the MovingPanel object.

AnimatedPanel

Class AnimatedPanel (Fig. 22.12), which extends class MovingPanel, represents an animated object from the model (i.e., moving objects whose corresponding image changes continuously), such as a Person. The ElevatorView animates an AnimatedPanel object by changing the image associated with imageIcon.

1// AnimatedPanel.java

2 // MovingPanel subclass with animation capabilities

3 package com.deitel.jhtp4.elevator.view;

4

5 // Java core packages

6 import java.awt.*;

7 import java.util.*;

8

9 // Java extension packages

10 import javax.swing.*;

11

12 public class AnimatedPanel extends MovingPanel {

13

14// should ImageIcon cycle frames

15private boolean animating;

16

17// frame cycle rate (i.e., rate advancing to next frame)

18private int animationRate;

Fig. 22.12 Class AnimatedPanel represents and displays an animated object from the model (part 1 of 4).

1324

Java Media Framework and Java Sound (on CD)

Chapter 22

19private int animationRateCounter;

20private boolean cycleForward = true;

22// individual ImageIcons used for animation frames

23private ImageIcon imageIcons[];

24

25// storage for all frame sequences

26private java.util.List frameSequences;

27private int currentAnimation;

28

29// should loop (continue) animation at end of cycle?

30private boolean loop;

31

32// should animation display last frame at end of animation?

33private boolean displayLastFrame;

34

35// helps determine next displayed frame

36private int currentFrameCounter;

37

38// constructor takes array of filenames and screen position

39public AnimatedPanel( int identifier, String imageName[] )

40{

41super( identifier, imageName[ 0 ] );

42

43// creates ImageIcon objects from imageName string array

44imageIcons = new ImageIcon[ imageName.length ];

45

 

46

for ( int i = 0; i < imageIcons.length; i++ ) {

47

imageIcons[ i ] = new ImageIcon(

48

getClass().getResource( imageName[ i ] ) );

49

}

50

 

51

frameSequences = new ArrayList();

52

 

53

} // end AnimatedPanel constructor

54

 

55// update icon position and animation frame

56public void animate()

57{

58super.animate();

59

60// play next animation frame if counter > animation rate

61if ( frameSequences != null && isAnimating() ) {

62

 

63

if ( animationRateCounter > animationRate ) {

64

animationRateCounter = 0;

65

determineNextFrame();

66

}

67

else

68

animationRateCounter++;

69}

70} // end method animate

Fig. 22.12 Class AnimatedPanel represents and displays an animated object from the model (part 2 of 4).

Chapter 22

Java Media Framework and Java Sound (on CD)

1325

71

72// determine next animation frame

73private void determineNextFrame()

74{

75int frameSequence[] =

76

( int[] ) frameSequences.get( currentAnimation );

77

 

78// if no more animation frames, determine final frame,

79// unless loop is specified

80if ( currentFrameCounter >= frameSequence.length ) {

81

currentFrameCounter = 0;

82

 

83

// if loop is false, terminate animation

84

if ( !isLoop() ) {

85

 

86

setAnimating( false );

87

 

88

if ( isDisplayLastFrame() )

89

 

90

// display last frame in sequence

91

currentFrameCounter = frameSequence.length - 1;

92}

93}

94

95// set current animation frame

96setCurrentFrame( frameSequence[ currentFrameCounter ] );

97currentFrameCounter++;

98

99 } // end method determineNextFrame

100

101// add frame sequence (animation) to frameSequences ArrayList

102public void addFrameSequence( int frameSequence[] )

103{

104frameSequences.add( frameSequence );

105}

106

107// ask if AnimatedPanel is animating (cycling frames)

108public boolean isAnimating()

109{

110return animating;

111}

112

113// set AnimatedPanel to animate

114public void setAnimating( boolean animate )

115{

116animating = animate;

117}

118

119// set current ImageIcon

120public void setCurrentFrame( int frame )

121{

122setIcon( imageIcons[ frame ] );

Fig. 22.12 Class AnimatedPanel represents and displays an animated object from the model (part 3 of 4).

1326

Java Media Framework and Java Sound (on CD)

Chapter 22

 

 

 

123

}

 

124

 

 

125// set animation rate

126public void setAnimationRate( int rate )

127{

128animationRate = rate;

129}

130

131// get animation rate

132public int getAnimationRate()

133{

134return animationRate;

135}

136

137// set whether animation should loop

138public void setLoop( boolean loopAnimation )

139{

140loop = loopAnimation;

141}

142

143// get whether animation should loop

144public boolean isLoop()

145{

146return loop;

147}

148

149// get whether to display last frame at animation end

150private boolean isDisplayLastFrame()

151{

152return displayLastFrame;

153}

154

155// set whether to display last frame at animation end

156public void setDisplayLastFrame( boolean displayFrame )

157{

158displayLastFrame = displayFrame;

159}

160

161// start playing animation sequence of given index

162public void playAnimation( int frameSequence )

163{

164currentAnimation = frameSequence;

165currentFrameCounter = 0;

166setAnimating( true );

167}

168}

Fig. 22.12 Class AnimatedPanel represents and displays an animated object from the model (part 4 of 4).

Class AnimatedPanel chooses the ImageIcon object to be drawn on screen from among several ImageIcon objects stored in array imageIcons (line 23). Class AnimatedPanel determines the ImageIcon object according to a series of frame sequence references, stored in List frameSequences (line 26). A frame sequence is an array of

Chapter 22

Java Media Framework and Java Sound (on CD)

1327

integers holding the proper sequence to display the ImageIcon objects; specifically, each integer represents the index of an ImageIcon object in imageIcons. Figure 22.13 demonstrates the relationship between imageIcons and frameSequences (this is not a diagram of the UML). For example, frame sequence number

2 = { 2, 1, 0 }

refers to { imageIcon[ 2 ], imageIcon[ 1 ], imageIcon[ 0 ] }, which yields the image sequence { C, B, A }. In the view, each image is a unique .png file. Method addFrameSequence (lines 102–105) adds a frame sequence to List frameSequences. Method playAnimation (lines 162–167) starts the animation associated with the parameter frameSequence. For example, assume an AnimatedPanel object called personAnimatedPanel in class ElevatorView. The code segment

animatedPanel.playAnimation( 1 );

would generate the { A, B, D, B, A } image sequence using Fig. 22.13 as a reference. Method animate (lines 56–70) overrides method animate of superclass Moving-

Panel. Lines 61–69 determine the next frame of animation depending on attribute animationRate, which is inversely proportional to the animation speed—a higher value for animationRate yields a slower frame rate. For example, if animationRate is 5, animate moves to the next frame of animation every fifth time it is invoked. Using this logic, the animation rate maximizes when animationRate has a value of 1, because the next frame is determined each time animate runs.

Method animate calls determineNextFrame (lines 73–99) to determine the next frame (image) to display—specifically, it calls method setCurrentFrame (lines 120–123), which sets imageIcon (the current image displayed) to the image returned from the current frame sequence. Lines 84–92 of determineNextFrame are used for “looping” purposes in the animation. If loop is false, the animation terminates after one iteration. The last frame in the sequence is displayed if displayLastFrame is true, and the first frame in the sequence is displayed if displayLastFrame is false. We explain in greater detail in Appendix I how ElevatorView uses displayLastFrame for the Person and Door AnimatedPanels to ensure the proper display of the image. If loop is true, the animation repeats until stopped explicitly.

Sound Effects

We now discuss how we generate audio in our elevator simulation. We divide audio functionality between two classes—SoundEffects and ElevatorMusic. (these classes are not part of the Java packages, although SoundEffects uses the java.applet package and ElevatorMusic uses the javax.sound.midi package). Class SoundEffects (Figure 22.14) transforms audio (.au) and wave (.wav) files, containing such sounds as the bell ring and the person’s footsteps, into java.applet.AudioClip objects. In Appendix I, we list all AudioClips used in our simulation. Class ElevatorMusic (Fig. 22.15) plays a MIDI (.mid) file when the person rides the elevator. The ElevatorView object will play the AudioClip and ElevatorMusic objects to generate sound. All sound files are in the directory structure

com/deitel/jhtp4/elevator/view/sounds

1328

Java Media Framework and Java Sound (on CD)

Chapter 22

 

 

 

 

 

 

 

 

frameSequences

 

image sequences

 

 

imageIcons

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

0=

0

1

2

 

 

 

 

A

B

C

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

1=

0 1 3

1 0

 

 

A

B

D

B

A

 

 

A

 

B

 

C

 

D

 

 

 

 

 

 

 

 

 

 

 

2=

2

1

0

 

 

 

 

C

B

A

 

 

 

0

1

 

2

 

3

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

3=

3

2

2

0

 

 

 

D

C

C

A

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Fig. 22.13 Relationship between array imageIcons and List frameSequences.

(i.e., in the sounds directory where the classes for the view are located in the file system). In our simulation, we use sounds and MIDI files provided free for download by Microsoft at the Web site:

msdn.microsoft.com/downloads/default.asp

To download these sounds, click on “Graphics and Multimedia,” “Multimedia (General),” then “Sounds.”

1// SoundEffects.java

2// Returns AudioClip objects

3 package com.deitel.jhtp4.elevator.view;

4

5 // Java core packages

6 import java.applet.*;

7

8 public class SoundEffects {

9

10// location of sound files

11private String prefix = "";

13 public SoundEffects() {}

14

15// get AudioClip associated with soundFile

16public AudioClip getAudioClip( String soundFile )

17{

18try {

19

return Applet.newAudioClip( getClass().getResource(

20

prefix + soundFile ) );

21

}

22

 

23// return null if soundFile does not exist

24catch ( NullPointerException nullPointerException ) {

25return null;

26}

27}

Fig. 22.14 Class SoundEffects return AudioClip objects (part 1 of 2).

Chapter 22

Java Media Framework and Java Sound (on CD)

1329

28

29// set prefix for location of soundFile

30public void setPathPrefix( String string )

31{

32prefix = string;

33}

34}

Fig. 22.14 Class SoundEffects return AudioClip objects (part 2 of 2).

Class SoundEffects contains method getAudioClip (lines 16–27), which uses static method newAudioClip (of class java.applet.Applet) to return an

AudioClip object using the soundFile parameter. Method setPrefix (lines 30– 33) allows for changing the directory of a sound file (useful if we want to partition our sounds among several directories).

1// ElevatorMusic.java

2 // Allows for MIDI playing capabilities

3 package com.deitel.jhtp4.elevator.view;

4

5 // Java core packages

6 import java.io.*;

7 import java.net.*;

8

9 // Java extension packages

10 import javax.sound.midi.*;

11

12 public class ElevatorMusic implements MetaEventListener {

13

14// MIDI sequencer

15private Sequencer sequencer;

17// should music stop playing?

18private boolean endOfMusic;

20// sound file name

21private String fileName;

23// sequence associated with sound file

24private Sequence soundSequence;

25

26// constructor opens a MIDI file to play

27public ElevatorMusic( String file )

28{

29// set sequencer

30try {

31

sequencer = MidiSystem.getSequencer();

32

sequencer.addMetaEventListener( this );

33fileName = file;

34}

Fig. 22.15 Class ElevatorMusic plays music when a Person rides in the Elevator (part 1 of 3).

1330

Java Media Framework and Java Sound (on CD)

Chapter 22

35

36// handle exception if MIDI is unavailable

37catch ( MidiUnavailableException midiException ) {

38midiException.printStackTrace();

39}

40} // end ElevatorMusic constructor

41

42// open music file

43public boolean open()

44{

45try {

46

 

47

// get URL for media file

48

URL url = getClass().getResource( fileName );

49

 

50

// get valid MIDI file

51

soundSequence = MidiSystem.getSequence ( url );

52

 

53

// open sequencer for specified file

54

sequencer.open();

55sequencer.setSequence( soundSequence );

56}

57

58// handle exception if URL does not exist

59catch ( NullPointerException nullPointerException ) {

60 nullPointerException.printStackTrace();

61return false;

62}

63

64// handle exception if MIDI data is invalid

65catch ( InvalidMidiDataException midiException ) {

66

midiException.printStackTrace();

67

soundSequence = null;

68return false;

69}

70

71// handle IO exception

72catch ( java.io.IOException ioException ) {

73

ioException.printStackTrace();

74

soundSequence = null;

75return false;

76}

77

78// handle exception if MIDI is unavailable

79catch ( MidiUnavailableException midiException ) {

80 midiException.printStackTrace();

81return false;

82}

83

84return true;

85}

86

Fig. 22.15 Class ElevatorMusic plays music when a Person rides in the Elevator (part 2 of 3).

Chapter 22

Java Media Framework and Java Sound (on CD)

1331

87// play MIDI track

88public void play()

89{

90sequencer.start();

91endOfMusic = false;

92}

93

94// get sequencer

95public Sequencer getSequencer()

96{

97return sequencer;

98}

99

100// handle end of track

101public void meta( MetaMessage message )

102{

103if ( message.getType() == 47 ) {

104 endOfMusic = true;

105sequencer.stop();

106}

107}

108}

Fig. 22.15 Class ElevatorMusic plays music when a Person rides in the Elevator (part 3 of 3).

As we discussed in Section 22.7, Java 2 offers MIDI support. Class ElevatorMusic uses the javax.sound.midi package to play the MIDI file. Class ElevatorMusic listens for a MetaMessage event from the MIDI file. The sequencer generates a MetaMessage event. Class ElevatorMusic’s constructor (lines 27–40) of the constructor initializes the system’s MIDI sequencer and registers class ElevatorMusic for MetaMessage events from the sequencer. Method open (lines 43–85) opens the sequencer for a specified file and ensures the MIDI data is valid. Method play (lines 88–92) starts the sequencer and plays the MIDI file.

Conclusion

You have completed a substantial object-oriented design (OOD) process that was intended to help prepare you for the challenges of “industrial-strength” projects. We hope you have found the optional “Thinking About Objects” sections informative and useful as a supplement to the material presented in the chapters. In addition, we hope you have enjoyed the experience designing the elevator system using the UML. The worldwide software industry has adopted the UML as the de facto standard for modeling object-oriented software.

Although we have completed the design process, we have merely “scratched the surface” of the implementation process. We urge you to read Appendices G, H and I on the accompanying CD, which fully implement the design. These appendices translate the UML diagrams into a 3,465-line Java program for the elevator simulation. In these appendices, we present all code that we did not cover in the “Thinking About Objects” sections and a complete “walkthrough” of this code.

1.Appendix G presents the Java files that implement events and listeners

2.Appendix H presents the Java files that implement the model

1332

Java Media Framework and Java Sound (on CD)

Chapter 22

3. Appendix I presents the Java files that implement the view

We do not introduce an abundance of new material or UML design in these appen- dices—they simply serve to implement the UML-based diagram we have presented in previous chapters into a fully functional program. Studying the implementation in the appendices should hone the programming skills you have developed throughout the book and reinforce your understanding of the design process.

SUMMARY

Through the JMF API, programmers can create Java applications that play, edit, stream and capture many popular and high-quality media types.

JMF 2.1.1 supports popular media file types such as Microsoft Audio/Video Interleave (.avi), Macromedia Flash 2 movies (.swf), MPEG Layer 3 Audio (.mp3), Musical Instrument Digital Interface (MIDI;.mid), MPEG-1 videos (.mpeg, .mpg), QuickTime (.mov) and Sun Audio (.au).

The Java Sound API and its extensive sound processing capabilities. Java Sound is a lower-level API that supports many of the JMF’s internal audio capabilities.

A Player is a type of Controller in JMF that can process and play media clips. Playing media clips with interface Player can be as simple as specifying the media source, creating a Player for the media, obtaining the output media and controls GUI components from Player and displaying them. In addition, Players can access media from a capture device such as a microphone and from a Real-time transport protocol (RTP) stream—a stream of bytes sent over a network that can be buffered and played on the client computer.

Play media involves accessing the media, creating a Controller for the media and outputting the media. Before outputting the media, there is the option of formatting the media.

JMF provides lightweight video renderers compatible with Swing GUI components using Manager method setHint with parameter Manager.LIGHTWEIGHT_RENDERER and Boolean.TRUE.

A MediaLocator is similar to a URL, but it also supports RTP streaming session addresses and capture device locations.

Invoke Manager method createPlayer to create a Player object that references a media player. Method createPlayer opens the specified media source and determines the appropriate player for the media source. A NoPlayerException occurs if no appropriate player can be found for the media clip.

Class Manager provides static methods that enable programs to access to most JMF resources.

Throughout the media-handling process, Players generate ControllerEvents that ControllerListeners listen for. Class ControllerAdapter, which implements methods of interface ControllerListener.

Controllers use state transitions to confirm their position in the media processing algorithm.

Player’s realize method to confirm all resources necessary to play media. Method realize places the Player in a Realizing state where the player interacts with its media sources. When a Player completes realizing, it generates a RealizedCompleteEvent—a type of ControllerEvent that occurs when a Player completes its transition to state Realized.

Player method prefetch causes the Player to obtain hardware resources for playing the media and begin buffering the media data. Buffering the media data reduces the delay before the media clip plays because media reading can take a long time.

Chapter 22

Java Media Framework and Java Sound (on CD)

1333

Invoke Player method getVisualComponent method to obtain the visual component of a video. Invoke Player method getControlPanelComponent to return the player’s GUI controls.

When the media clip ends, the Player generates a ControllerEvent of type EndOfMediaEvent.

Player method setMediaTime sets the position of the media to a specific time in the media.

Invoking Player method start starts media playback. It also buffers and realizes the player if that has not been done.

Capture devices such as microphones have the ability to convert analog media into digitized media. This type of media is known as captured media.

Class DataSource abstracts the media source to allow a program to manipulate it and provides a connection to the media source.

Interface Processor allows a program to manipulate data at the various processing stages. It extends interface Player and provides more control over media processing.

Monitoring allows you to hear or see the captured media as it is captured and saved. A MonitorControl and other control objects obtained from Controller by invoking method getControl.

JMF provides class Format to describe the attributes of a media format, such as the sampling rate (which controls the quality of the sound) and whether the media should be in stereo or mono format. FormatControl objects that allow us to format objects that support format controls.

Class CaptureDeviceManager enables a program to access capture device information.

A CaptureDeviceInfo object provides the essential information necessary of a capture device’s DataSource.

Invoke Manager method createDataSource to obtain the DataSource object that of that media location.

Manager method createRealizedProcessor creates a realized Processor object that can start processing media data. The method requires as an argument a ProcessorModel object containing the specifications of the Processor.

Use a ContentDescriptor to describe the content-type of output from a Processor. FileTypeDescriptor specifies the a file media content.

Call Processor method getTrackControls to get each track’s controls.

An object that implements interface DataSink enables media data to be output to a specific lo- cation—most commonly a file. Manager method createDataSink receives the DataSource and MediaLocator as arguments to create a DataSink object.

Register a DataSinkListener to listen for DataSinkEvents generated by a DataSink. A program can call DataSinkListener method dataSinkUpdate when each DataSinkEvent occurs. A DataSink causes an EndOfStreamEvent when the capture stream connection closes

Streaming media refers to media that is transferred from a server to a client in a continuous stream of bytes. Streaming media technology loads media data into buffers before displaying media.

JMF provides a streaming media package that enables Java applications to send and receive streams of media in the formats discussed earlier in this chapter. JMF uses the industry-standard Real-Time Transport Protocol (RTP) to control media transmission. RTP is designed specifically to transmit real-time media data.

Use a DataSink or a RTPManager to stream media. RTPManagers provide more control and versatility for the transmission. If an application sends multiple streams, the application must have

1334

Java Media Framework and Java Sound (on CD)

Chapter 22

an RTPManager for each separate streaming session. Both require the DataSource obtained from Processor’s getOutput method.

The URL of RTP streams is in format: rtp://<host>:<port>/<contentType>

Formatting the media can only be done when the Processor has been configured. To notify the program when it completes Processor configuration, register a ControllerListener to notify the program that it has completed configuring. A ConfigureCompleteEvent occurs when Processor completes configuration.

Processor method setContentDescriptor sets the stream to an RTP-enabled format with ContentDescriptor.RAW_RTP parameter.

TrackControl interface allow the formats of the media tracks to be set.

SessionAddress contains an IP addresses and port number used in the streaming process.

RTPMangers use SessionAddresses to stream media.

Invoke RTPManager method initialize to initialize the local streaming session with the local session address as the parameter. Invoke RTPManager method addTarget to add the destination session address as the client recipient of the media stream. To stream media to multiple clients, call RTPManger method addTarget for each destination address.

RTPManager method removeTargets closes streaming to specific destinations. RTPManager method dispose release the resources held by the RTP sessions

The Java Sound API provides classes and interfaces for accessing, manipulating and playing Musical Instrumental Data Interface (MIDI) and sampled audio.

A sound card is required to play audio with Java Sound. Java Sound throws exceptions when it accesses audio system resources to process audio on a computer that does not have a sound card.

Programmers can use package javax.sound.sampled to play sampled audio file formats, which includes Sun Audio (.au), Wave (.wav) and AIFF (.aiff).

To process audio data, we can to use a Clip line that allows the flow of raw digital data to audio data we can listen to.

An AudioInputStream object to point to the audio stream. Class AudioInputStream (a subclass of InputStream) provides access to the audio stream contents.

The length of video and audio clips is measured in frames. Each frame represents data at a specific time interval in the audio file.

The algorithm for playing sampled audio supported by Java Sound is as follows: obtain an AudioInputStream from an audio file, obtain a formatted Clip line, load the AudioInputStream into the Clip line, start the data flow in the Clip line.

All Lines generate LineEvents that can be handled by LineListener. The first step to sampled audio playback involves obtaining the audio stream from an audio file.

Class AudioSystem enables a program to access many audio system resources required to play and manipulate sound files.

Method getAudioInputStream throws an UnsupportedAudioFileException if the specified sound file is a non-audio file or contains a sound clip format that is not supported by Java Sound.

Method getLine requires a Line.Info object as an argument, which specifies the attributes of the line the AudioSystem should obtain.

We can use a DataLine.Info object that specifies a Clip data line, a general encoding format and a buffer range. We need to specify a buffer range so the program can determine the best buffer size given a preferred range.

Chapter 22

Java Media Framework and Java Sound (on CD)

1335

DataLine.Info objects specify information about a Clip line, such as the formats supported by the Clip. The DataLine.Info object constructor receives as arguments the Line class, the line’s supported AudioFormats, the minimum buffer size and the maximum buffer size in bytes.

AudioSystem method getLine and Clip method open throw LineUnavailableExceptions if another application is using the requested audio resource. Clip method open also throws an IOException if open is unable to read the specified AudioInputStream.

Invoke Clip method start to begin audio playback.

When a LineEvent occurs, the program calls LineListener method update to process the event. The four LineEvent types are defined in class LineEvent.Type. The event types are

CLOSE, OPEN, START and STOP.

Method close of class Line stops audio activity and closes the line—which releases any audio resources obtained previously by the Line.

Clip method loop can be called with parameter Clip.LOOP_CONTINUOSLY. to replay the audio clip forever.

Invoking method stop of interface Clip only stops data activity in the Line. Invoking method start resumes data activity.

MIDI (Musical Instrument Digital Interface) music can be created through a digital instrument, such as an electronic keyboard (synthesizer), or through packaged software synthesizers. A MIDI synthesizer is a device that can produce MIDI sounds and music.

The MIDI specification provides detailed information on the formats of a MIDI file. For detailed information on MIDI and its specification, visit their official Web site at www.midi.org. Java Sound’s MIDI package allows developers to access the data that specify the MIDI, but it does not provide support for the specification.

Interpretation of MIDI data varies between synthesizers and will sound different with different instruments. Package javax.sound.midi enables program to manipulate, play and synthesize MIDI. There are three MIDI types—0 (the most common), 1 and 2. Java Sound supports MIDI files with .mid extensions and .rmf (Rich Music Format).

Some file parsers in various operating systems are unable to interpret the MIDI file as a MIDI file that Java can play.

MIDI playback is accomplished by a MIDI sequencer. Specifically, sequencers can play and manipulate a MIDI sequence, which is the data formula that tells a device how to handle the MIDI data.

Often, MIDI is referred to as a sequence, because the musical data in MIDI is composed of a sequence of events. The simplicity of MIDI data enables us to view each event individually and learn the purpose of each event. The process to MIDI playback involves accessing a sequencer, loading a MIDI sequence or a MIDI file into a sequencer and starting the sequencer.

Method getSequence also can obtain a MIDI sequence from a URL or an InputStream. Method getSequence throws an InvalidMidiDataException if the MIDI system detects an incompatible MIDI file.

Interface Sequencer, which extends interface MidiDevice (the super-interface for all MIDI devices), represents the standard device to play MIDI data.

Sequencer’s open method prepares to play a Sequence. Sequencer method setSequence loads a MIDI Sequence into the Sequencer and throws an InvalidMidiException if the Sequencer detects an unrecognizable MIDI sequence. Sequencer method play begins playing the MIDI sequence.

1336

Java Media Framework and Java Sound (on CD)

Chapter 22

A MIDI track is a recorded sequence of data; MIDIs usually contain multiple tracks. MIDI tracks are similar to CD tracks except that the music data in MIDI are played simultaneously. Class Track (package javax.sound.midi) provides access to the MIDI music data stored in the MIDI tracks.

MIDI data in MIDI tracks are represented by MIDI events. MIDI events are the holders of the MIDI action and the time when the MIDI command should occur. There are three types of MIDI message—ShortMessage, SysexMessage and MetaMessage. ShortMessages provide instructions, such as specific notes play, and can configure options, such when a MIDI starts. The other two less-used messages are exclusive system messages called SysexMessage and MetaMessages which may tell a device that the MIDI has reached the end of a track. This section deals exclusively with ShortMessages that play specific notes. Each MidiMessage is encapsulated in a MidiEvent and a sequence of MidiEvents form a MIDI track.

Each MidiEvent’s getTick method provides the time when the event takes place (time stamp).

ShortMessage method getCommand returns the command integer of the message. ShortMessage method getData1 returns the first status byte of the message. ShortMessage method getData2 returns the second status byte. The first and second status bytes vary in interpretation according to the type of command in ShortMessage.

General MIDI recording is accomplished through a sequencer. Interface Sequencer provides simple methods for recording—assuming the transmitters and receivers of MIDI devices are “wired” correctly.

After setting up a sequencer and an empty sequence, a Sequencer object can invoke its startRecording method to enable and start recording on the empty track. Method recordEnable of interface Sequencer takes a Track object and a channel number as the parameters to enable recording on a track.

Method write of class MidiSystem writes the sequence to a specified file.

An alternative method to record MIDI without having to deal with transmitters and receivers is to create events from ShortMessages. The events should be added to a track of a sequence.

Interface Synthesizer is a MidiDevice interface which enables access to MIDI sound generation, instruments, channel resources, and sound banks.

A SoundBank is the container for various Instruments, which tell the computer how to sound a specific note and are programmed algorithms of instructions. Different notes on various instruments are played through a MidiChannel on different tracks simultaneously to produce symphonic melodies.

Acquiring any MIDI resources throws a MidiUnavailableException if the resource is unavailable.

Invokes Synthesizer’s getChannels method to obtain all 16 channels from the synthesizer. A MidiChannel can sound a note by calling its noteOn method with the note number (0- 127) and volume as parameters. MidiChannel’s noteOff method turns off a note with just the note number parameter.

Synthesizer’s getAvailableInstruments method obtains the default instrument programs of a synthesizer. One can also import more instruments by loading a customized sound bank through method loadAllInstruments (SoundBank) in interface Synthesizer. A sound bank usually has 128 instruments. MidiChannel’s programChange method loads the desired instrument program into the synthesizer.

Invoke Receiver’s send method with a MidiMessage and a time stamp as its parameters to send MIDI message to all its transmitters.

Chapter 22 Java Media Framework and Java Sound (on CD) 1337

TERMINOLOGY

addControllerListener method of

DataLine interface

Controller

DataLine.Info class

addDataSinkListener method of

DataSink interface

DataSink

DataSinkEvent class

addLineListener method of Line

DataSinkListener interface

addMetaEventListener method of

dataSinkUpdate method of

Sequencer

DataSinkListener

addTarget method of RTPManager

DataSource class

AudioFormat class

deleteTrack method of Sequence

AudioFormat.Encoding.PCM_SIGNED

device ports

AudioInputStream class

Direct Sound

AudioSystem class

dispose method of RTPManager

Boolean.TRUE

encoding

broadband

endOfMedia method of

CannotRealizeException class

ControllerAdapter

capture

EndofMediaEvent class

capture device

EndofStreamEvent class

captured media

FileTypeDescriptor class

CaptureDevice interface

FileTypeDescriptor.QUICKTIME

CaptureDeviceInfo class

Format class

CaptureDeviceManger class

FormatControl interface

Clip interface

frames

Clip.class

get method of Track

Clip.LOOP_CONTINUOUSLY

getAudioInputStream method of

Clock interface

AudioSystem

close method of Controller

getBank method of Patch

close method of Line

getChannels method of Synthesizer

close method of MidiDevice

getCommand method of ShortMessage

configure method of Processor

getControlComponent method of Control

configureComplete method of

getControlPanelComponent method of

ControllerAdapter

Player

ConfigureCompleteEvent class

getData1 method of ShortMessage

Controller.Prefetching

getData2 method of ShortMessage

Controller.Prefeteched

getDataOutput method of Processor

Controller.Realized

getDeviceList method of

Controller.Realizing

CaptureDeviceManager

Controller.Started

getFormat method of AudioFormat

Controller.Stopped

getFormat method of FormatControl

ControllerAdapter class

getFormatControls method of

ControllerEvent class

CaptureDevice

ControllerListener interface

getFrameLength method of

createDataSink method of Manager

AudioInputStream

createDataSource method of Manager

getFrameSize method of AudioFormat

createPlayer method of Manager

getLine method of AudioSystem

createProcessor method of Manager

getLocator method of

createRealizedProcessor method of

CaptureDeviceInfo

Manager

getMessage method of MidiEvent

createSendStream method of RTPManagergetMidiFileTypes method of MidiSystem

createTrack method of Sequence

getPatch method of Instrument

1338

Java Media Framework and Java Sound (on CD)

Chapter 22

getProgram method of Patch

MidiEvent class

 

getReceiver method of MidiDevice

MidiMessage class

 

getResolution method of Sequence

MidiSystem class

 

getSequence method of MidiSystem

MidiUnavailableException class

getSequencer method of MidiSystem

mixers

 

getSupportedFormats method of

MonitorControl interface

 

FormatControl

monitoring

 

getSynthesizer method of MidiSystem

MP3

 

getTargetFormat method of AudioSystemMPEG-1

 

getTick method of MidiEvent

network ports

 

getTrackControls method of Processor

newInstance method of RTPManager

getTracks method of Sequence

NoDataSinkException class

 

getTransmitter method of MidiDevice

NoDataSourceException class

getType method of LineEvent

NoPlayerException class

 

getVisualComponent method of Player

NoProcessorException class

 

initialize method of RTPManager

noteOff method of MidiChannel

Instrument class

noteOn method of MidiChannel

InvalidMidiException class

open method of Clip

 

InvalidSessionAddress class

open method of DataSink

 

isEnabled method of FormatControl

open method of MidiDevice

 

isLineSupported method of AudioSystemoutput format

 

Java Media Framework

packetized data

 

Java Sound

Patch class

 

javax.media package

pitch

 

javax.media.control package

Player interface

 

javax.media.datasink package

pre-buffer

 

javax.media.format package

prefetchComplete method of

 

javax.media.protocol package

ControllerAdapter

 

javax.media.rtp package

PrefetchCompleteEvent class

javax.sound.midi package

pre-process

 

javax.sound.sampled package

Processor interface

 

JOptionPane.CLOSED_OPTION

Processor.Configured

 

JOptionPane.DEFAULT_OPTION

Processor.Configuring

 

JOptionPane.OK_OPTION

ProcessorModel class

 

Line interface

propagation delay

 

LineEvent class

protocol

 

LineEvent.Type.STOP

QuickTime

 

LineListener interface

realize method of Controller

LineUnavailableException class

realizeComplete method of

 

loop method of Clip

ControllerAdapter

 

Manager class

RealizeCompleteEvent class

 

Manger.LIGHTWEIGHT_RENDERER

Receiver interface

 

media

 

recordEnable method of Sequencer

media clip

 

removeTargets method of RTPManager

media location

RMF (Rich Music Format)

 

media tracks

RTP (Real-time Transport Protocol)

 

MediaLocator class

RTPManger class

 

MIDI (Musical Instrument Digital Interface)

SecurityException class

 

MIDI Specification

send method of Receiver

 

MidiChannel interface

SendStream interface

 

Chapter 22

Java Media Framework and Java Sound (on CD)

1339

Sequence class

 

start method of Player

 

Sequence.PPQ

 

start method of SendStream

 

Sequencer interface

 

start method of Sequencer

 

SessionAddress class

 

startRecord method of Sequencer

 

SessionAddress class

 

stop method of DataLine

 

SessionEvent class

 

stop method of DataSink

 

SessionListener interface

stop method of Sequencer

 

setContentDescriptor method of

stopRecord method of Sequencer

 

Processor

 

streaming media

 

setFormat method of FormatControl

streams

 

setHint method of Manager

synchronization

 

setMediaTime of Clock

 

synthesis

 

setMessage method of ShortMessage

Synthesizer interface

 

setReceiver method of Transmitter

teleconferencing

 

setSequence method of Sequencer

tempo

 

ShortMessage class

 

time stamp

 

ShortMessage.NOTE_OFF

Track class

 

ShortMessage.NOTE_ON

 

TrackControl interface

 

ShortMessage.PROGRAM_CHANGE

Transmitter interface

 

simulation

 

UnsupportedAudioFileException class

size method of track

 

UnsupportedFormatException class

SoundBank interface

 

video conference

 

start method of DataLine

Video for Windows

 

start method of DataSink

write method of MidiSystem

 

SELF-REVIEW EXERCISES

22.1Fill in the blanks in each of the following.

a)

Class

 

 

provides access to many JMF resources.

 

 

 

 

 

 

 

 

b)

In addition to locations of media files stored on the local computer, a

 

can

 

also specify the location of capture devices and RTP sessions.

 

 

c)

Class

 

 

provides access to sampled audio system resources while class

 

 

 

 

 

provides access to MIDI system resources.

 

 

 

 

 

 

 

 

d)

An event of type

 

 

 

 

 

 

indicates that a Controller has establish communica-

 

tions with the media source.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

e)

Method createRealizedProcessor takes a

 

 

 

as an argument.

 

 

f)

In order, the Processor’s

states

are: Unrealized,

 

 

,

 

,

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

,

 

 

,

 

 

 

,

 

 

 

 

and Started.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

g)

Constant

 

 

 

 

 

specifies that the Processor should output media in QuickTime

 

format.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

h)

To stream media, we can use a

 

 

 

 

or a

 

.

 

 

 

 

 

 

i)objects set the stream formats for capture devices.

j)

Invoking Clip method

 

with constant

 

 

as an argument replays a

 

sampled audio file continuously.

 

 

 

 

 

k)

A MIDI

 

 

contains multiple tracks, which contain a sequence of MIDI

 

 

 

that each encapsulate a MIDI

 

 

.

 

22.2State whether each of the following is true or false. If false, explain why.

a)Manager method setHint can be used to specify that the visual component of a media clip should be rendered using lightweight GUI components.

b)A ControllerListener handles events generated by a DataSink.

c)Only objects that implement interface Processor can play media.

1340

Java Media Framework and Java Sound (on CD)

Chapter 22

d)A Player cannot access media from capture devices; a Processor must be used for this purpose.

e)A Clip plays MIDI Sequences.

f)MIDI playback stops automatically when the Sequencer reaches the end of a MIDI

Sequence.

g)An RTPManger can stream an entire media file regardless of the number of tracks in the file.

h)Method createPlayer throws a NoDataSourceException if it is unable to locate the specified media data source.

ANSWERS TO SELF-REVIEW EXERCISES

22.1 a) Manager. b) MediaLocator. c) AudioSystem, MidiSystem. d) RealizeCompleteEvent. e) ProcessorModel. f) Configuring, Configured, Realizing, Realized,

Prefetching, Prefetched. g) FileTypeDescriptor.QUICKTIME. h) DataSink, RTPManager. i) FormatControl. j) loop, Clip.LOOP_CONTINUOUSLY. k) Sequence, events, message.

22.2The answers to Self-Review Exercise 3.2 are as follows:

a)True.

b)False. A DataSinkListener handles DataSinkEvents generated by a DataSink.

c)False. Objects that implement Player or Processor can play media.

d)False. Both a Processor and a Player can access media from capture devices.

e)False. A Sequencer plays MIDI sequences.

f)True.

g)False. Each RTPManager can stream only one track.

h)False. Method createPlayer throws a NoPlayerException if it is unable to locate the specified media data source.

EXERCISES

22.3 Wave audio clips are commonly used to play sounds that alert the user of a problem in a program. Typically, such sounds are accompanied by error-message dialogs. Modify the DivideByZeroTest example of Fig. 14.1 to play an error-message sound (in addition to displaying an error message dialog) if the user enters an invalid integer or attempts to divide by zero. Preload a compatible sound clip using a Clip line as demonstrated in Fig. 22.5. The Clip line needs to support only the format of the chosen sound clip. There should be a separate method that invokes the playback of the clip. When the program detects an exception, it should call this method to play the error message sound. After each clip playback, the program needs to rewind the clip by invoking Clip’s method setFramePosition with the frame position as the argument, so that the clip can replay from its beginning position.

22.4 Incorporate MIDI file playback capabilities, as demonstrated in class MidiData (Fig. 22.7), into the ClipPlayer demo. Class ClipPlayer should have separate methods for obtaining MIDI sequence data and for playing back the sequence with a sequencer.

22.5 The SimplePlayer demo (Fig. 22.7) demonstrated JMF’s media playback (videos, capture media) capabilities using interface Player. Using the SimplePlayer demo as a guideline, develop a karaoke application in which one portion of the program plays a music/video file (preferably without lyrics) while another portion of the program simultaneously captures the user’s voice. The program should start playback and capture as soon as it obtains the media. It is important that the program allows the user to control both the capture and music, so the control GUIs of each media should be displayed. When the media file finishes playing, the voice capture should cease and the program

Chapter 22

Java Media Framework and Java Sound (on CD)

1341

should reset the music to the beginning. The program should close all Player-related resources when the user terminates the program.

22.6Modify your solution to Exercise 3.5 by implementing the program using interface Processor. Create a Processor that is ready to display media with no format or output specifications. The voice capture should not end and the media should not rewind when the media finishes playing. Deallocate Processor-related resources when the user opens a new file or closes the program. All other program details remain the same as specified in Exercise 3.5.

22.7Referring to the file saving process demonstrated in class CapturePlayer (Fig. 22.2), modify your solution to Exercise 22.6 by saving both audio streams to two separate QuickTime files. Specify the media tracks to be in AudioFormat.IMA4 encoding. The program should display file saver dialogs for each audio file saver and a message when the saving completes or stops. There should be separate data writers for each audio stream. The program should close the data writers when there is no more data to process or when the user terminates the program. DataSinkEvent method getSourceDataSink is available to obtain the DataSink that is generating the DataSinkEvent. Use MonitorControls to monitor both audio streams, so there is no need to display video or default user controls. MonitorControl method setEnabled is available to enable monitoring of the audio streams. Display one of the MonitorControls in a dialog box. Make sure to close Processor resources when there is no more data from the media file or when the user opens another file or terminates the program.

22.8Modify class MidiSynthesizer (Fig. 22.9) into an application where the user can play violin notes by pressing the computer keyboard keys. Use the virtual key code of the keys to specify the note number that the synthesizer should play. The violin’s program number is 40. Use the first and ninth channel to sound the notes at the same time. The ninth channel may generate a different version of the violin notes.

SPECIAL SECTION: CHALLENGING MULTIMEDIA PROJECTS

The preceding exercises are keyed to the text and designed to test the reader’s understanding of fundamental JMF and Java Sound concepts. This section includes a collection of advanced multimedia projects. The reader should find these problems challenging, yet entertaining. The problems vary considerably in difficulty. Some require an hour or two of program writing and implementation. Others are useful for lab assignments that might require two or three weeks of study and implementation. Some are challenging term projects. [Note: Solutions are not provided for these exercises.].

22.9Modify the ClipPlayer (Fig. 22.5, Fig. 22.6) demo to provide a replay checkbox that allows the user to replay the sampled audio file.

22.10Modify the RTPServer demo (Fig. 22.3) to enable transmission of the audio portions of media files to two clients. The application testing class should have twice the number of IP and port number inquiry dialog boxes. The program can check for audio formats by matching track control formats of the media to be instances of AudioFormat (class AudioFormat).

22.11Many Web sites are able to play video clips. The SimplePlayer (Fig. 22.1) program can be an applet. Simplify the SimplePlayer program to an applet that plays a preloaded media clip on a web page. Insert this applet tag into your HTML file:

<applet code = AppletName.class width = # height = # > <param name = file value = "sample.mov" >

</applet>

22.12 Modify class MidiRecord (Fig. 22.8) and class MidiData (Fig. 22.7) to create a new application class that duplicates MIDI files by recording the sequence to a new file. Play the sequence

1342

Java Media Framework and Java Sound (on CD)

Chapter 22

using MidiData and use its Transmitter to transmit MIDI information to the Receiver of

MidiRecord.

22.13Modify your solution to Exercise 22.6 to create a streaming karaoke application in which the application streams only the video portion of a music video and the sound stream is replaced by a voice capture stream. [Note: If the video format contains only one track for both audio and video, the application cannot choose to stream only the video portion of the track.]

22.14Modify class MidiData (Fig. 22.7) to load all tracks of a MIDI file and revise class MidiDemo (Fig. 22.10) to enable the user to select the playback of each individual track displayed in a JList selector panel. Allow the user to replay the sequence forever.

22.15Implement an MP3 player with a file list window using Vectors and a JList.

22.16Modify class MidiRecord (Fig. 22.8) and class MidiDemo (Fig. 22.10) to allow the user to record MIDI to individual tracks stored in a Vector. Playback of the recorded MIDI should play all MIDI tracks simultaneously.

22.17Currently the MidiDemo program (Section 22.7) records synthesized music with the first available instrument (i.e., Grand Piano). Modify class MidiDemo so that music will be recorded with a user-selected instrument, and allow the user to change the instrument during recording. Also allow the user to import their own sound banks. Make changes to classes MidiSynthesizer, MidiData and MidiRecord as needed. (Hint: The command parameter to change instrument is Short-

Message.PROGRAM_CHANGE)

22.18Modify the SimplePlayer demo (Fig. 22.1) to support multiple media players. Present each media clip in its own JInternalFrame. The program needs to create separate Players for each media clip and should register a ControllerListener for each player. ControllerEvent method getSourceController is available to obtain the controller generating the ControllerEvent. Implement the program using a dynamic data structure such as a Vector to store the multiple Players.

22.19Modify your solution to Exercise 3.7 to save both media streams to one file and play the combined stream. Use Manager method createMergingDataSource, which receives an array of DataSource objects, to save both the capture stream and the music stream into one stream, whose content-type will be MIXED. The program should obtain the output DataSources from the Processors as the DataSource objects to be merged. The program must also obtain a duplicate DataSource (of the merged DataSource) for creating the Player for that DataSource. To

do this, use Manager method createCloneableDataSource to create a Cloneable

DataSource with the merged DataSource as the argument. Duplicate the DataSource for the player by invoking method createClone of interface Cloneable on the DataSource (similar to obtaining the FormatControls of a CaptureDevice DataSource in the CapturePlayer demo (Fig. 22.2) ).

22.20A program can record MIDI without the use of transmitters and receivers by manually creating MidiMessages, placing them in MidiEvents, and adding these events to a track. In addition to the MidiMessage argument, a program must specify a time stamp to create the MidiEvent, expressed in ticks (i.e. milliseconds of long type), so the program must obtain the system’s current time in milliseconds, which can be obtained from System method currentTimeMillis. Track method add is available to add events to a track. Create an acoustics table (e.g. drums, cymbals, etc.) where the user can selected a sequence of instruments to play. Allow the user to save the recorded MIDI sequence to a file.

22.21Create a peer-to-peer teleconferencing kit that enables users to talk to and hear each other. To listen to each other, each user must open an RTP session for the capture stream. A program can open an RTP stream with a MediaLocator specifying the RTP session address. Then, the program

Chapter 22

Java Media Framework and Java Sound (on CD)

1343

can use the MediaLocator to create a Player for the RTP stream. The program can send the voice capture as demonstrated in the RTPManager demo (Fig. 22.3). To send the voice capture to more than two people, use RTPManagers for each separate session and call its addTarget method to add each recipient’s session address as a destination of the capture stream. This is referred to as multicast-unicast sessions.

22.22Using the “piano player” driver (Section 22.7.4 discusses the driver) from class MidiDemo (Fig. 22.10) and image animation functions from Chapter 18, write a program that displays a bouncing ball whose pinnacle height is specified by the note numbers (of a ShortMessage in a MidiEvent) of a loaded track in a MIDI file. The program should use the duration ticks of the MidiEvent as the duration of the bounce.

22.23Most karaoke music videos are in MPEG format, for which JMF provides an MpegAudioControl interface to control the audio channels. For multilingual and karaoke MPEG videos, channel layers direct the main audio to one of two audio streams (e.g. english-dubbed audio stream) or both audio streams (e.g. both music and song channels turned on in karaoke videos). As an additional feature for MPEG videos to your solution to Exercise 3.6, obtain and display the control GUI component from a MpegAudioControl, if any, or display a customized radio button GUI selector to let the user select the channel layout of the MPEG audio. Interface MpegAudioControl provides method setChannelLayout to set the audio channel layout for MPEG videos, with the channel layout as the argument. (Refer to the use of MonitorControl in Fig. 22.2)

22.24Create a multimedia-rich Tic-Tac-Toe game that plays sampled audio sounds when a player makes a valid move or makes an invalid move. Use a Vector to store preloaded AudioInputStreams representing each audio clip. Use a Clip line to play sounds in response to the user interactions with the game. Play continuous MIDI background music while the game is in progress. Use the JMF’s interface Player to play a video when a player wins.

22.25Java Sound’s MIDI package can access MIDI software devices as well as hardware devices. If you have a MIDI keyboard that the computer can detect or one that can be plugged into a MIDI IN port of a sound card, Java Sound can access that keyboard. Use synthesizers, receivers, transmitters and sequencers to allow the user to record MIDI synthesized by the electronic keyboard. MidiSystem method getMidiDeviceInfo is available to obtain all detectable MIDI devices’ information (array of MidiDevice.Info objects). Use MidiSystem method getMidiDevice with a MidiDevice.Info argument to obtain the specified MIDI device resource.

22.26Enhance the MidiDemo program to allow for more configurations such as tempo, control and replay. Sequencers can implement MetaEventListeners to handle MetaMessages and ControlEventListeners to handle ShortMessage.CONTROL_CHANGE commands (see the MIDI specification for the type of changes and the various MetaEvents). Interface Sequencer also provides many configuration and control methods that affect sequencer playback.

22.27Enhance the RTPServer program (Fig. 22.3, Fig. 22.4) to a video distribution server where a live video feed from a video capture device (e.g., VFW TV card, digital cameras) is broadcast to everyone in the network. Use the IP address ending with .255 (i.e. to create a SessionAddress) to broadcast to everyone in the network subnet. A server program should have access to stream transmission status, error controls and delay management. Package javax.media.rtp provides many interfaces to handle stream configurations and statistics. Package javax.media.rtcp allows the user to access RTP session reports. Package javax.media.rtp.event contains many events generated during an RTP session that can be used to perform RTP enhancements at those stages in the session. Package javax.media.control provides several control interfaces useful in RTP sessions.

22.28Enhance the media player application solution to Exercise 3.18 by adding editing features to the program. First add a replay checkbox. Although a Processor is more suitable for control tasks than a Player is, one can also use both interfaces by creating a Player for the output Data-

1344

Java Media Framework and Java Sound (on CD)

Chapter 22

Source from the Processor. Control features should include track formatting, frame control setting (interface FrameRateControl), buffer control (interface BufferControl), and quality control (interface QualityControl). Include a program option that allows the user to save media clips given the settings of these controls. For capture devices, there is a PortControl interface available to control their ports of devices. These interfaces are in package javax.media.control. In package javax.media, there are other interfaces such as Codec and Effect that enable further rendering and processing of media to specific media formats. Allow the user to import new codecs. Also implement an editing feature which enables the user to extract certain portions of a media clip. (Hint: set the media position of a media clip and obtain the Processor output at the marked positions.)

22.29Package javax.media.sound offers many audio system resources. Use this package to create a sound capture program that allows the users to save the capture stream in their desired formats, bit rates, frequencies and encodings.

22.30Create a visualization studio that displays graphics bars that synchronize with sampled audio playback.

22.31Extend MP3 playback support for class ClipPlayer (Fig. 22.5) using classes in package javax.media.sound.spi. The MP3 encoding process uses the Huffman algorithm.

22.32(Story Teller) Record audio for a large number of nouns, verbs, articles, prepositions, etc. Then use random number generation to forms sentences and have your program speak the sentences.

22.33(Project: Multimedia Authoring System) Develop a general-purpose multimedia authoring system. Your program should allow the user to form multimedia presentations consisting of text, audios, images, animations and eventually, videos. Your program lets the user weave together a presentation consisting of any of these multimedia elements that are selected from a catalog your program displays. Provide controls to allow the user to customize the presentation dynamically as the presentation is delivered.

22.34(Video Games) Video games have become wildly popular. Develop your own Java video game program. Have a contest with your classmates to develop the best original video game.

22.35(Physics Demo: Bouncing Ball) Develop an animated program that shows a bouncing ball. Give the ball a constant horizontal velocity. Allow the user to specify the coefficient of restitution, e.g., a coefficient of restitution of 75% means that after the ball bounces it returns to only 75% of its height before it was bounced. Your demo should take gravity into effect—this will cause the bouncing ball to trace a parabolic path. Track down a “boing” sound (like a spring bouncing) and play the sound every time the ball hits the ground.

22.36(Physics Demo: Kinetics) If you have taken physics, implement a Java program that will demo concepts like energy, inertia, momentum, velocity, acceleration, friction, coefficient of restitution, gravity and others. Create visual effects and use audios for emphasis and realism.

22.37(Project: Flight Simulator) Develop your own flight simulator Java program. This is a very challenging project. It is also an excellent candidate for a contest with your classmates.

22.38(Towers of Hanoi) Write an animated version of the Towers of Hanoi problem we presented in Exercise 6.37. As each disk is lifted off a peg or slid onto a peg play a “whooshing” sound. As each disk lands on the pile play a “clunking” sound. Play some appropriate background music.

22.39(Tortoise and the Hare) Develop a multimedia version of the Tortoise and Hare simulation we presented in Exercise 7.41. You might record an announcer’s voice calling the race, “The contenders are at the starting line.” “And they’re off!” “The Hare pulls out in front.” “The Tortoise is coming on strong.” etc. As the race proceeds, play the appropriate recorded audios. Play sounds to simulate the animals’ running, and don’t forget the crowd cheering! Do an animation of the animals racing up the side of the slippery mountain.

Chapter 22

Java Media Framework and Java Sound (on CD)

1345

22.40(Knight’s Tour Walker) Develop multimedia-based versions of the Knight’s Tour programs you wrote in Exercises 7.22 and 7.23.

22.41(Pinball Machine) Here’s another contest problem. Develop a Java program that simulates a pinball machine of your own design. Have a contest with your classmates to develop the best original multimedia pinball machine. Use every possible multimedia trick you can think of to add “pizzazz” to your pinball game. Try to keep the game mechanisms close to those of real pinball games.

22.42(Roulette) Study the rules for the game of roulette and implement a multimedia-based version of the game. Create an animated spinning roulette wheel. Use audio to simulate the sound of the ball jumping the various compartments that correspond to each of the numbers. Use an audio to simulate the sound of the ball falling into its final slot. While the roulette wheel is spinning, allow multiple players to place their bets. When the ball lands in its final slot, you should update the bank accounts of each of the players with the appropriate wins or losses.

22.43(Craps) Simulate the complete game of craps. Use a graphical representation of a craps table. Allow multiple players to place their bets. Use an animation of the player who is rolling the dice and show the animated dice rolling eventually to a stop. Use audio to simulate some of the chatter around the craps table. After each roll, the system should update the bank accounts of each of the players depending on the bets they have made.

22.44(Morse Code) Modify your solution to Exercise 10.26 to output the morse code using audio clips. Use two different audio clips for the dot and dash characters in Morse code.

A

Java Demos

A.1 Introduction1

In this appendix, we list some of the best Java demos we found on the Web. We began our journey at software.dev.earthweb.com/java. This site is an incredible Java resource and has some of the best Java demos including a huge compilation of games. The code ranges from basic to complex. Many of the authors of these games and other resources have provided source code. We hope you enjoy surfing these sites as much as we did.

A.2 The Sites

softwaredev.earthweb.com/java

Gamelan, a site owned by EarthWeb, has been a wonderful Java resource since the early days of Java. This site originally was a large Java repository where individuals traded ideas on Java and examples of Java programming. One of its early benefits was the volume of Java source code that was available to the many people learning Java. It is now an all-around Java resource with Java references, free Java downloads, areas where you can ask questions to Java experts, discussion groups on Java, a glossary of Java-related terminology, upcoming Java-related events, directories for specialized industry topics and hundreds of other Java resources.

www.jars.com

Another EarthWeb Web site is JARS—originally called the Java Applet Rating Service. The JARS site calls itself the “#1 Java Review Service.” This site originally was a large Java repository for applets. It rated every applet registered at the site as top 1%, top 5% and top 25%, so you could immediately view the best applets on the Web. Early in the development of the Java language, having your applet rated here was a great way to demonstrate your Java programming abilities. JARS is now another allaround resource for Java programmers.

1.There are many Java-related Web sites that cover more advanced Java topics such as servlets, JavaServer Pages (JSP), Enterprise Java Beans (EJB), database, Java 2 Enterprise Edition (J2EE), Java 2 Micro Edition (J2ME), Security, XML and many more. These sites are provided in our companion book, Advanced Java 2 Platform How to Program (ISBN# 0-13-089560-1).

Appendix A

Java Demos 1347

www.javashareware.com

Java Shareware contains hundreds of Java applications, applets, classes and other Java resources. The site includes a large number of links to other Java developer Web sites.

javaboutique.internet.com

Java Boutique is a great resource for any Java programmer. The site offers applets, applications, forums, tutorials, reviews, glossaries and more.

www.thejmaker.com

The J Maker has numerous live Java demos, including games, menus and animated visual effects. Many of the programs on this site are acclaimed worldwide and some have won awards.

www.demicron.com/gallery/photoalbum2/index.shtml

The PhotoAlbum II has some of the coolest effects we have found on the Web. The effects include a liquid effect, folding an image into a paper airplane and others.

www.blaupunkt.de/simulations/svdef_en.html

The Sevilla RDM 168 is a simulation, built with Java, of a car Radio and CD player. You can tune into a variety of on-line radio stations or CDs, adjust the volume, clock settings and more.

www.frontiernet.net/~imaging/play_a_piano.html

Play A Piano is a Java applet that allows you to play the piano or watch the sound waves and listen as the piano plays itself.

www.gamesdomain.co.uk/GamesArena/goldmine

Goldmine is a fun game using simple animation.

www.javaonthebrain.com

This site offers many new and original Java games for the Web. Source code for many of the programs is provided.

www.javagamepark.com

If you are looking for games, the Java Game Park site has loads of them. All of the games are written in Java. The source code is provided in some cases.

teamball.sdsu.edu/~boyns/java/

This site has interesting games written in Java and includes source code for many of them.

www.cruzio.com/~sabweb/arcade/index.html

SABames Arcade is another source for Java video games. Source code is provided for many of the games. Don’t miss the SabBowl bowling game.

dogfeathers.com/java/hyprcube.html

Stereoscopic Animated Hypercube. If you happen to possess the old red and blue 3D glasses, check this site out. The programmer was able to create a 3D image using Java. It isn’t really a complicated image, just some cubes, however the idea that you can create images that will jump off your screen is a great concept!

www.npac.syr.edu/projects/vishuman/VisibleHuman.html

This site has won various awards. You can look at cross sections of the human body.

www-groups.dcs.st-and.ac.uk/~history/Java/

Famous Curves Applet Index. Provides graphs of complex curves. Allows the user to alter the parameters to the equations that calculate the curves.

B

Java Resources

B.1 Resources1

java.sun.com

The Sun Microsystems, Inc. Java Web site is an essential stop when searching the Web for Java information. Go to this site to download the Java 2 Software Development Kit. This site offers news, information, on-line support, code samples and more.

java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html

This site reviews the Sun Microsystems, Inc. code conventions for the Java programming language.

www.softwaredev.earthweb.com

This site provides a wide variety of information on Java and other Internet-related topics. The Java directory page contains links to thousands of Java applets and other Java resources.

softwaredev.earthweb.com/java

The Gamelan site has been a wonderful Java resource since the early days of Java. This site originally was a large Java repository where individuals traded ideas on Java and examples of Java programming. One of its early benefits was the volume of Java source code that was available to the many people learning Java. It is now an all-around Java resource with Java references, free Java downloads, areas where you can ask questions of Java experts, discussion groups on Java, a glossary of Java terminology, upcoming Java events, directories for specialized industry topics and hundreds of other Java resources.

www.jars.com

Another Earthweb.com Web site is JARS—originally called the Java Applet Rating Service. The JARS site calls itself the “#1 Java Review Service.” This site originated as a large Java repository for applets. Its benefit was that it rated every applet registered at the site as top 1%, top 5% and top 25%, so you could immediately view the best applets on the Web. Early in the development of the Java language, having your applet rated here was a great way to demonstrate your Java programming abilities. JARS is now another all-around resource for Java programmers.

1.There are many Java-related Web sites that cover more advanced Java topics such as servlets, JavaServer Pages (JSP), Enterprise Java Beans (EJB), database, Java 2 Enterprise Edition (J2EE), Java 2 Micro Edition (J2ME), Security, XML and many more. These sites are provided in our companion book, Advanced Java 2 Platform How to Program (ISBN# 0-13-089560-1).

Appendix B

Java Resources

1349

developer.java.sun.com/developer

On the Sun Microsystems Java Web site, visit the Java Developer Connection. The site includes technical support, discussion forums, on-line training courses, technical articles, resources, announcements of new Java features, early access to new Java technologies and links to other important Java Web sites. Even though the site is free, you must register to use it.

www.acme.com/java

This page has several animated Java applets with the source code provided. This site is an excellent resource for information on Java. The page provides software, notes and a list of hyperlinks to other resources. Under software you will find animated applets, utility classes and applications.

www.javaworld.com/index.html

The JavaWorld online magazine provides a collection of Java articles, tips, news and discussions. A questions area of this site addresses both general and specific problems programmers face.

www.nikos.com/javatoys

The Java Toys Web site includes links to the latest Java news, Java User Groups (JUGs), FAQs, tools, Java-related mailing lists, books and white papers.

www.java-zone.com

The Development Exchange Java Zone site includes Java discussion groups, an “ask the Java Pro” section and some recent Java news.

www.ibiblio.org/javafaq

This site provides the latest Java news. It also has some helpful Java resources including a Java FAQ List, a tutorial called Brewing Java, Java User Groups, Java Links, the Java Book List, Java Trade Shows, Java Training and Exercises.

dir.yahoo.com/Computers_and_Internet/Programming_Languages/Java

Yahoo, a popular World Wide Web search engine, provides a complete Java resource. You can initiate a search using key words or explore the categories listed at the site including games, contests, events, tutorials and documentation, mailing lists, security and more.

www-106.ibm.com/developerworks/java

The IBM Developers Java Technology Zone site lists the latest news, tools, code, case studies and events related to IBM and Java.

B.2 Products

java.sun.com/products

Download the Java 2 SDK and other Java products from the Sun Microsystems Java Products page.

www.sun.com/forte/ffj/index.cgi

The NetBeans IDE is a customizable, platform independent, visual programming development environment.

www.borland.com/jbuilder

The Borland JBuilder IDE home page has news, product information and customer support.

www.towerj.com

At this site you will find information on how to enhance the performance of server-side Java applications along with free evaluation copies of native Java compilers.

www.symantec.com/domain/cafe

Visit the Symantec site for information on their Visual Café Integrated Development Environment.

www-4.ibm.com/software/ad/vajava

Download and read more about the IBM Visual Age for Java development environment.

1350

Java Resources

Appendix B

www.metrowerks.com

The Metrowerks CodeWarrior IDE supports a few programming languages, including Java.

B.3 FAQs

www.ibiblio.org/javafaq/javafaq.html

This is a comprehensive resource for both Java language basics and more advanced topics in Java Programming. Section 6: Language Issues and Section 11: Common Errors and Problems may be particularly useful, as they clarify situations that often are not explained well.

www.afu.com/javafaq.html

This is another FAQ which covers a fairly broad slice of topics in Java. This includes some good code samples and hints for getting projects to compile and run.

www.nikos.com/javatoys/faqs.html

The Java Toys Web site includes links to FAQs on a broad range of Java-related topics.

www.jguru.com/faq/index.jsp

This is a thorough compilation of FAQs on Java and related subjects. Questions can be read in order or searched for by subject.

B.4 Tutorials

Several tutorials are on the sites listed in the Resources section.

java.sun.com/docs/books/tutorial/

The Java Tutorial Site has a number of tutorials, including sections on JavaBeans, JDBC, RMI, Servlets, Collections and Java Native Interface.

www.ibiblio.org/javafaq/

This site provides the latest Java news. It also has some helpful Java resources including the Java FAQ List, a tutorial called Brewing Java, Java User Groups, Java Links, the Java Book List, Java Conferences, Java Course Notes and Java Seminar Slides.

B.5 Magazines

www.javaworld.com

The JavaWorld on-line magazine is an excellent resource for current Java information. You will find news clips, conference information and links to Java-related Web sites.

www.sys-con.com/java

Catch up with the latest Java news at the Java Developer’s Journal site. This magazine is one of the premier resources for Java news.

www.javareport.com

The Java Report is a great resource for Java developers. You will find the latest industry news, sample code, event listings, products and jobs.

www.javapro.com

The JAVAPro is an excellent Java developer resource with up-to-the-minute technical articles.

B.6 Java Applets

java.sun.com/applets/index.html

This page contains a variety of Java applet resources, including free applets you can use on your own Web site, the demonstration applets from the J2SDK and a variety of other applets. There is a section entitled “Applets at Work” where you can read about applets in industry.

Appendix B

Java Resources

1351

developer.java.sun.com/developer/

On the Sun Microsystems Java Web site, visit the Java Developer Connection. This free site has close to one million members. The site includes technical support, discussion forums, on-line training courses, technical articles, resources, announcements of new Java features, early access to new Java technologies, and links to other important Java Web sites.

www.gamelan.com

Gamelan, a site owned by EarthWeb, has been a wonderful Java resource since the early days of Java. This site originally was a large Java repository where individuals traded ideas on Java and examples of Java programming. One of its early benefits was the volume of Java source code that was available to the many people learning Java. It is now an all-around Java resource with Java references, free Java downloads, areas where you can ask questions to Java experts, discussion groups on Java, a glossary of Java-related terminology, upcoming Java-related events, directories for specialized industry topics and hundreds of other Java resources.

www.jars.com

Another EarthWeb Web site is JARS—originally called the Java Applet Rating Service. The JARS site calls itself the “#1 Java Review Service.” This site originally was a large Java repository for applets. Its benefit was that it rated every applet registered at the site as top 1%, top 5% and top 25%, so you could immediately view the best applets on the Web. Early in the development of the Java language, having your applet rated here was a great way to demonstrate your Java programming abilities. JARS is now another all-around resource for Java programmers.

B.7 Multimedia

java.sun.com/products/java-media/jmf

This is the Java Media Framework home page on the Java Web site. Here you can download the latest Sun implementation of the JMF (see Chapter 22). The site also contains the documentation for the JMF.

www.nasa.gov/gallery/index.html

The NASA multimedia gallery contains a wide variety of images, audio clips and video clips that you can download and use to test your Java multimedia programs.

sunsite.sut.ac.jp/multimed

The Sunsite Japan Multimedia Collection also provides a wide variety of images, audio clips and video clips that you can download for educational purposes.

www.anbg.gov.au/anbg/index.html

The Australian National Botanic Gardens Web site provides links to the audio clips of many animal sounds.

java.sun.com/products/java-media/jmf/index.html

This site provides an HTML-based on-line guide to the Java Media Framework API.

B.8 Newsgroups

Newsgroups are forums on the Internet in which people can post questions, responses, hints and clarifications for other users. Newsgroups can be a valuable resource to anyone learning Java or anyone with questions on specific Java topics. When posting your own questions to a newsgroup, provide specific details of the problem you are trying to solve (such as a problem with a program you are writing). This will enable other people reading the newsgroup to understand your posting and (hopefully) provide a response to you. Be sure to specify a subject heading that clearly states your problem. If you are responding to other people’s

1352

Java Resources

Appendix B

questions, verify your response before posting it to ensure that the response is correct. Newsgroups should not be used to promote products or services, nor should contact information (such as email addresses for other newsgroup users) be used for unrelated purposes. These are generally not forums for chatting, so posts should be courteous and to the point.

Normally, newsgroup reader software is required for you to interact with a newsgroup. Such software is provided as part of Netscape Navigator and Microsoft Outlook Express, and there are many other newsgroup software programs available. You also can access newsgroups through the Web. If you do not use newsgroups already, try the Google site

groups.google.com

Type the name of the group you would like to view (you can also search for newsgroups) and you will be presented with a list of that newsgroup’s current topics and questions. Listed below are some Java newsgroups that you may find useful.

news:comp.lang.java.advocacy

This group is an active center of discussion for current Java culture, including the merits of different programming languages.

news:comp.lang.java.announce

This group provides announcements on major additions to Java, new class libraries and conferences.

news:comp.lang.java.api

This groups contains questions about bugs, compile errors, Java specifications and which classes are most appropriate for different situations.

news:comp.lang.java.gui

This group responds to problems encountered working with Java graphical user interfaces. If you are having trouble with a particular component, layout or event, this may be a good place to start.

news:comp.lang.java.help

This group is particularly active. It addresses many language and environment issues. Questions include requests for classes or algorithms that solve a specific problem.

news:comp.lang.java.machine

For people interested in the inner workings of Java, this group focuses on the Java Virtual Machine.

news:comp.lang.java.misc

This group contains everything from job postings to questions about the Java documentation and is mainly for questions that do not fit into other Java newsgroup categories.

news:comp.lang.java.programmer

This group is another extremely active forum that addresses a range of questions. Posts tend to be largely project-oriented and concerned with overall program style and structure.

news:comp.lang.java.softwaretools

This newsgroup is centered around Java software products, their uses, their faults and possible modifications. Some questions about writing effective software are also included here.

news:comp.lang.java.tech

This is a new group devoted to the technical aspects of Java and its inner workings.

C

Operator Precedence

Chart

Operators are shown in decreasing order of precedence from top to bottom.

Operator

Type

Associativity

 

 

 

()

parentheses

left to right

[]

array subscript

 

.

member selection

 

 

 

 

++

unary postincrement

right to left

--

unary postdecrement

 

 

 

 

++

unary preincrement

right to left

--

unary predecrement

 

+

unary plus

 

-

unary minus

 

!

unary logical negation

 

~

unary bitwise complement

 

( type )

unary cast

 

 

 

 

*

multiplication

left to right

/

division

 

%

modulus

 

 

 

 

+

addition

left to right

-

subtraction

 

 

 

 

<<

bitwise left shift

left to right

>>

bitwise right shift with sign extension

 

>>>

bitwise right shift with zero extension

 

Fig. C.1 Operator precedence chart (part 1 of 2).

1354

Operator Precedence Chart

Appendix C

 

 

 

Operator

Type

Associativity

 

 

 

 

<

 

relational less than

left to right

<=

 

relational less than or equal to

 

>

 

relational greater than

 

>=

 

relational greater than or equal to

 

instanceof

type comparison

 

 

 

 

 

==

 

relational is equal to

left to right

!=

 

relational is not equal to

 

 

 

 

 

&

 

bitwise AND

left to right

 

 

 

 

^

 

bitwise exclusive OR

left to right

 

 

boolean logical exclusive OR

 

 

 

 

 

|

 

bitwise inclusive OR

left to right

 

 

boolean logical inclusive OR

 

 

 

 

 

&&

 

logical AND

left to right

 

 

 

 

||

 

logical OR

left to right

 

 

 

 

?:

 

ternary conditional

right to left

 

 

 

 

=

 

assignment

right to left

+=

 

addition assignment

 

-=

 

subtraction assignment

 

*=

 

multiplication assignment

 

/=

 

division assignment

 

%=

 

modulus assignment

 

&=

 

bitwise AND assignment

 

^=

 

bitwise exclusive OR assignment

 

|=

 

bitwise inclusive OR assignment

 

<<=

 

bitwise left shift assignment

 

>>=

 

bitwise right shift with sign extension assignment

 

>>>=

 

bitwise right shift with zero extension assignment

 

Fig. C.1 Operator precedence chart (part 2 of 2).

D

ASCII Character Set

 

0

1

2

3

4

5

6

7

8

9

0

nul

soh

stx

etx

eot

enq

ack

bel

bs

ht

1

 

 

 

 

 

 

 

 

 

 

nl

vt

ff

cr

so

si

dle

dc1

dc2

dc3

2

 

 

 

 

 

 

 

 

 

 

dc4

nak

syn

etb

can

em

sub

esc

fs

gs

3

 

 

 

 

 

 

 

 

 

 

rs

us

sp

!

"

#

$

%

&

4

 

 

 

 

 

 

 

 

 

 

(

)

*

+

,

-

.

/

0

1

5

 

 

 

 

 

 

 

 

 

 

2

3

4

5

6

7

8

9

:

;

6

 

 

 

 

 

 

 

 

 

 

<

=

>

?

@

A

B

C

D

E

7

 

 

 

 

 

 

 

 

 

 

F

G

H

I

J

K

L

M

N

O

8

 

 

 

 

 

 

 

 

 

 

P

Q

R

S

T

U

V

W

X

Y

9

 

 

 

 

 

 

 

 

 

 

Z

[

\

]

^

_

a

b

c

10

 

 

 

 

 

 

 

 

 

 

d

e

f

g

h

i

j

k

l

m

11

 

 

 

 

 

 

 

 

 

 

n

o

p

q

r

s

t

u

v

w

12

 

 

 

 

 

 

 

 

 

 

x

y

z

{

|

}

~

del

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Fig. D.1 ASCII character set.

The digits at the left of the table are the left digits of the decimal equivalent (0-127) of the character code, and the digits at the top of the table are the right digits of the character code. For example, the character code for “F” is 70, and the character code for “&” is 38.

Most users of this book are interested in the ASCII character set used to represent English characters on many computers. The ASCII character set is a subset of the Unicode character set used by Java to represent characters from most of the world’s languages. For more information on the Unicode character set, see Appendix K.

E

Number Systems

(on CD)

Objectives

To understand basic number systems concepts such as base, positional value, and symbol value.

To understand how to work with numbers represented

in the binary, octal, and hexadecimal number systems

To be able to abbreviate binary numbers as octal numbers or hexadecimal numbers.

To be able to convert octal numbers and hexadecimal

numbers to binary numbers.

To be able to covert back and forth between decimal numbers and their binary, octal, and hexadecimal

equivalents.

• To understand binary arithmetic, and how negative binary numbers are represented using two’s complement notation.

Here are only numbers ratified.

William Shakespeare

Nature has some sort of arithmetic-geometrical coordinate system, because nature has all kinds of models. What we experience of nature is in models, and all of nature’s models are so beautiful.

It struck me that nature’s system must be a real beauty, because in chemistry we find that the associations are always in beautiful whole numbers—there are no fractions.

Richard Buckminster Fuller

Appendix E Number Systems (on CD) 1357

Outline

E.1

Introduction

E.2

Abbreviating Binary Numbers as Octal Numbers and Hexadecimal

 

Numbers

E.3

Converting Octal Numbers and Hexadecimal Numbers to Binary

 

Numbers

E.4

Converting from Binary, Octal, or Hexadecimal to Decimal

E.5

Converting from Decimal to Binary, Octal, or Hexadecimal

E.6

Negative Binary Numbers: Two’s Complement Notation

Summary • Terminology • Self-Review Exercises • Answers to Self-Review Exercises • Exercises

E.1 Introduction

In this appendix, we introduce the key number systems that Java programmers use, especially when they are working on software projects that require close interaction with “ma- chine-level” hardware. Projects like this include operating systems, computer networking software, compilers, database systems, and applications requiring high performance.

When we write an integer such as 227 or -63 in a Java program, the number is assumed to be in the decimal (base 10) number system. The digits in the decimal number system are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. The lowest digit is 0 and the highest digit is 9—one less than the base of 10. Internally, computers use the binary (base 2) number system. The binary number system has only two digits, namely 0 and 1. Its lowest digit is 0 and its highest digit is 1—one less than the base of 2.

As we will see, binary numbers tend to be much longer than their decimal equivalents. Programmers who work in assembly languages and in high-level languages like Java that enable programmers to reach down to the “machine level,” find it cumbersome to work with binary numbers. So two other number systems the octal number system (base 8) and the hexadecimal number system (base 16)—are popular primarily because they make it convenient to abbreviate binary numbers.

In the octal number system, the digits range from 0 to 7. Because both the binary number system and the octal number system have fewer digits than the decimal number system, their digits are the same as the corresponding digits in decimal.

The hexadecimal number system poses a problem because it requires sixteen digits— a lowest digit of 0 and a highest digit with a value equivalent to decimal 15 (one less than the base of 16). By convention, we use the letters A through F to represent the hexadecimal digits corresponding to decimal values 10 through 15. Thus in hexadecimal we can have numbers like 876 consisting solely of decimal-like digits, numbers like 8A55F consisting of digits and letters, and numbers like FFE consisting solely of letters. Occasionally, a hexadecimal number spells a common word such as FACE or FEED—this can appear strange to programmers accustomed to working with numbers.

Each of these number systems uses positional notation—each position in which a digit is written has a different positional value. For example, in the decimal number 937 (the 9, the 3, and the 7 are referred to as symbol values), we say that the 7 is written in the ones position, the 3 is written in the tens position, and the 9 is written in the hundreds position.

1358

Number Systems (on CD)

Appendix E

Notice that each of these positions is a power of the base (base 10), and that these powers begin at 0 and increase by 1 as we move left in the number (Fig. E.3).

Binary digit

Octal digit

Decimal digit

Hexadecimal digit

 

 

 

 

0

0

0

0

1

1

1

1

 

2

2

2

 

3

3

3

 

4

4

4

 

5

5

5

 

6

6

6

 

7

7

7

 

 

8

8

 

 

9

9

 

 

 

A (decimal value of 10)

B (decimal value of 11)

C (decimal value of 12)

D (decimal value of 13)

E (decimal value of 14)

F (decimal value of 15)

Fig. E.1 Digits of the binary, octal, decimal and hexadecimal number systems.

Attribute Binary Octal Decimal Hexadecimal

Base

2

8

10

16

Lowest digit

0

0

0

0

Highest digit

1

7

9

F

Fig. E.2

Comparing the binary, octal, decimal and hexadecimal number systems.

 

 

Positional values in the decimal number system

 

 

 

 

 

Decimal digit

9

3

7

Position name

Hundreds

Tens

Ones

Positional value

100

10

1

Positional value as a

102

101

100

power of the base (10)

 

 

 

Fig. E.3 Positional values in the decimal number system.

Appendix E

Number Systems (on CD)

1359

For longer decimal numbers, the next positions to the left would be the thousands position (10 to the 3rd power), the ten-thousands position (10 to the 4th power), the hundredthousands position (10 to the 5th power), the millions position (10 to the 6th power), the ten-millions position (10 to the 7th power), and so on.

In the binary number 101, we say that the rightmost 1 is written in the ones position, the 0 is written in the twos position, and the leftmost 1 is written in the fours position. Notice that each of these positions is a power of the base (base 2), and that these powers begin at 0 and increase by 1 as we move left in the number (Fig E.4).

For longer binary numbers, the next positions to the left would be the eights position (2 to the 3rd power), the sixteens position (2 to the 4th power), the thirty-twos position (2 to the 5th power), the sixty-fours position (2 to the 6th power), and so on.

In the octal number 425, we say that the 5 is written in the ones position, the 2 is written in the eights position, and the 4 is written in the sixty-fours position. Notice that each of these positions is a power of the base (base 8), and that these powers begin at 0 and increase by 1 as we move left in the number (Fig. E.5).

For longer octal numbers, the next positions to the left would be the five-hundred-and- twelves position (8 to the 3rd power), the four-thousand-and-ninety-sixes position (8 to the 4th power), the thirty-two-thousand-seven-hundred-and-sixty eights position (8 to the 5th power), and so on.

In the hexadecimal number 3DA, we say that the A is written in the ones position, the D is written in the sixteens position, and the 3 is written in the two-hundred-and-fifty-sixes position. Notice that each of these positions is a power of the base (base 16), and that these powers begin at 0 and increase by 1 as we move left in the number (Fig. E.6).

Positional values in the binary number system

Binary digit

1

0

1

Position name

Fours

Twos

Ones

Positional value

4

2

1

Positional value as a

22

21

20

power of the base (2)

 

 

 

 

 

 

Fig. E.4

Positional values in the binary number system.

 

 

 

 

Positional values in the octal number system

 

 

 

 

 

 

Decimal digit

4

2

5

Position name

Sixty-fours

Eights

Ones

Positional value

64

8

1

Positional value as a

82

81

80

power of the base (8)

 

 

 

Fig. E.5 Positional values in the octal number system.