Showing posts with label j2me multimedia. Show all posts
Showing posts with label j2me multimedia. Show all posts

View PNG Image with Thread

/*--------------------------------------------------

* ViewPngThread.java

*

* Download and view a png file. The download is

* done in the background with a separate thread

*

* Example from the book: Core J2ME Technology

* Copyright John W. Muchow http://www.CoreJ2ME.com

* You may use/modify for any non-commercial purpose

*-------------------------------------------------*/

import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

import javax.microedition.io.*;

import java.io.*;


public class ViewPngThread extends MIDlet implements CommandListener

{

private Display display;

private TextBox tbMain;

private Alert alStatus;

private Form fmViewPng;

private Command cmExit;

private Command cmView;

private Command cmBack;

private static final int ALERT_DISPLAY_TIME = 3000;

Image im = null;

public ViewPngThread()

{

display = Display.getDisplay(this);

// Create the Main textbox with a maximum of 75 characters

tbMain = new TextBox("Enter url", "http://www.corej2me.com/midpbook_v1e1/ch14/bird.png", 75, 0);

// Create commands and add to textbox

cmExit = new Command("Exit", Command.EXIT, 1);

cmView = new Command("View", Command.SCREEN, 2);

tbMain.addCommand(cmExit);

tbMain.addCommand(cmView );

// Set up a listener for textbox

tbMain.setCommandListener(this);

// Create the form that will hold the png image

fmViewPng = new Form("");

// Create commands and add to form

cmBack = new Command("Back", Command.BACK, 1);

fmViewPng.addCommand(cmBack);

// Set up a listener for form

fmViewPng.setCommandListener(this);

}

public void startApp()

{

display.setCurrent(tbMain);

}

public void pauseApp()

{ }

public void destroyApp(boolean unconditional)

{ }

/*--------------------------------------------------

* Process events

*-------------------------------------------------*/

public void commandAction(Command c, Displayable s)

{

// If the Command button pressed was "Exit"

if (c == cmExit)

{

destroyApp(false);

notifyDestroyed();

}

else if (c == cmView)

{

// Show alert indicating we are starting a download.

// This alert is NOT modal, it appears for

// approximately 3 seconds (see ALERT_DISPLAY_TIME)

showAlert("Downloading", false, tbMain);

// Create an instance of the class that will

// download the file in a separate thread

Download dl = new Download(tbMain.getString(), this);

// Start the thread/download

dl.start();

}

else if (c == cmBack)

{

display.setCurrent(tbMain);

}

}

/*--------------------------------------------------

* Called by the thread after attempting to download

* an image. If the parameter is 'true' the download

* was successful, and the image is shown on a form.

* If parameter is 'false' the download failed, and

* the user is returned to the textbox.

*

* In either case, show an alert indicating the

* the result of the download.

*-------------------------------------------------*/

public void showImage(boolean flag)

{

// Download failed...

if (flag == false)

{

// Alert followed by the main textbox

showAlert("Download Failure", true, tbMain);

}

else // Successful download...

{

ImageItem ii = new ImageItem(null, im, ImageItem.LAYOUT_DEFAULT, null);

// If there is already an image, set (replace) it

if (fmViewPng.size() != 0)

fmViewPng.set(0, ii);

else // Append the image to the empty form

fmViewPng.append(ii);

// Alert followed by the form holding the image

showAlert("Download Successful", true, fmViewPng);

}

}

/*--------------------------------------------------

* Show an alert with the parameters determining

* the type (modal or not) and the displayable to

* show after the alert is dismissed

*-------------------------------------------------*/

public void showAlert(String msg, boolean modal, Displayable displayable)

{

// Create alert, add text, associate a sound

alStatus = new Alert("Status", msg, null, AlertType.INFO);

// Set the alert type

if (modal)

alStatus.setTimeout(Alert.FOREVER);

else

alStatus.setTimeout(ALERT_DISPLAY_TIME);

// Show the alert, followed by the displayable

display.setCurrent(alStatus, displayable);

}

}

/*--------------------------------------------------

* Class - Download

*

* Download an image file in a separate thread

*-------------------------------------------------*/

class Download implements Runnable

