media in java

Upload: tiendat46sc

Post on 04-Jun-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 Media in Java

    1/37

    2000 Prentice Hall, Inc. All rights reserved.

    Java Multimedia: Images, Animation,

    Audio and Video

    Outline30.1 Introduction30.2 Loading, Displaying and Scaling Images30.3 Loading and Playing Audio Clips30.4 Animating a Series of Images30.5 Animation Issues30.6 Customizing Applets via the HTMLparamTag30.7 Image Maps30.8 Java Plug-In30.9 Internet and World Wide Web Resources

  • 8/13/2019 Media in Java

    2/37

    2000 Prentice Hall, Inc. All rights reserved.

    30.1 Introduction

    Revolution in computer industry

    Before, computers used for high-speed calculations

    Now, data manipulation important

    Multimedia

    "sizzle" of Java - images, sound, video CDs, DVDs, video cards

    Demands extraordinary computing power

    Fast processors making multimedia possible

    Java Has built-in multimedia capabilities

    Most programming languages do not

    Develop powerful multimedia applications

  • 8/13/2019 Media in Java

    3/37

    2000 Prentice Hall, Inc. All rights reserved.

    30.2 Loading, Displaying and Scaling

    Images

    Java Multimedia

    Graphics, images, animations, sounds, and video

    Begin with images

    Class Image(java.awt)

    Abstract class, cannot create an object directly Must request that an Imagebe loaded and returned to you

    ClassApplet(superclass of JApplet) has this method

    getImage( imageLocation, filename );

    imageLocation - getDocumentBase()- URL

    (address) of HTML file

    filename - Java supports .gifand .jpg(.jpeg)

  • 8/13/2019 Media in Java

    4/37

    2000 Prentice Hall, Inc. All rights reserved.

    30.2 Loading, Displaying and Scaling

    Images (II)

    Displaying Images with drawImage Many overloaded versions

    g.drawImage( myImage, x, y, ImageObserver );

    myImage - Imageobject

    x,y - coordinates to display image

    ImageObserver- object on which image is displayed Use "this"to indicate the applet

    Can be any object that implements ImageObserverinterface

    g.drawImage( myImage, x, y, width, height,ImageObserver );

    widthand height- dimensions of image (automaticallyscaled)

    getWidth(), getHeight()- return dimensions of

    applet

  • 8/13/2019 Media in Java

    5/37

    2000 Prentice Hall, Inc. All rights reserved.

    30.2 Loading, Displaying and Scaling

    Images (III)

    Class ImageIcon

    Not an abstract class (can create objects)

    Example constructor

    private ImageIcon myIcon;

    myIcon = new ImageIcon( "myIcon.gif" );

    Displaying Iconswith methodpaintIconmyIcon.paintIcon( Component, Graphics, x, y )

    Component - Componentobject on which to display image

    (this)

    Graphics- Graphicsobject used to render image (g)

    x, y- coordinates of Icon

  • 8/13/2019 Media in Java

    6/37

    2000 Prentice Hall, Inc. All rights reserved.

    30.2 Loading, Displaying and Scaling

    Images (IV)

    Usage

    ImageIcons are simpler than Images

    Create objects directly

    No need for ImageObserverreference

    However, cannot scale ImageIcons

    Scaling

    Use ImageIconmethod getImage

    Returns Imagereference

    This can be used with drawImageand be scaled

  • 8/13/2019 Media in Java

    7/372000 Prentice Hall, Inc. All rights reserved.

    Outline

    Image Example

    1. import

    1.1 Declare objects

    2. init()

    2.1 Initialize objects

    3.paint()

    3.1 drawImagecalls

    1 // Fig. 30.1: LoadImageAndScale.java

    2 // Load an image and display it in its original size

    3 // and scale it to twice its original width and height.

    4 // Load and display the same image as an ImageIcon.

    5 importjava.applet.Applet;

    6 importjava.awt.*;

    7 importjavax.swing.*;

    8

    9 public classLoadImageAndScale extendsJApplet {

    10 privateImage logo1;

    11 privateImageIcon logo2;

    12

    13 // load the image when the applet is loaded

    14 public voidinit()

    15 {

    16 logo1 = getImage( getDocumentBase(), "logo.gif" );

    17 logo2 = newImageIcon( "logo.gif" );

    18 }

    19

    20 // display the image

    21 public voidpaint( Graphics g )

    22 {23 // draw the original image

    24 g.drawImage( logo1, 0, 0, this);

    25

    26 // draw the image scaled to fit the width of the applet

    27 // and the height of the applet minus 120 pixels

    28 g.drawImage( logo1, 0, 120,

    29 getWidth(), getHeight() - 120, this);

    30

    31 // draw the icon using its paintIcon method

  • 8/13/2019 Media in Java

    8/372000 Prentice Hall, Inc. All rights reserved.

    Outline

    3.2paintIconcall

    Program Output

    32 logo2.paintIcon( this, g, 180, 0 );

    33 }

    34 }

  • 8/13/2019 Media in Java

    9/372000 Prentice Hall, Inc. All rights reserved.

    30.3 Loading and Playing Audio Clips

    Audio clips

    Require speakers and a sound board

    Sound engine - plays audio clips

    Supports .au, .wav, .aif, .mid

    Java Media Framework supports additional formats

    Playing audio clips

    playmethod inApplet

    Plays clip once, marked for garbage collection when finished

    play( location, soundFileName );

    location - getDocumentBase(URL of HTML file)

    play( soundURL );

    soundURL- URL that contains location and filename of clip

  • 8/13/2019 Media in Java

    10/372000 Prentice Hall, Inc. All rights reserved.

    30.3 Loading and Playing Audio Clips (II)

    Playing audio clips MethodplayfromAudioClipinterface

    More flexible thanAppletmethodplay

    Audio stored in program, can be reused

    getAudioClip

    Returns reference to anAudioClip

    Same format asAppletmethodplay

    getAudioClip( location, filename )

    getAudioClip( soundURL )

    OnceAudioCliploaded, use methodsplay- plays audio once

    loop- continuous loops audio in background

    stop- terminates clip that is currently playing

  • 8/13/2019 Media in Java

    11/372000 Prentice Hall, Inc. All rights reserved.

    Outline

    1. import

    1.1 Declare objects

    2. init

    2.1 Set layout

    1 // Fig. 30.2: LoadAudioAndPlay.java

    2 // Load an audio clip and play it.

    3 importjava.applet.*;

    4 importjava.awt.*;

    5 importjava.awt.event.*;

    6 importjavax.swing.*;

    7

    8 public classLoadAudioAndPlay extendsJApplet {9 privateAudioClip sound1, sound2, currentSound;

    10 privateJButton playSound, loopSound, stopSound;

    11 privateJComboBox chooseSound;

    12

    13 // load the image when the applet begins executing

    14 public voidinit()

    15 {

    16 Container c = getContentPane();

    17 c.setLayout( newFlowLayout() );

    18

    19 String choices[] = { "Welcome", "Hi" };

    20 chooseSound = newJComboBox( choices );

    21 chooseSound.addItemListener(

    22 newItemListener() {

    23 public voiditemStateChanged( ItemEvent e )24 {

    25 currentSound.stop();

    26

    27 currentSound =

    28 chooseSound.getSelectedIndex() == 0 ?

    29 sound1 : sound2;

    30 }

    31 }

    32 );

  • 8/13/2019 Media in Java

    12/372000 Prentice Hall, Inc. All rights reserved.

    Outline

    2.2 Add buttons

    2.3 Initialize audio

    clips

    3. stop

    4. ClassButtonHandler

    33 c.add( chooseSound );

    34

    35 ButtonHandler handler = newButtonHandler();

    36 playSound = newJButton( "Play" );

    37 playSound.addActionListener( handler );

    38 c.add( playSound );

    39 loopSound = newJButton( "Loop" );

    40 loopSound.addActionListener( handler );41 c.add( loopSound );

    42 stopSound = newJButton( "Stop" );

    43 stopSound.addActionListener( handler );

    44 c.add( stopSound );

    45

    46 sound1 = getAudioClip(

    47 getDocumentBase(), "welcome.wav" );

    48 sound2 = getAudioClip(

    49 getDocumentBase(), "hi.au" );

    50 currentSound = sound1;

    51 }

    52

    53 // stop the sound when the user switches Web pages

    54 // (i.e., be polite to the user)

    55 public voidstop()56 {

    57 currentSound.stop();

    58 }

    59

    60 private classButtonHandler implementsActionListener {

    61 public voidactionPerformed( ActionEvent e )

    62 {

    63 if( e.getSource() == playSound )

    64 currentSound.play();

    65 l if ( tS () l S d )

  • 8/13/2019 Media in Java

    13/372000 Prentice Hall, Inc. All rights reserved.

    Outline

    Program Output

    65 else if( e.getSource() == loopSound )

    66 currentSound.loop();

    67 else if( e.getSource() == stopSound )

    68 currentSound.stop();

    69 }

    70 }

    71 }

  • 8/13/2019 Media in Java

    14/37

  • 8/13/2019 Media in Java

    15/372000 Prentice Hall, Inc. All rights reserved.

    30.4 Animating a Series of Images (II)

    Method repaint Calls update, which callspaintComponent

    Subclasses of JComponentshould draw in method

    paintComponent

    Call superclass'spaintComponentto make sure Swingcomponents displayed properly

    View area

    Width and height specify entire window, not client area

    Dimensionobjects Containwidthand heightvalues

    myDimObject = new Dimension( 100, 200 );

    myDimObject.width

  • 8/13/2019 Media in Java

    16/372000 Prentice Hall, Inc. All rights reserved.

    30.4 Animating a Series of Images (III)

    getImageLoadStatus

    ImageIconmethod Determines if image is completely loaded into memory

    Only complete images should be displayed (smooth animation)

    If loaded, returnsMediaTracker.COMPLETE

    MediaTracker

    Can determine when images are loaded, or force program to

    wait if not

    ImageIconcreates ourMediaTrackerfor us

    1 // Fig 30 3: LogoAnimator java

  • 8/13/2019 Media in Java

    17/372000 Prentice Hall, Inc. All rights reserved.

    Outline

    1. import

    1.1 implements

    ActionListener

    1.2 Declare objects

    1.3 Constructor

    1.4 InitializeImageIconarray

    2.paintComponent

    2.1 Call to superclasspaintComponent

    1 // Fig. 30.3: LogoAnimator.java

    2 // Animation a series of images

    3 importjava.awt.*;

    4 importjava.awt.event.*;

    5 importjavax.swing.*;

    6

    7 public classLogoAnimator extendsJPanel

    8 implementsActionListener {9 protectedImageIcon images[];

    10 protected inttotalImages = 30,

    11 currentImage = 0,

    12 animationDelay = 50; // 50 millisecond delay

    13 protectedTimer animationTimer;

    14

    15 publicLogoAnimator()

    16 {

    17 setSize( getPreferredSize() );

    18

    19 images = newImageIcon[ totalImages ];

    20

    21 for( inti = 0; i < images.length; ++i )

    22 images[ i ] =

    23 newImageIcon( "images/deitel" + i + ".gif" );24

    25 startAnimation();

    26 }

    27

    28 public voidpaintComponent( Graphics g )

    29 {

    30 super.paintComponent( g );

    31

    32 if ( images[ currentImage ] getImageLoadStatus() ==

  • 8/13/2019 Media in Java

    18/372000 Prentice Hall, Inc. All rights reserved.

    Outline

    2.2 If image loaded,display it (paintIcon)

    2.3 IncrementcurrentImage

    3.actionPerformed

    3.1startAnimation

    3.2 stopAnimation

    3.3getMinimumSize

    32 if( images[ currentImage ].getImageLoadStatus() ==

    33 MediaTracker.COMPLETE ) {

    34 images[ currentImage ].paintIcon( this, g, 0, 0 );

    35 currentImage = ( currentImage + 1 ) % totalImages;

    36 }

    37 }

    38

    39 publicvoidactionPerformed( ActionEvent e )40 {

    41 repaint();

    42 }

    43

    44 public voidstartAnimation()

    45 {

    46 if( animationTimer == null) {

    47 currentImage = 0;48 animationTimer = newTimer( animationDelay, this);

    49 animationTimer.start();

    50 }

    51 else // continue from last image displayed

    52 if( ! animationTimer.isRunning() )

    53 animationTimer.restart();

    54 }

    55

    56 public voidstopAnimation()

    57 {

    58 animationTimer.stop();

    59 }

    60

    61 publicDimension getMinimumSize()

    62 {

    63 returngetPreferredSize();

    64 }

    65

  • 8/13/2019 Media in Java

    19/372000 Prentice Hall, Inc. All rights reserved.

    Outline

    3.4.getPreferredSize

    4. main

    65

    66 publicDimension getPreferredSize()

    67 {

    68 return newDimension( 160, 80 );

    69 }

    70

    71 public static voidmain( String args[] )

    72 {

    73 LogoAnimator anim = newLogoAnimator();

    74

    75 JFrame app = newJFrame( "Animator test" );

    76 app.getContentPane().add( anim, fBorderLayout.CENTER );

    77

    78 app.addWindowListener(

    79 newWindowAdapter() {

    80 public voidwindowClosing( WindowEvent e )

    81 {

    82 System.exit( 0 );

    83 }

    84 }

    85 );

    86

    87 // The constants 10 and 30 are used below to size the

    88 // window 10 pixels wider than the animation and

    89 // 30 pixels taller than the animation.

    90 app.setSize( anim.getPreferredSize().width + 10,

    91 anim.getPreferredSize().height + 30 );

    92 app.show();

    93 }

    94 }

  • 8/13/2019 Media in Java

    20/37

  • 8/13/2019 Media in Java

    21/372000 Prentice Hall, Inc. All rights reserved.

    30.5 Animation Issues

    Storing images Interlaced/non-interlaced formats

    Specifies order in which pixels are stored

    Non-interlaced - pixels stored in order they appear on screen

    Image appears in chunks from top to bottom as it is loaded

    Interlaced - pixels stored in rows, but out of order

    Image appears to fade in and become more clear

    Animation flickers Due to updatebeing called in response to repaint

    In AWT GUI components

    Draws filled rectangle in background color where image was

    Draw image, sleep, clear background (flicker), draw nextimage...

    Swing's JPaneloverrides updateto avoid this

  • 8/13/2019 Media in Java

    22/37

    2000 Prentice Hall, Inc. All rights reserved.

    30.5 Animation Issues (II)

    Double buffering

    Used to smooth animations

    Program renders one image on screen

    Builds next image in off-screen buffer

    When time to display next image, done smoothly

    Partial images user would have seen (while image loads) are

    hidden

    All pixels for next image displayed at once

    Space/Time tradeoff

    Reduces flicker, but can slow animation speed and uses morememory

    Used by Swing GUI components by default

  • 8/13/2019 Media in Java

    23/37

    2000 Prentice Hall, Inc. All rights reserved.

    30.6 Customizing Applets via the HTMLparamTag

    Applets

    Customize through parameters in HTML file that invokesit

    Invokes applet LogoApplet

    paramtags Each has a nameand a value

    Use Applet method getParameter(returns a String)

    parameter = getParameter( "animationdelay" );

  • 8/13/2019 Media in Java

    24/37

    2000 Prentice Hall, Inc. All rights reserved.

    30.6 Customizing Applets via the HTMLparamTag (II)

    Following example Use the LogoAnimatorclass as before, but modified

    slightly

    Create Applet LogoApplet

    Takes parameters

    Creates LogoAnimatorobject using the parameters Plays animation

    1 // Fig. 30.4: LogoAnimator.java

  • 8/13/2019 Media in Java

    25/37

    2000 Prentice Hall, Inc. All rights reserved.

    Outline

    1. import

    1.1 LogoAnimator

    class as before

    1.2 Constructor to

    allow customization

    // g g j

    2 // Animating a series of images

    3 importjava.awt.*;

    4 importjava.awt.event.*;

    5 importjavax.swing.*;

    6

    7 public classLogoAnimator extendsJPanel

    8 implementsActionListener {9 protectedImageIcon images[];

    10 protected inttotalImages = 30,

    11 currentImage = 0,

    12 animationDelay = 50; // 50 millisecond delay

    13 protectedString imageName = "deitel";

    14 protectedTimer animationTimer;

    15

    16 publicLogoAnimator()

    17 {

    18 initializeAnim();

    19 }

    20

    21 // new constructor to support customization

    22 publicLogoAnimator( intnum, intdelay, String name )

    23 {24 totalImages = num;

    25 animationDelay = delay;

    26 imageName = name;

    27

    28 initializeAnim();

    29 }

    30

    31 private voidinitializeAnim()

    32 {

    33 images = newImageIcon[ totalImages ];

  • 8/13/2019 Media in Java

    26/37

    2000 Prentice Hall, Inc. All rights reserved.

    Outline

    2. Methods as before

    g g [ g ]

    34

    35 for( inti = 0; i < images.length; ++i )

    36 images[ i ] = newImageIcon( "images/" +

    37 imageName + i + ".gif" );

    38

    39 // moved here so getPreferredSize can check the size of

    40 // the first loaded image.41 setSize( getPreferredSize() );

    42

    43 startAnimation();

    44 }

    45

    46 public voidpaintComponent( Graphics g )

    47 {

    48 super.paintComponent( g );

    49

    50 if( images[ currentImage ].getImageLoadStatus() ==

    51 MediaTracker.COMPLETE ) {

    52 images[ currentImage ].paintIcon( this, g, 0, 0 );

    53 currentImage = ( currentImage + 1 ) % totalImages;

    54 }

    55 }56

    57 public voidactionPerformed( ActionEvent e )

    58 {

    59 repaint();

    60 }

    61

    62 public voidstartAnimation()

    63 {

    64 if( animationTimer == null) {

    65 currentImage = 0;

  • 8/13/2019 Media in Java

    27/37

    2000 Prentice Hall, Inc. All rights reserved.

    Outline

    2. Methods as before

    g

    66 animationTimer = newTimer( animationDelay, this);

    67 animationTimer.start();

    68 }

    69 else // continue from last image displayed

    70 if( ! animationTimer.isRunning() )

    71 animationTimer.restart();

    72 }73

    74 public voidstopAnimation()

    75 {

    76 animationTimer.stop();

    77 }

    78

    79 publicDimension getMinimumSize()

    80 {

    81 returngetPreferredSize();

    82 }

    83

    84 publicDimension getPreferredSize()

    85 {

    86 return newDimension( images[ 0 ].getIconWidth(),

    87 images[ 0 ].getIconHeight() );88 }

    89

    90 public static voidmain( String args[] )

    91 {

    92 LogoAnimator anim = newLogoAnimator();

    93

    94 JFrame app = newJFrame( "Animator test" );

    95 app.getContentPane().add( anim, BorderLayout.CENTER );

    96

    97 app.addWindowListener(

  • 8/13/2019 Media in Java

    28/37

    2000 Prentice Hall, Inc. All rights reserved.

    Outline98 newWindowAdapter() {99 public voidwindowClosing( WindowEvent e )

    100 {

    101 System.exit( 0 );

    102 }

    103 }

    104 );

    105

    106 app.setSize( anim.getPreferredSize().width + 10,

    107 anim.getPreferredSize().height + 30 );

    108 app.show();

    109 }

    110}

    111// Fig. 30.4: LogoApplet.java

    112// Customizing an applet via HTML parameters

    113//

    114// HTML parameter "animationdelay" is an int indicating

    115// milliseconds to sleep between images (default 50).

    116//

    117// HTML parameter "imagename" is the base name of the images

    118// that will be displayed (i.e., "deitel" is the base name

    119// for images "deitel0.gif," "deitel1.gif," etc.). The applet

    120// assumes that images are in an "images" subdirectory of

    121// the directory in which the applet resides.

    122//

    123// HTML parameter "totalimages" is an integer representing the

    124// total number of images in the animation. The applet assumes

    125// images are numbered from 0 to totalimages - 1 (default 30).

    126

    127importjava.awt.*;

  • 8/13/2019 Media in Java

    29/37

    2000 Prentice Hall, Inc. All rights reserved.

    Outline

    Applet

    1. init

    1.1 Initialize objects

    from parameters

    1.2 Supply variables toconstructor

    2. Set layout

    128importjavax.swing.*;

    129

    130public classLogoApplet extendsJApplet{

    131 public voidinit()

    132 {

    133 String parameter;

    134

    135 parameter = getParameter( "animationdelay" );

    136 intanimationDelay = ( parameter == null? 50 :

    137 Integer.parseInt( parameter ) );

    138

    139 String imageName = getParameter( "imagename" );

    140

    141 parameter = getParameter( "totalimages" );

    142 inttotalImages = ( parameter == null? 0 :

    143 Integer.parseInt( parameter ) );

    144

    145 // Create an instance of LogoAnimator

    146 LogoAnimator animator;

    147

    148 if( imageName == null|| totalImages == 0 )

    149 animator = newLogoAnimator();

    150 else

    151 animator = newLogoAnimator( totalImages,

    152 animationDelay, imageName );

    153

    154 setSize( animator.getPreferredSize().width,

    155 animator.getPreferredSize().height );

    156 getContentPane().add( animator, BorderLayout.CENTER );

    157

  • 8/13/2019 Media in Java

    30/37

    2000 Prentice Hall, Inc. All rights reserved.

    Outline

    3. startAnimation

    158 animator.startAnimation();

    159 }

    160}

  • 8/13/2019 Media in Java

    31/37

    2000 Prentice Hall, Inc. All rights reserved.

    30.7 Image Maps Image map

    Image that has hot areas

    User can click to accomplish a task

    Bubble help

    When mouse over particular point in screen, small message

    displayed in status bar

    In the following example

    Load several images

    Use event handlermouseMovedto find x-coordinate

    Based on the x-coordinate, display a message

    1 // Fig. 30.5: ImageMap.java

  • 8/13/2019 Media in Java

    32/37

    2000 Prentice Hall, Inc. All rights reserved.

    Outline

    1. import

    1.1 Declare objects

    2. init

    2.1

    addMouseListener

    2.2 Initialize

    ImageIcon

    2 // Demonstrating an image map.

    3 importjava.awt.*;

    4 importjava.awt.event.*;

    5 importjavax.swing.*;

    6

    7 public classImageMap extendsJApplet {

    8 privateImageIcon mapImage;9 privateintwidth, height;

    10

    11 public voidinit()

    12 {

    13 addMouseListener(

    14 newMouseAdapter() {

    15 public voidmouseExited( MouseEvent e )

    16 {

    17 showStatus( "Pointer outside applet" );

    18 }

    19 }

    20 );

    21

    22 addMouseMotionListener(

    23 newMouseMotionAdapter() {24 public voidmouseMoved( MouseEvent e )

    25 {

    26 showStatus( translateLocation( e.getX() ) );

    27 }

    28 }

    29 );

    30

    31 mapImage = newImageIcon( "icons2.gif" );

    32 width = mapImage.getIconWidth();

    O

    33 height = mapImage.getIconHeight();

  • 8/13/2019 Media in Java

    33/37

    2000 Prentice Hall, Inc. All rights reserved.

    Outline

    3.paint

    4.translateLocation

    4.1 Display messagedepending on x

    34 setSize( width, height );

    35 }

    36

    37 public voidpaint( Graphics g )

    38 {

    39 mapImage.paintIcon( this, g, 0, 0 );

    40 }

    41

    42 publicString translateLocation( intx )

    43 {

    44 // determine width of each icon (there are 6)

    45 inticonWidth = width / 6;

    46

    47 if( x >= 0 && x iconWidth && x iconWidth * 2 && x iconWidth * 3 && x iconWidth * 4 && x iconWidth * 5 && x

  • 8/13/2019 Media in Java

    34/37

    2000 Prentice Hall, Inc. All rights reserved.

    Outline

    Program Output

  • 8/13/2019 Media in Java

    35/37

  • 8/13/2019 Media in Java

    36/37

    2000 Prentice Hall, Inc. All rights reserved.

    30.8 Java Plug-In (II)

    Using the Plug in with applets The,andtags must be

    converted

    Must indicate that Plug-in should be used to execute applet

    Java Plug-in 1.2 HTML Converter

    Performs conversion for us http://java.sun.com/products/plugin/

    Execution

    In install directory type java HTMLConverter

    Select file to convert and type of conversion

  • 8/13/2019 Media in Java

    37/37