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
Blanc
Posts: 638
Registered: ‎07-02-2009
My Device: Not Specified

Blackberry Media Player. Embed Media Player with in your screen

 

Hi All,

 

The following is the code to create a Blackberry Media Player, where you can hold the control the media.

 

Comments and Critics, Improvements and Suggestions, Compliments and Gifts :smileyhappy::smileywink:

are most welcome..

 

 

 

package com.winit.video.app;

import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.UiEngineInstance;

public class VideoApp extends UiApplication
{

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		// TODO Auto-generated method stub
		new VideoApp().enterEventDispatcher();
	}
	
	public VideoApp() 
	{
		// TODO Auto-generated constructor stub
		UiEngineInstance ui = Ui.getUiEngineInstance();
		ui.setAcceptableDirections(Display.DIRECTION_LANDSCAPE);
		PlayerScreen ps = new PlayerScreen("file:///SDCard/techno-chicken.3gp"); 
		pushScreen(ps);
	}
}

 

 

 

 

 

 

package com.winit.video.app;

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 net.rim.device.api.system.Application;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.TouchEvent;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.container.MainScreen;

import com.winit.common.AppConstants;
import com.winit.common.Tools;
 

public class PlayerScreen extends MainScreen implements  PlayerListener, VideoListener
{
	private Player _player;
    private VideoControl _videoControl;
    private Field _videoField;

  
    
	public PlayerScreen(String vUrl)
    { 
	
		super(NO_VERTICAL_SCROLL);
 
        try
        {    
            _player = Manager.createPlayer(vUrl);
            _player.addPlayerListener(this);
            _player.realize();
            
            _videoControl = (VideoControl)_player.getControl("VideoControl");
            if(_videoControl != null)
            {
            	
                _videoField = (Field)_videoControl.initDisplayMode(0, "net.rim.device.api.ui.Field");
                _videoControl.setDisplaySize(AppConstants.DEVICE_DISPLAY_WIDTH, AppConstants.DEVICE_DISPLAY_HEIGHT);
                
                _videoControl.setVisible(true);
                add(_videoField);
                
                _videoField.setChangeListener(new FieldChangeListener() {
					
					public void fieldChanged(Field field, int context) {
						Dialog.alert("Hello ");
					}
				});
            }

            UiApplication.getUiApplication().invokeLater(new Runnable() 
            {

                public void run()
                {
                    try
                    {
                        _player.prefetch();
                        _player.start();
                    }
                    catch(Exception e)
                    {
                        //GlobalSettings.setErrorLog(e.toString());
                    }
                }

            });
          
                  }
        catch(Exception e)
        {
        	Tools.print("XCO: PlayerScreen: Error While playing media: " + e.toString());
        }
    }
	protected void paint(Graphics graphics) 
	{
		graphics.setBackgroundColor(0x000000);
		graphics.clear();
		subpaint( graphics );
		super.paint(graphics);
	}

    

    public void playerUpdate(Player player, String event, Object eventData)
    {
        if("error".equals(event))
            Dialog.alert(String.valueOf(eventData));
        if("started".equals(event))
            UiApplication.getUiApplication().invokeLater(new Runnable() {

                public void run()
                {
                    try
                    {
                        _videoControl.setDisplayFullScreen(true);
                    }
                    catch(Exception e)
                    {
                        //GlobalSettings.setErrorLog(e.toString());
                    }
                }

            }, 1000L, false);
        if("stopped".equals(event))
            try
            {
                _videoControl.setDisplayFullScreen(false);
            }
            catch(Exception e){ }
    }

    protected boolean keyControl(char c, int status, int time)
    {
        return true;
    }

    public void close()
    {
        super.close();
    }

    public boolean onSavePrompt()
    {
        setDirty(false);
        return true;
    }
    
    protected boolean navigationClick(int status, int time)
    {
    	try{
    		_player.stop();
    		}catch(Exception e){}
    	UiApplication.getUiApplication().invokeLater(new Runnable()
	    {	
	    	public void run()
	    	{
	    		synchronized (Application.getEventLock()) 
	    		{
	    			UiApplication.getUiApplication().pushScreen(new FieldsScreen(PlayerScreen.this));	
	    		}
	    	}
	    });
    	return true;
    }