{

private String url;

private ViewPngThread MIDlet;

private boolean downloadSuccess = false;

public Download(String url, ViewPngThread MIDlet)

{

this.url = url;

this.MIDlet = MIDlet;

}

/*--------------------------------------------------

* Download the image

*-------------------------------------------------*/

public void run()

{

try

{

getImage(url);

}

catch (Exception e)

{

System.err.println("Msg: " + e.toString());

}

}

/*--------------------------------------------------

* Create and start the new thread

*-------------------------------------------------*/

public void start()

{

Thread thread = new Thread(this);

try

{

thread.start();

}

catch (Exception e)

{

}

}

/*--------------------------------------------------

* Open connection and download png into a byte array.

*-------------------------------------------------*/

private void getImage(String url) throws IOException

{

ContentConnection connection = (ContentConnection) Connector.open(url);

// * There is a bug in MIDP 1.0.3 in which read() sometimes returns

// an invalid length. To work around this, I have changed the

// stream to DataInputStream and called readFully() instead of read()

// InputStream iStrm = connection.openInputStream();

DataInputStream iStrm = connection.openDataInputStream();

ByteArrayOutputStream bStrm = null;

Image im = null;

try

{

// ContentConnection includes a length method

byte imageData[];

int length = (int) connection.getLength();

if (length != -1)

{

imageData = new byte[length];

// Read the png into an array

// iStrm.read(imageData);

iStrm.readFully(imageData);

}

else // Length not available...

{

bStrm = new ByteArrayOutputStream();

int ch;

while ((ch = iStrm.read()) != -1)

bStrm.write(ch);

imageData = bStrm.toByteArray();

}

// Create the image from the byte array

im = Image.createImage(imageData, 0, imageData.length);

}

finally

{

// Clean up

if (connection != null)

connection.close();

if (iStrm != null)

iStrm.close();

if (bStrm != null)

bStrm.close();

}

// Return to the caller the status of the download

if (im == null)

MIDlet.showImage(false);

else

{

MIDlet.im = im;

MIDlet.showImage(true);

}

}

}

Display Alert

//jad file (please verify the jar size)
/*
MIDlet-Name: DisplayAlert
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: DisplayAlert.jar
MIDlet-1: DisplayAlert, , DisplayAlert
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100

*/
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class DisplayAlert extends MIDlet implements CommandListener {
private Display display;

private Alert alert;

private Form form = new Form("Throw Exception");

private Command exit = new Command("Exit", Command.SCREEN, 1);

private boolean exitFlag = false;

public DisplayAlert() {
display = Display.getDisplay(this);
form.addCommand(exit);
form.setCommandListener(this);
}

public void startApp() {
display.setCurrent(form);
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) throws MIDletStateChangeException {
if (unconditional == false) {
throw new MIDletStateChangeException();
}
}

public void commandAction(Command command, Displayable displayable) {
if (command == exit) {
try {
if (exitFlag == false) {
alert = new Alert("Busy", "Please try again.", null, AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert, form);
destroyApp(false);
} else {
destroyApp(true);
notifyDestroyed();
}
} catch (Exception exception) {
exitFlag = true;
}
}
}
}

Accessing Commands

/*--------------------------------------------------
* AccessingCommands.java
*
* Example from the book: Core J2ME Technology
* Copyright John W. Muchow http://www.CoreJ2ME.com
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class AccessingCommands extends MIDlet implements CommandListener
{
private Display display; // Reference to Display object
private Form fmMain; // A Form
private Command cmExit; // A Command to exit the MIDlet

public AccessingCommands()
{
display = Display.getDisplay(this);

cmExit = new Command("Exit", Command.EXIT, 1);

fmMain = new Form("Core J2ME");
fmMain.addCommand(cmExit);
fmMain.setCommandListener(this);
}

// Called by application manager to start the MIDlet.
public void startApp()
{
display.setCurrent(fmMain);
}

// A required method
public void pauseApp()
{ }

// A required method
public void destroyApp(boolean unconditional)
{ }

// Check to see if our Exit command was selected
public void commandAction(Command c, Displayable s)
{
if (c == cmExit)
{
destroyApp(false);
notifyDestroyed();
}
}
}

Animation Midlet

/*
J2ME in a Nutshell
By Kim Topley
ISBN: 0-596-00253-X

*/


