Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Developer
Posts: 436
Registered: ‎06-22-2010
My Device: na
My Carrier: blackberry developer

How to play embedded audio file

I am playing an embedded video in this way

 

package com.imimobile.controls;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;
import javax.microedition.media.control.VideoControl;
import javax.microedition.media.control.VolumeControl;
import javax.speech.AudioManager;

import com.imimobile.common.PersistentStorage;

import mypackage.MyMainScreen;
import net.rim.device.api.system.Characters;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Keypad;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.BackgroundFactory;



public class MediaControl extends VerticalFieldManager implements FieldChangeListener, PlayerListener
{    
    private Player _player;
    private VolumeControl _volumeControl;
    private RichTextField _statusField;
    private ButtonField _controlButton;
    private Field _videoField;        
    private HorizontalFieldManager _hfm1; 
    private HorizontalFieldManager _hfm2; 
  //  private VerticalFieldManager _vfm; 
    private LabelField _currentTime;
    private LabelField _duration;
    private LabelField _volumeDisplay;
    public String mediaUrl;
    public int Plwd,Plht;
    private TimerUpdateThread _timerUpdateThread;
            
    // Constructor
    public MediaControl(String url,int wd,int ht)
    {   
    	super(NO_VERTICAL_SCROLL);
    	mediaUrl=url;
    	Plwd=wd;
    	Plht=ht;
    	//_vfm=new VerticalFieldManager(USE_ALL_WIDTH|USE_ALL_HEIGHT|NO_VERTICAL_SCROLL);
    
        _statusField = new RichTextField("Loading media, please wait...");
        add(_statusField);
        
        UiApplication.getUiApplication().invokeLater(new Runnable()
        {
            public void run()
            {
                initializeMedia();                
                
                // If initialization was successful...
                if(_videoField != null)
                {                    
                    initializeUiComponents();                   
                    addComponentsToScreen();
                    updateVideoSize();                                                         
                }
                else
                {
                    _statusField.setText("Error: Could not load media");
                }
            }
        });                      
    }    
    
    /**
    * Implementation of FieldChangeListener.
    * @param field The field that changed.
    * @param context Information specifying the origin of the change.
    * 
    * @see net.rim.device.api.ui.FieldChangeListener#fieldChanged(Field , int)
    */
    public void fieldChanged(Field field, int context)
    {              
        if (_controlButton.getLabel().equals("Play"))
        {   
            try
            {   
                // Start/resume the media player.
                _player.start();
                
                _timerUpdateThread = new TimerUpdateThread();
                _timerUpdateThread.start();
            }
            catch(MediaException pe)
            {
                Dialog.alert("Player#start() threw " + pe.toString());
            } 
        }
        else
        {
            try
            {
                // Stop/pause the media player.
                _player.stop();             
                
                _timerUpdateThread.stop();
            }
            catch(MediaException pe)
            {
            	 Dialog.alert("Player#stop() threw " + pe.toString());
            }
        }                   
    }   
    
    /**
     * @see net.rim.device.api.ui.Manager#sublayout(int,int)      
     * @param width Width available for this screen.
     * @param height Height available for this screen.
     */
    protected void sublayout( int width, int height )
    {
        super.sublayout( width, height );
        updateVideoSize();
    }
    
    /**
     * Initializes UI Components
     */
    private void initializeUiComponents()
    {
        delete(_statusField);
                    
        _hfm1 = new HorizontalFieldManager(Field.FIELD_HCENTER);            
        _controlButton = new ButtonField("Play", ButtonField.NEVER_DIRTY);        
        _controlButton.setChangeListener(this);
        _hfm1.add(_controlButton);
        
        _hfm2 = new HorizontalFieldManager(Field.FIELD_HCENTER);
        _currentTime = new LabelField("-");
        _duration = new LabelField("- s");
        _volumeDisplay = new LabelField ("Volume : " +  _volumeControl.getLevel());
        //_hfm2.add(_currentTime);
       // _hfm2.add(new LabelField(" / "));
       // _hfm2.add(_duration);
       // _hfm2.add(new LabelField("\t\t"));
        //_hfm2.add(_volumeDisplay);       
    }

    /**
     * Adds UI components to the main screen.  
     */
    private void addComponentsToScreen()
    {     
    	add(_videoField);
    	add(_hfm1);
    	setBackground(BackgroundFactory.createSolidBackground(Color.DARKGRAY));
       // add(_vfm);       
       
    }    
    