    protected boolean touchEvent(TouchEvent message)
    {
    	int event = message.getEvent();
    	
    	switch(event)
    	{
	    	case TouchEvent.CLICK:
	    		try{
		    		_player.stop();
		    		}catch(Exception e){}
	    		UiApplication.getUiApplication().invokeLater(new Runnable()
	    	    {	
	    	    	public void run()
	    	    	{
	    	    		synchronized (Application.getEventLock()) 
	    	    		{
	    	    			UiApplication.getUiApplication().pushScreen(new FieldsScreen(PlayerScreen.this));	
	    	    		}
	    	    	}
	    	    });
		    	 return true;
	    	case TouchEvent.UNCLICK:
	    		 return true;
		   	default :
		   	    	  break;
    	}
	    
    	return super.touchEvent(message);
    }
    
	 
	public void playerListener(int actionType)
	{
		try
		{
			 if(actionType == VideoListener.PLAYER_PLAY)
			 {
				 _player.start();
			 }
			 else if(actionType == VideoListener.PLAYER_PAUSE)
			 {
				 _player.stop();
			 }
			 else if(actionType == VideoListener.PLAYER_STOP)
			 {
				 _player.stop();
				 _player.setMediaTime(0);
			 }
			 else if(actionType == VideoListener.PLAYER_REPLAY)
			 {
				 _player.setMediaTime(0);
				 _player.start();
			 }
		}
		catch(MediaException me)
		{
			Tools.print("Player Screen: Error: " + me.getMessage());
		}
	}
    
 
	public int getPlayerState()
	{
		return _player.getState();
	}
	
	public long getPlayerDuration()
	{
		return _player.getDuration();
	}
	
	public long getPlayerMediaTime()
	{
		return _player.getMediaTime();
	}
}

 

 

 

 

package com.winit.video.app;

import com.winit.common.AppConstants;