import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemStateListener;
import javax.microedition.midlet.MIDlet;

public class AnimationMIDlet extends MIDlet
implements CommandListener, ItemStateListener {

// The MIDlet's Display object
private Display display;

// Flag indicating first call of startApp
protected boolean started;

// Exit command
private Command exitCommand;

// Setup command
private Command setupCommand;

// Run command
private Command runCommand;

// Configuration form
private Form form;

// Animation canvas
private AnimationCanvas canvas;

// Gauge for block count
private Gauge blockGauge;

// Gauge for frame rate
private Gauge rateGauge;

// Initial frame rate
private static final int FRAME_RATE = 1;

// Initial number of blocks
private static final int BLOCK_COUNT = 1;

protected void startApp() {
if (!started) {
display = Display.getDisplay(this);
form = new Form("Animation");
rateGauge = new Gauge("Frame rate", true, 10, FRAME_RATE);
blockGauge = new Gauge("Blocks", true, 4, BLOCK_COUNT);
form.append(rateGauge);
form.append(blockGauge);
form.setItemStateListener(this);

canvas = createAnimationCanvas();

exitCommand = new Command("Exit", Command.EXIT, 0);
setupCommand = new Command("Setup", Command.SCREEN, 0);
runCommand = new Command("Run", Command.SCREEN, 0);

canvas.addCommand(exitCommand);
canvas.addCommand(setupCommand);
form.addCommand(exitCommand);
form.addCommand(runCommand);

form.setCommandListener(this);
canvas.setCommandListener(this);

display.setCurrent(form);
started = true;
}
}

protected void pauseApp() {
}

protected void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
// Exit. No need to call destroyApp
// because it is empty.
notifyDestroyed();
} else if (c == runCommand) {
display.setCurrent(canvas);
} else if (c == setupCommand) {
display.setCurrent(form);
}
}

public void itemStateChanged(Item item) {
if (item == blockGauge) {
int count = blockGauge.getValue();
if (count < 1) {
count = 1;
}
canvas.setBlockCount(count);
} else if (item == rateGauge) {
int count = rateGauge.getValue();
if (count < 1) {
count = 1;
}
canvas.setFrameRate(count);
}
}

// Creates the canvas that will draw the block
protected AnimationCanvas createAnimationCanvas() {
return new AnimationCanvas();
}