    /**
     * Creates a Player based on a specified URL and provides a
     * VolumeControl object.
     */
    private void initializeMedia()
    {         
        try
        {   
            /* For the purpose of this sample we are supplying a URL to a media file
            that is included in the project itself. 
            See the javax.microedition.media.Manager javadoc for more information on 
            handling data residing on a server.
            */
            InputStream is = getClass().getResourceAsStream(mediaUrl);
            _player = javax.microedition.media.Manager.createPlayer(is, "video/3gp");
            _player.addPlayerListener(this);            
            _player.realize();        
         
            VideoControl vc = (VideoControl) _player.getControl("VideoControl");
           
            if (vc != null)
            {
                _videoField = (Field) vc.initDisplayMode (VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
                vc.setVisible(true);
            }    
            
            _volumeControl = (VolumeControl) _player.getControl("VolumeControl");   
                    
        }
        catch(MediaException pe)
        {
        	 Dialog.alert(pe.toString());
        }
        catch (IOException ioe)
        {
        	 Dialog.alert("Manager.createPlayer() threw " + ioe.toString());
        }        
    }   
    
    /**
     * Updates the video size according to the current screen dimensions.
     * @param screenWidth The screen's width.
     * @param screenHeight The screen's height.
     */
    private void updateVideoSize()
    {
        if(_player != null)
        {
            try
            {
                VideoControl vc = (VideoControl) _player.getControl("VideoControl");
                if( vc != null )
                {
                    int videoHeight =540;
                    int videoWidth = 480;            
                    vc.setDisplaySize( videoWidth, videoHeight);                                              
                }
            }
            catch ( Exception e )
            { 
            	 Dialog.alert("VideoControl#setDisplayDize() threw " + e.toString());
            }
        }        
    }       
    
    /**
     * @see net.rim.device.api.ui.Screen#keyControl(char,int,int)
     */
    protected boolean keyControl(char c, int status, int time)
    {        
        // Capture volume control key press and adjust volume accordingly.
        switch( c )
        {
            case Characters.CONTROL_VOLUME_DOWN:
                _volumeControl.setLevel(_volumeControl.getLevel() - 10);          
                return true;
                
            case Characters.CONTROL_VOLUME_UP:
                _volumeControl.setLevel(_volumeControl.getLevel() + 10);                           
                return true;
        }
        
        return super.keyControl( c, status, time );
    }    
    
    /**
     * @see javax.microedition.media.PlayerListener#playerUpdate(Player,String,Object)
     */
    public void playerUpdate(Player player, final String event, Object eventData)
    {
        UiApplication.getUiApplication().invokeLater(new Runnable()
        {
            public void run()
            {
                if (event.equals(VOLUME_CHANGED))
                {
                    _volumeDisplay.setText("Volume : " + _volumeControl.getLevel());
                }
                else if (event.equals(STARTED ))
                {
                    _currentTime.setText(" ");
                    _controlButton.setLabel("Pause");      
                }    
                else if (event.equals(STOPPED))
                {
                    _currentTime.setText(_player.getMediaTime()/1000000 + "");
                    _controlButton.setLabel("Play");              
                }                       
                else if (event.equals(DURATION_UPDATED))
                {
                    _duration.setText(_player.getDuration()/1000000 + " s");       
                }           
                else if (event.equals(END_OF_MEDIA))
                {
                    _controlButton.setLabel("Play");        
                }
            }           
        });
    }

    /**
     * @see net.rim.device.api.ui.Screen#invokeAction(int)
     */   
    protected boolean invokeAction(int action)
    {
        boolean handled = super.invokeAction(action); 
                    
        if(!handled)
        {
            switch(action)
            {
                case ACTION_INVOKE: // Trackball click.
                {   
                    // Suppress the menu
                    return true;
                }
            }
        }        
        return handled;                
    }    
    
    
    
    /**
     * A thread which acts as a timer to update the screen
     */
    private class TimerUpdateThread extends Thread
    {
        private boolean _threadCanRun;

        /**
         * @see java.lang.Runnable#run()
         */
        public void run()
        {
            _threadCanRun = true;
            while( _threadCanRun ) {
                UiApplication.getUiApplication().invokeLater( new Runnable() {
                    public void run()
                    {
                        _currentTime.setText( _player.getMediaTime() / 1000000 + "" );
                    }
                } );
                
                try {
                    Thread.sleep( 500L );
                } catch( InterruptedException e ) {
                	 Dialog.alert("Thread.sleep(long) threw " + e.toString());
                }
            }
        }

        /**
         * @see java.lang.Thread#stop()
         */
        public void stop()
        {
            _threadCanRun = false;
        }
    }
    
	protected boolean keyChar(char character, int status, int time) {
		if (character == (char) Keypad.KEY_ESCAPE) {

			//System.exit(0);
			
			UiApplication.getUiApplication().popScreen(getScreen());
			
			return true;
		}
		return false;
	}
}

 Now i want to play an audio instead of video with the same layout.Can anyone help me?