lunedì 29 novembre 1999

Simple audio player for J2ME

The following article shows how a simple mp3 file in your jar application can be played using the mmapi classes (included in the JSR-135 optional package or in all the MIDP 2.0 devices which include a subset of mmapi).

Suppose the file is sound.mp3. You can create a class implementing this method:

    public void playSound(final String soundFile, final Display display) {  
        try {
            InputStream is =
                getClass().getResourceAsStream( "/sound.mp3" );
           
            Player player = Manager.createPlayer( is, "audio/mpeg" );
            player.addPlayerListener( this );
            player.realize();
            player.prefetch( );
            player.start();
        }
        catch ( Exception e ) {        
            e.printStackTrace();
           
            if ( player != null ) {
                player.close();
                player = null;
            }
        }
    }


In the method we have added a PlayerListener (player.addPlayerListener( this )) so we suppose the class implementing the playSound method implements the following PlayerListener interface playerUpdate ( Player player, String event, Object arg2 ) method:

public void playerUpdate ( Player player, String event, Object arg2 ) {
        if ( event.equals( STOPPED ) || event.equals( ERROR ) || event.equals( END_OF_MEDIA ) ||  event.equals( DEVICE_UNAVAILABLE ) || event.equals( CLOSED ) ) {
           
player.deallocate();
            player.close();
            player = null;
        }
    } 


This method frees resources when the player ends the sound playback or an unexpected error occurs. The same method can be used to play sound from network or using the FileConnection API (in those case the URL of the file changes).

Nessun commento:

Posta un commento