class AnimationCanvas extends Canvas {

// Size of each block
protected static final int SIZE = 4;

// Initial speeds in the X direction
protected final int[] xSpeeds = { 2, -2, 0, -2 };

// Initial speeds in the Y direction
protected final int[] ySpeeds = { 2, -2, 2, -0 };

// Background color
protected int background = display.isColor() ? 0 : 0xc0c0c0;

// Foreground color
protected int foreground = display.isColor() ? 0xffff00 : 0;

// Width of screen
protected int width = getWidth();

// Height of screen
protected int height = getHeight();

// The screen update rate
protected int frameRate;

// The blocks to draw on the screen
protected Block[] blocks;

// The update timer
protected Timer timer;

// The update timer task
protected TimerTask updateTask;

// Gets the maximum number of blocks
public int getMaxBlocks() {
return blocks.length;
}

// Constructs a canvas with default settings
AnimationCanvas() {
setBlockCount(BLOCK_COUNT);
setFrameRate(FRAME_RATE);
}

// Sets the number of blocks to draw
public void setBlockCount(int count) {
if (count > xSpeeds.length) {
throw new IllegalArgumentException("Cannot have more than "
+ xSpeeds.length + " blocks");
}

blocks = new Block[count];
createBlocks();
}

// Gets the number of blocks to draw
public int getBlockCount() {
return blocks.length;
}

// Sets the number of updates per second
public void setFrameRate(int frameRate) {
if (frameRate < 1 || frameRate > 10) {
throw new IllegalArgumentException("Frame rate must be > 0 and <= 10");
}
this.frameRate = frameRate;
if (isShown()) {
startFrameTimer();
}
}

// Gets the number of updates per second
public int getFrameRate() {
return frameRate;
}

// Paint canvas background and all
// of the blocks in their correct locations.
protected void paint(Graphics g) {
// Paint with the background color
g.setColor(background);
g.fillRect(0, 0, width, height);

// Draw all of the blocks
g.setColor(foreground);
synchronized (this) {
for (int i = 0, count = blocks.length; i < count; i++) {
g.fillRect(blocks[i].x, blocks[i].y, SIZE, SIZE);
}
}
}

// Notification that the canvas has been made visible
protected void showNotify() {
// Start the frame timer running
startFrameTimer();
}

// Notification that the canvas is no longer visible
protected void hideNotify() {
// Stop the frame timer
stopFrameTimer();
}

// Creates the blocks to be displayed
private void createBlocks() {
int startX = (width - SIZE)/2;
int startY = (height - SIZE)/2;
for (int i = 0, count = blocks.length; i < count; i++) {
blocks[i] = new Block(startX, startY, xSpeeds[i], ySpeeds[i]);
}
}

// Starts the frame redraw timer
protected void startFrameTimer() {
timer = new Timer();

updateTask = new TimerTask() {
public void run() {
moveAllBlocks();
}
};
long interval = 1000/frameRate;
timer.schedule(updateTask, interval, interval);
}

// Stops the frame redraw timer
protected void stopFrameTimer() {
timer.cancel();
}

// Called on expiry of timer.
public synchronized void moveAllBlocks() {
// Update the positions and speeds
// of all of the blocks
for (int i = 0, count = blocks.length; i < count; i++) {
blocks[i].move();

// Request a repaint of the screen
repaint();
}
}

// Inner class used to represent a block on the screen
class Block {
int x; // X position
int y; // Y position
int xSpeed; // Speed in the X direction
int ySpeed; // Speed in the Y direction

Block(int x, int y, int xSpeed, int ySpeed) {
this.x = x;
this.y = y;
this.xSpeed = xSpeed;
this.ySpeed = ySpeed;
}

void move() {
x += xSpeed;
if (x <= 0 || x + SIZE >= width) {
xSpeed = -xSpeed;
}

y += ySpeed;
if (y <= 0 || y + SIZE >= height) {
ySpeed = -ySpeed;
}
}
}
}
}

Font Demo J2ME

The Font class represents fonts and font metrics. Fonts cannot be created by applications. The setFont(Font font) method of graphic class sets the font for all subsequent text rendering operations. And there is no call to showNotify and hideNotify method on some the device. This application will help game developer to find out the exact behaviour of mobile device.

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class FontDemo extends MIDlet {

private boolean boolMotion=false;
private int iX=10, iY=60;

Display mDisplay;
Thread th;
public void destroyApp(boolean unconditional){}

public void pauseApp() {}

public void startApp() {

mDisplay = Display.getDisplay(this);
final MyCanvas can = new MyCanvas();
mDisplay.setCurrent(can);

}
}

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class MyCanvas extends Canvas {

Font font;
String msg;
public MyCanvas() {

font=Font.getFont(Font.FACE_MONOSPACE,
Font.STYLE_ITALIC, Font.SIZE_LARGE);
msg = "Font:FACE_MONOSPACE Font.STYLE_ITALIC Font.SIZE_LARGE";
}

public void paint(Graphics g) {
g.setFont(font);
g.drawString(msg,0,10,g.TOP|g.LEFT);
g.drawString("press NUM KEY: 1 2 or 3",0,80,g.TOP|g.LEFT);
}

void changeValue(int change) {
switch(change) {
case '1':
font=Font.getFont(Font.FACE_MONOSPACE,
Font.STYLE_ITALIC, Font.SIZE_LARGE) ;
msg="Font:FACE_MONOSPACE Font.STYLE_ITALIC "+
"Font.SIZE_LARGE";
break;
case '2':
font=Font.getFont(Font.FACE_PROPORTIONAL,
Font.STYLE_ITALIC, Font.SMALL) ;
msg = "Font:FACE_PROPORTIONAL Font.STYLE_ITALIC "+
"Font.SIZE_SMALL";
break;
case '3':
font=Font.getFont(Font.FACE_SYSTEM ,
Font.STYLE_BOLD, Font.SIZE_LARGE) ;
msg="Font:FACE_SYSTEM Font.STYLE_BOLD "+
"Font.SIZE_LARGE";
break;
}
}


//Handling keyEvents
protected void keyPressed(int keyCode) {
changeValue(keyCode);
repaint();
}

}

