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
arunbiet
Posts: 381
Registered: ‎06-22-2010
My Device: na

How to add background image to a Video Control

package com.imimobile.controls;

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

import javax.microedition.media.Manager;
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 net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.DrawStyle;
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.BitmapField;
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.VerticalFieldManager;
import net.rim.device.api.ui.decor.BackgroundFactory;



public class MediaControl extends VerticalFieldManager implements FieldChangeListener, PlayerListener
{    
    public static Player _player;
    private VolumeControl _volumeControl;
    private RichTextField _statusField;
    private ButtonField _controlButton;
    private Field _videoField;        
    private HorizontalFieldManager _hfm1; 
    private HorizontalFieldManager _hfm2; 
    private LabelField _currentTime;
    private LabelField _duration;
    private LabelField _volumeDisplay;
    public String mediaUrl,mediaType;;
    public int Plwd,Plht;
    public static PlayerThread _playerThread;
    public static TimerUpdateThread _timerUpdateThread;
    public VerticalFieldManager vfm;
   
    public MediaControl(String url,String type,int width,int height)
    {   
    	super(NO_VERTICAL_SCROLL);
    	mediaUrl=url;
    	mediaType=type;
        Plwd=width;
        Plht=height;
        _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.
            	if(mediaType.equalsIgnoreCase("video")){
                _player.start();
                _timerUpdateThread = new TimerUpdateThread();
                _timerUpdateThread.start();
            	}
            	else if(mediaType.equalsIgnoreCase("audio")){
                	 _player.start();
                _playerThread = new PlayerThread();
               
                }
            }
            catch(Exception pe)
            {
                Dialog.alert("Player#start() threw " + pe.toString());
            } 
            
        }
        else
        {
            try
            {
                // Stop/pause the media player.
            	if(mediaType.equalsIgnoreCase("video")){
                _player.stop();             
                _timerUpdateThread.stop();
            	}
            else if(mediaType.equalsIgnoreCase("audio")){
            	  _player.stop();
            	_playerThread.stop();
            	  }
            
            	
            }
            catch(Exception pe)
            {
                Dialog.alert("Player#start() 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_HCENTER);
        _currentTime = new LabelField("-",DrawStyle.LEFT);

        _duration = new LabelField("- s",DrawStyle.LEFT);
        _volumeDisplay = new LabelField ("Volume : " +  _volumeControl.getLevel(),DrawStyle.RIGHT);
      
    }

    /**
     * Adds UI components to the main screen.  
     */
    private void addComponentsToScreen()
    {     
       
    	add(_videoField);
    	add(_hfm1);
    //	add(_hfm2);
    	setBackground(BackgroundFactory.createSolidBackground(Color.DARKGRAY));
               
    }    
    
    /**
     * 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/mp4");
            _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");   
            _volumeControl.setLevel(100);
                    
        }
        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 =Plht;
                    int videoWidth = Plwd;    
                    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;                
    }    
    
    public class PlayerThread extends Thread
    {
        /**
         * Create and start the player
         * @see java.lang.Runnable#run()
         */
    	   private boolean _threadCanRun;

        public void run()
        {

        	
        
			while( _threadCanRun ) {     
            try
            {
            	 InputStream is = getClass().getResourceAsStream(mediaUrl);
                _player = Manager.createPlayer(is,"audio/mp3");
              
                _player.start();
            }
                 
            catch (final Exception e)
            {
                // Acquire the UI lock
                UiApplication.getUiApplication().invokeLater(new Runnable()
                {
                    public void run()
                    {
                       // _playStatusField.setText("Stopped");
                        Dialog.alert("Error: " + e.getMessage());
                    }
                });
            }
        } 
	       
        }
                   
        public void stop()
        {
            _threadCanRun = false;
        }
    }
  
    
    /**
     * A thread which acts as a timer to update the screen
     */
    public 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);
		 	 try {
				
				  _player.stop();
	            	_playerThread.stop();
			} catch (MediaException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
          
			return true;
		}
		return false;
	}
}

 Above is the Video  & Audio Control code.Everything is working fine.The change i want to make is that,now videoControl section is coming as black.i want to set a background image to that black section.How can i achieve it

Please use plain text.