import net.rim.device.api.system.Application;
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.Graphics;
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.container.FullScreen;
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 FieldsScreen extends FullScreen implements Runnable
{
	private BitmapField btnPlay, btnStop, btnReplay;
    private Bitmap imgPlay, imgPause, imgStop, imgReplay, bottomBar;
    private Bitmap imgPlayHover, imgPauseHover, imgStopHover, imgReplayHover;
    
    HorizontalFieldManager hfmBottom;
	boolean isplay;
	private VideoListener _listener;	
	
	private ProgressBar progressBar;
	
	public FieldsScreen(VideoListener listener) 
	{
		
		setBackground(BackgroundFactory.createSolidTransparentBackground(Color.WHITE, 0));
		
		_listener = listener;
		
		imgPause = Bitmap.getBitmapResource("playerImages/pause_btn.png");
        imgPlay = Bitmap.getBitmapResource("playerImages/play_btn.png");
    	isplay = false;
        
    	imgPlayHover = Bitmap.getBitmapResource("playerImages/play_btn_hover.png");
    	imgPauseHover = Bitmap.getBitmapResource("playerImages/pause_btn_hover.png");
    	imgStopHover = Bitmap.getBitmapResource("playerImages/stop_icon_hover.png");
    	imgReplayHover = Bitmap.getBitmapResource("playerImages/replay_btn_hover.png");
    	
        btnPlay = new BitmapField(imgPlay,BitmapField.FOCUSABLE|ButtonField.CONSUME_CLICK)
        {	
    		protected boolean navigationClick(int status, int time) 
		    {
    			if(!isplay)
    			{
					btnPlay.setBitmap(imgPlay);
					invalidate();
   					_listener.playerListener(VideoListener.PLAYER_PLAY);
   					isplay = true;
   					popScreen();
   					return true;
				       
		        }
    			else if(isplay)
    			{
				     btnPlay.setBitmap(imgPause);
				     invalidate();
				     _listener.playerListener(VideoListener.PLAYER_PAUSE);
				     isplay = false;
    			}
    			
    			return true;
    		}
    		
    		protected void onFocus(int direction)
    		{
    			if(!isplay)
    			{
    				this.setBitmap(imgPlayHover);
    			}
    			else
    			{
    				this.setBitmap(imgPauseHover);
    			}
    		}
    		
    		protected void onUnfocus()
    		{
    			if(!isplay)
    			{
    				this.setBitmap(imgPlay);
    			}
    			else
    			{
    				this.setBitmap(imgPause);
    			}
    		}
    		
    		protected void drawFocus(Graphics graphics, boolean on) 
    	   	{
    			//    	   			
    	   	}
    		
    	};
    	
    	imgStop = Bitmap.getBitmapResource("playerImages/stop_icon.png");
    	btnStop = new BitmapField(imgStop,BitmapField.FOCUSABLE|ButtonField.CONSUME_CLICK)
    	{
    		protected boolean navigationClick(int status, int time) 
		    {
    			btnPlay.setBitmap(imgPlay);
    			_listener.playerListener(VideoListener.PLAYER_STOP);
    			return true;
    		}
    		
    		protected void onFocus(int direction)
    		{
    			this.setBitmap(imgStopHover);
    		}
    		
    		protected void onUnfocus()
    		{
    			this.setBitmap(imgStop);
    		}
    		protected void drawFocus(Graphics graphics, boolean on) 
    		{
  		
    		}
    	};
    	
   	    imgReplay = Bitmap.getBitmapResource("playerImages/replay_btn.png");
	    btnReplay = new BitmapField(imgReplay,BitmapField.FOCUSABLE|ButtonField.CONSUME_CLICK)
	    {
		    
	    	protected boolean navigationClick(int status, int time) 
		    {
    			btnPlay.setBitmap(imgPlay);
    			_listener.playerListener(VideoListener.PLAYER_REPLAY);
    			popScreen();
    			return true;
    		}
	    	protected void onFocus(int direction)
    		{
    			this.setBitmap(imgReplayHover);
    		}
    		
    		protected void onUnfocus()
    		{
    			this.setBitmap(imgReplay);
    		}
			protected void drawFocus(Graphics graphics, boolean on) 
			{
			
			}
	    };
	    
//    	playerMenuLayer = Bitmap.getBitmapResource("playerImages/Button_Background.png");
	    bottomBar = Bitmap.getBitmapResource("playerImages/bg_blk.png");
	    
	    
        hfmBottom = new HorizontalFieldManager(USE_ALL_WIDTH)
        {
     	   protected void sublayout(int width, int height)
     		{
     		   	int x = (AppConstants.DEVICE_DISPLAY_WIDTH - (3*imgPauseHover.getWidth()))/2;	
	 			
     		   	setPositionChild(btnReplay, x, 3);
	 			layoutChild(btnReplay, getScreen().getWidth(), getScreen().getHeight());
	 			 
	 			x += imgReplayHover.getWidth();
	 			setPositionChild(btnPlay, x ,3);  
	 			layoutChild(btnPlay, getScreen().getWidth(), getScreen().getHeight());
	 			
	 			x += imgReplayHover.getWidth();
	 			setPositionChild(btnStop,x, 3);  
	 			layoutChild(btnStop, getScreen().getWidth(), getScreen().getHeight());
	 			
	 			setExtent(width, height);
     		}
     		
     	   protected void paint(Graphics graphics)
            {  
                graphics.drawBitmap(0, 0,bottomBar.getWidth() ,bottomBar.getHeight(), bottomBar, 0, 0);                                 
                super.paint(graphics);
            }
        };
        
        hfmBottom.add(btnReplay);
        hfmBottom.add(btnPlay);
        hfmBottom.add(btnStop);
        
        VerticalFieldManager vfm = new VerticalFieldManager(USE_ALL_WIDTH | USE_ALL_HEIGHT)
        {
        	protected void sublayout(int widht, int height)
        	{
        		
        		setPositionChild(getField(0), 0, AppConstants.DEVICE_DISPLAY_HEIGHT-75);
        		layoutChild(getField(0), getScreen().getWidth(), getScreen().getHeight());
        		
        		setPositionChild(getField(1), 0, AppConstants.DEVICE_DISPLAY_HEIGHT-50);
        		layoutChild(getField(1), getScreen().getWidth(), getScreen().getHeight());
        		
        		setExtent(widht, height);
        	}
        	
        	public void paint(Graphics g)
        	{
        		super.paint(g);
        	}
        };
        
        progressBar = new ProgressBar();
        
        vfm.add(progressBar);
        vfm.add(hfmBottom);
        
        add(vfm);
        
        new Thread(this).start();
	}
	
	private void popScreen()
	{
		synchronized (Application.getEventLock())
		{
			try{
			Thread.sleep(1000L);
			}catch(Exception e){}
			UiApplication.getUiApplication().popScreen(this);
		}
	}
	
	protected boolean keyChar(char ch, int status, int time)
	{
		if(ch == Characters.ESCAPE)
		{
			popScreen();
		}
		return super.keyChar(ch, status, time);
	}

	public void run()
    {
        do
        {
            progressBar.update(_listener.getPlayerState() == 400, (int)(_listener.getPlayerMediaTime() / 0xf4240L), (int)(_listener.getPlayerDuration() / 0xf4240L));
            try
            {
                Thread.sleep(200L);
            }
            catch(Exception e) { }
        } while(true);
    }
}

 

 

 

 