Capturing Video with J2ME

Illustration below takes pictures on a J2ME device.

import java.io.IOException;
import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.media.control.VideoControl;

public class VideoMIDlet extends MIDlet implements CommandListener {

private Display display;
private Form form;
private Command exit,back,capture,camera;
private Player player;
private VideoControl videoControl;
private Video video;

public VideoMIDlet() {

exit = new Command("Exit", Command.EXIT, 0);
camera = new Command("Camera", Command.SCREEN, 0);
back = new Command("Back", Command.BACK, 0);
capture = new Command("Capture", Command.SCREEN, 0);

form = new Form("Capture Video");
form.addCommand(camera);
form.setCommandListener(this);
}

public void startApp() {
display = Display.getDisplay(this);
display.setCurrent(form);
}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

public void commandAction(Command c, Displayable s) {
if (c == exit) {
destroyApp(true);
notifyDestroyed();
} else if (c == camera) {
showCamera();
} else if (c == back)
display.setCurrent(form);
else if (c == capture) {
video = new Video(this);
video.start();
}
}

public void showCamera() {
try {
player = Manager.createPlayer("capture://video");
player.realize();

videoControl = (VideoControl)player.getControl("VideoControl");
Canvas canvas = new VideoCanvas(this, videoControl);
canvas.addCommand(back);
canvas.addCommand(capture);
canvas.setCommandListener(this);
display.setCurrent(canvas);
player.start();
} catch (IOException ioe) {} catch (MediaException me) {}
}

class Video extends Thread {
videoMIDlet midlet;
public Video(VideoMIDlet midlet) {
this.midlet = midlet;
}

public void run() {
captureVideo();

}

public void captureVideo() {
try {
byte[] raw = videoControl.getSnapshot(null);
Image image = Image.createImage(raw, 0, raw.length);
form.append(image);
display.setCurrent(form);

player.close();
player = null;
videoControl = null;
} catch (MediaException me) { }
}
};
}

import javax.microedition.lcdui.*;
import javax.microedition.media.MediaException;
import javax.microedition.media.control.VideoControl;

public class VideoCanvas extends Canvas {
private VideoMIDlet midlet;

public VideoCanvas(VideoMIDlet midlet, VideoControl videoControl) {
int width = getWidth();
int height = getHeight();
this.midlet = midlet;

videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, this);
try {
videoControl.setDisplayLocation(2, 2);
videoControl.setDisplaySize(width - 4, height - 4);
} catch (MediaException me) {}
videoControl.setVisible(true);
}

public void paint(Graphics g) {
int width = getWidth();
int height = getHeight();

g.setColor(0x00ff00);
g.drawRect(0, 0, width - 1, height - 1);
g.drawRect(1, 1, width - 3, height - 3);
}

Playing local MP3

The method below creates player and play mp3 file.
public void run()
{
try
{
InputStream is = getClass().getResourceAsStream("/your.mp3");
player = Manager.createPlayer(is,"audio/mpeg");

player.realize();
// get volume control for player and set volume to max
vc = (VolumeControl) player.getControl("VolumeControl");
if(vc != null)
{
vc.setLevel(100);
}
player.prefetch();
player.start();
}
catch(Exception e)
{}
}

Playing Video

MMAPI(Mobile Media API) provides a framework for playing media content on J2ME devices.There are protocols defined for real-time streaming of Internet radio content, streaming other RTP (Real-time Transport Protocol) content, capturing audio, and taking pictures.

The method below plays a video file the on mobile device:
public void run()
{
try
{
String url = "http://server/video-mpeg.mpg";
Player p = Manager.createPlayer(url);
p.realize();

//Get the video controller
VideoControl video = (VideoControl) p.getControl("VideoControl");

//Get a GUI to display the video
Item videoItem = (Item)video.initDisplayMode(
VideoControl.USE_GUI_PRIMITIVE, null);

//Append the GUI to a form
videoForm.append(videoItem);

//Start the video
p.start();
}
catch(Exception e)
{}
}

If you want to play the video from an rtsp server, you only need to change url with "rtsp://server/video.mpg". This will only work on devices which support real time input streams.
 

Design by Blogger Buster | Distributed by Blogging Tips