package com.winit.video.app;

import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.resources.Resource;

public class ProgressBar extends Field {

	 public ProgressBar()
	    {
	        percent = 0.0F;
	        isPlaying = false;
	        height = 17;
	        width = Graphics.getScreenWidth();
	    }

	    public void update(boolean playing, int cur, int dur)
	    {
	        isPlaying = playing;
	        if(percent < 0.0F || percent > 1.0F)
	        {
	            throw new IllegalArgumentException("Percent must between 0 and 1.");
	        } else
	        {
	            percent = (float)cur / (float)dur;
	            current = Utils.getTime(cur);
	            duration = Utils.getTime(dur);
	            invalidate();
	            return;
	        }
	    }

	    protected void layout(int maxWidth, int maxHeight)
	    {
	        setExtent(Math.min(width, maxWidth), Math.min(height, maxHeight));
	    }

	    protected void paint(Graphics g)
	    {
	        int w = (int)((float)(width - 56) * percent);
	        w = w >= 0 ? w : 0;
	        w = w <= width - 56 ? w : width - 56;
	        try
	        {
	            g.setColor(0x333333);
	            g.fillRect(0, 0, width, height);
	            if(isPlaying)
	              //  g.drawImage(4, 2, 8, 13, Resource.getImageFromSource("button_stop.png"), 0, 0, 0);
	           
	               // g.drawImage(4, 2, 7, 13, Resource.getImageFromSource("button_play.png"), 0, 0, 0);
	            g.setColor(0x335271);
	            g.fillRect(16, 7, width - 56, 4);
	            g.setColor(0x3399ff);
	            g.fillRect(16, 7, w, 4);
	            g.setColor(0xffffff);
	            g.setFont(Font.getDefault().derive(0, 12));
	            g.drawText(current, width - 33, 2, 4);
	        }
	        catch(Exception e)
	        {
	           // GlobalSettings.setErrorLog(e.toString());
	        }
	    }

	    protected void drawFocus(Graphics g, boolean flag)
	    {
	    }

	    protected void onFocus(int direction)
	    {
	        super.onFocus(direction);
	        invalidate();
	    }

	    protected void onUnfocus()
	    {
	        super.onUnfocus();
	        invalidate();
	    }

	    public boolean isFocusable()
	    {
	        return true;
	    }

	    protected boolean navigationClick(int status, int time)
	    {
	        fieldChangeNotify(isPlaying ? 10 : 11);
	        return true;
	    }

	    protected boolean keyChar(char character, int status, int time)
	    {
	        if(character == '\n')
	        {
	            fieldChangeNotify(isPlaying ? 10 : 11);
	            return true;
	        } else
	        {
	            return super.keyChar(character, status, time);
	        }
	    }

	    private float percent;
	    private int width;
	    private int height;
	    private boolean isPlaying;
	    private String duration;
	    private String current;


}

 

 

 

 

 

public class ImageUtils
{

	public static EncodedImage scaleImage(EncodedImage image, int newW, int newH)
    {
        int numeratorW = Fixed32.toFP(image.getWidth());
        int denominatorW = Fixed32.toFP(newW);
        int scaleW = Fixed32.div(numeratorW, denominatorW);
        int numeratorH = Fixed32.toFP(image.getHeight());
        int denominatorH = Fixed32.toFP(newH);
        int scaleH = Fixed32.div(numeratorH, denominatorH);
        
        return image.scaleImage32(scaleW, scaleH);
    }
}

 

 

 

 

public class Utils
{

    private Utils()
    {
    }

    public static String getTime(int time)
    {
        if(time == 0)
            return "--";
        String str = "";
        int seconds = time % 60;
        int minutes = (time - time % 60) / 60;
        if(minutes > 60)
            minutes %= 60;
        int hours = (time - (time - time % 60) / 60 - seconds) % 60;
        if(time < 18600)
            hours = 0;
        if(hours > 0)
            str = str + (hours >= 10 ? "" : "0") + hours + ":";
        if(minutes > 0)
            str = str + (minutes >= 10 ? "" : "0") + minutes + ":";
        else
            str = str + "00:";
        if(seconds > 0)
            str = str + (seconds >= 10 ? "" : "0") + seconds;
        else
            str = str + "00";
        return str;
    }
}

 

 

 

public interface VideoListener 
{
	public final static int PLAYER_PLAY = 1;
  	public final static int PLAYER_PAUSE = 2;
    public final static int PLAYER_STOP = 3;
    public final static int PLAYER_REPLAY = 4;
	    
	public void playerListener(int actionType);
	
	public int getPlayerState();
	
	public long getPlayerDuration();
	
	public long getPlayerMediaTime();
	
}

 

 

 

 

 

Thanks and Regards,
PraveenGoparaju.
Trusted Contributor
kirthiga
Posts: 204
Registered: ‎07-14-2010
My Device: 8100

Re: Blackberry Media Player. Embed Media Player with in your screen

what is AppConstants here ? interface ?

Contributor
sujayarun8
Posts: 48
Registered: ‎07-20-2010
My Device: Not Specified

Re: Blackberry Media Player. Embed Media Player with in your screen

hi.. can you provide the code for AppConstants class????

Developer
Blanc
Posts: 638
Registered: ‎07-02-2009
My Device: Not Specified

Re: Blackberry Media Player. Embed Media Player with in your screen

AppConstants is my custom class.

 

AppConstants.DISPLAY_DEVICE_WIDTH = Display.getWidth();

AppConstants.DISPLAY_DEVICE_HEIGHT = Display.getHeight();

Thanks and Regards,
PraveenGoparaju.
Contributor
sujayarun8
Posts: 48
Registered: ‎07-20-2010
My Device: Not Specified

Re: Blackberry Media Player. Embed Media Player with in your screen

without AppConstants class and Tools class how can we try your player.. can u provide the code for these classes ??

Developer
MrBawn
Posts: 26
Registered: ‎07-23-2008
My Device: Not Specified

Re: Blackberry Media Player. Embed Media Player with in your screen

 

import net.rim.device.api.system.Display;

public class AppConstants {

	public static final int DEVICE_DISPLAY_WIDTH = Display.getWidth();
	public static final int DEVICE_DISPLAY_HEIGHT = Display.getHeight();

}

 

public class Tools {

	public static void print(String msg) {
		System.out.println(msg);
	}

}

 

I would imagine that Blanc's versions of these classes include more stuff, but that's all you need for this application. You could even factor them out (call Display.getWidth, Display.getHeight, and System.out.println directly each time)

 

Developer
MrBawn
Posts: 26
Registered: ‎07-23-2008
My Device: Not Specified

Re: Blackberry Media Player. Embed Media Player with in your screen

You will also need to create the following images:

pause_btn.png  
play_btn.png  
play_btn_hover.png  
pause_btn_hover.png  
stop_icon_hover.png  
replay_btn_hover.png  
stop_icon.png  
replay_btn.png  
Button_Background.png  
bg_blk.png

Developer
Blanc
Posts: 638
Registered: ‎07-02-2009
My Device: Not Specified

Re: Blackberry Media Player. Embed Media Player with in your screen

Ofcourse MrBawn, your guess is correct.

Thanks and Regards,
PraveenGoparaju.
Contributor
kusumat
Posts: 26
Registered: ‎07-26-2010
My Device: Not Specified

Re: Blackberry Media Player. Embed Media Player with in your screen

Hi,

 

The replay functionality only works if the file is resources.

But when i play via url i could use the setMediaTime(0) .

 

How to implement replay in this case?

 

Thanks,

kusuma