lwuit video component floats over commands - java

My LWUIT video component floats over my commands. Any idea how I can fix this? My code is below.
public void showQuickProfileForm() {
Form f = new Form();
VideoComponent videoComponent = null;
try {
videoComponent = VideoComponent.createVideoPeer("capture://image");
} catch (IOException e) {
// e.printStackTrace();
try {
videoComponent = VideoComponent.createVideoPeer("capture://video");
} catch (IOException ex) {
// ex.printStackTrace();
}
}
videoComponent.setPreferredH((int) (Display.getInstance().getDisplayHeight() * 0.8));
videoComponent.setPreferredW(Display.getInstance().getDisplayWidth());
Player player = (Player) videoComponent.getNativePeer();
try {
player.realize();
player.start();
} catch (MediaException ex) {
ex.printStackTrace();
}
VideoControl videoControl = (VideoControl) player.getControl("VideoControl");
videoComponent.start();
f.addComponent(videoComponent);
f.addCommand(new Command("capture", 1));
f.show();
}
public void actionPerformed(ActionEvent evt) {
if (evt.getCommand().getId() == 1) {
// midlet.destroyApp(true);
Form d = new Form();
d.show();
}
}

Use this after initializing video control, change width and height as you see fit :
videoControl.setDisplaySize(width + 4, height - 25);

Related

What is causing my java awt and swing browser's back button to not function properly?

The actionForward and actionBack functions are both throwing IndexOutofBounds exceptions and I cannot figure out why? I was tasked with making a very simple web browser with function back and forward buttons as well as a url address bar. When the ArrayList pageList has a size of 2 the buttons work as intended. However, once the pageList has a size of 3 or more they break.
class Proj03RunnerHtmlHandler extends JFrame implements HyperlinkListener{
JEditorPane html;
JButton backButton, forwardButton;
JTextField urlTextField;
ArrayList<String> pageList = new ArrayList<String>();
public Proj03RunnerHtmlHandler(String website) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Asg03");
pageList.add(website);
try{
if(website != null){
html = new JEditorPane(website);
html.setEditable(false);
html.addHyperlinkListener(this);
JPanel buttonPanel = new JPanel();
backButton = new JButton("Back");
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionBack();
}
});
buttonPanel.add(backButton);
urlTextField = new JTextField("http://www.somesite.com");
urlTextField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
try {
showPage(new URL(urlTextField.getText()), true);
} catch(Exception ey){
ey.printStackTrace();
}
}
}
});
buttonPanel.add(urlTextField);
forwardButton = new JButton("Forward");
forwardButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionForward();
}
});
buttonPanel.add(forwardButton);
JScrollPane scroller = new JScrollPane();
JViewport vp = scroller.getViewport();
vp.add(html);
this.getContentPane().add(buttonPanel, BorderLayout.NORTH);
this.getContentPane().add(scroller, BorderLayout.CENTER);
this.setSize(669,669);
this.setVisible(true);
}
} catch(Exception e){
e.printStackTrace();
}
}
public void hyperlinkUpdate(HyperlinkEvent e){
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED){
if (!(e instanceof HTMLFrameHyperlinkEvent)) {
try {
showPage(e.getURL(), true);
} catch(Exception ex){
ex.printStackTrace();
}
}
}
}
public void actionBack() {
try {
String currentUrl = html.getPage().toString();
int currentIndex = pageList.indexOf(currentUrl);
showPage(new URL(pageList.get(currentIndex - 1)), false);
} catch (Exception e){
e.printStackTrace();
}
}
public void actionForward() {
try {
String currentUrl = html.getPage().toString();
int currentIndex = pageList.indexOf(currentUrl);
showPage(new URL(pageList.get(currentIndex + 1)), false);
} catch (Exception e){
e.printStackTrace();
}
}
public void showPage(URL pageUrl, boolean addToList){
try {
URL currentUrl = html.getPage();
html.setPage(pageUrl);
if (addToList) {
int listSize = pageList.size();
if (listSize > 0) {
int pageIndex =
pageList.indexOf(currentUrl.toString());
if (pageIndex < listSize - 1) {
for (int i = listSize - 1; i > pageIndex; i--) {
pageList.remove(i);
}
}
}
pageList.add(pageUrl.toString());
}
urlTextField.setText(pageUrl.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (pageIndex < listSize - 1) {
for (int i = listSize - 1; i > pageIndex; i--) {
pageList.remove(i);
}
}
There's two obvious problems with this.
You should be removing only one page from the history.
If the page is at the end (pageIndex == listSize - 1), then you don't remove the page but do add a duplicate.

Why Applet shuts the server down?

I am implementing a recording system using Java applet for my project but i am facing one problem during closing the applet, the applet shuts the server down.Is there any way to resolve this issue? I want to continue work on my project after completing the recording part but after recording when I close the applet it stops the server also So i need to restart the server again.
Any help or suggestion?
Code :-
public class Main extends JPanel implements ActionListener {
public Main() {
setLayout(new BorderLayout());
EmptyBorder eb = new EmptyBorder(5, 5, 5, 5);
SoftBevelBorder sbb = new SoftBevelBorder(SoftBevelBorder.LOWERED);
setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel p1 = new JPanel();
// p1.setLayout(new BoxLayout(p1, BoxLayout.X_AXIS));
JPanel p2 = new JPanel();
p2.setBorder(sbb);
p2.setLayout(new BoxLayout(p2, BoxLayout.X_AXIS));
JPanel buttonsPanel = new JPanel();
buttonsPanel.setBorder(new EmptyBorder(10, 0, 5, 0));
radioGroup1 = new CheckboxGroup();
radio1 = new Checkbox("Record : ", radioGroup1,true);
p2.add(radio1);
playB = addButton("Play", buttonsPanel, false);
captB = addButton("Record", buttonsPanel, true);
closeA = addButton("Close", buttonsPanel, true);
p2.add(buttonsPanel);
p1.add(p2);
add(p1);
}
public void open() {
}
public void close() {
if (playback.thread != null) {
playB.doClick(0);
}
if (capture.thread != null) {
captB.doClick(0);
}
}
private JButton addButton(String name, JPanel p, boolean state) {
JButton b = new JButton(name);
b.addActionListener(this);
b.setEnabled(state);
p.add(b);
return b;
}
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
if (obj.equals(playB)) {
if (playB.getText().startsWith("Play")) {
playback.start();
captB.setEnabled(false);
playB.setText("Stop");
} else {
playback.stop();
captB.setEnabled(true);
playB.setText("Play");
}
} else if (obj.equals(captB)) {
if (captB.getText().startsWith("Record")) {
capture.start();
playB.setEnabled(false);
captB.setText("Stop");
} else {
capture.stop();
playB.setEnabled(true);
}
}
else if(obj.equals(closeA)) {
System.exit(0);
}
}
public class Playback implements Runnable {
SourceDataLine line;
Thread thread;
public void start() {
errStr = null;
thread = new Thread(this);
thread.setName("Playback");
thread.start();
}
public void stop() {
thread = null;
}
private void shutDown(String message) {
if ((errStr = message) != null) {
System.err.println(errStr);
}
if (thread != null) {
thread = null;
captB.setEnabled(true);
playB.setText("Play");
}
}
public void run() {
AudioFormat format = getAudioFormat();
try {
audioInputStream = AudioSystem.getAudioInputStream(wavFile);
} catch (UnsupportedAudioFileException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
AudioInputStream playbackInputStream = AudioSystem.getAudioInputStream(format,
audioInputStream);
if (playbackInputStream == null) {
shutDown("Unable to convert stream of format " + audioInputStream + " to format " + format);
return;
}
// get and open the source data line for playback.
try {
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(format, bufSize);
} catch (LineUnavailableException ex) {
shutDown("Unable to open the line: " + ex);
return;
}
// play back the captured audio data
int frameSizeInBytes = format.getFrameSize();
int bufferLengthInFrames = line.getBufferSize() / 8;
int bufferLengthInBytes = bufferLengthInFrames * frameSizeInBytes;
byte[] data = new byte[bufferLengthInBytes];
int numBytesRead = 0;
// start the source data line
line.start();
while (thread != null) {
try {
if ((numBytesRead = playbackInputStream.read(data)) == -1) {
break;
}
int numBytesRemaining = numBytesRead;
while (numBytesRemaining > 0) {
numBytesRemaining -= line.write(data, 0, numBytesRemaining);
}
} catch (Exception e) {
shutDown("Error during playback: " + e);
break;
}
}
// we reached the end of the stream.
// let the data play out, then
// stop and close the line.
if (thread != null) {
line.drain();
}
line.stop();
line.close();
line = null;
shutDown(null);
}
} // End class Playback
/**
* Reads data from the input channel and writes to the output stream
*/
class Capture implements Runnable {
TargetDataLine line;
Thread thread;
public void start() {
errStr = null;
thread = new Thread(this);
thread.setName("Capture");
thread.start();
}
public void stop() {
thread = null;
line.close();
//thread.stop();
}
private void shutDown(String message) {
if ((errStr = message) != null && thread != null) {
thread = null;
playB.setEnabled(true);
captB.setText("Record");
System.err.println(errStr);
}
}
public void run() {
duration = 0;
audioInputStream = null;
Playback pb = new Playback();
AudioFormat format = pb.getAudioFormat();
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
// get and open the target data line for capture.
try {
line = (TargetDataLine) AudioSystem.getLine(info);
// line.open(format, line.getBufferSize());
line.open(format);
line.start();
// saving audio file
AudioInputStream ais = new AudioInputStream(line);
// start recording
AudioSystem.write(ais, fileType, wavFile);
} catch (LineUnavailableException ex) {
shutDown("Unable to open the line: " + ex);
return;
} catch (SecurityException ex) {
shutDown(ex.toString());
//JavaSound.showInfoDialog();
return;
} catch (Exception ex) {
shutDown(ex.toString());
return;
}
// we reached the end of the stream.
// stop and close the line.
line.stop();
line.close();
line = null;
// stop and close the output stream
try {
out.flush();
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
// load bytes into the audio input stream for playback
byte audioBytes[] = out.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(audioBytes);
audioInputStream = new AudioInputStream(bais, format, audioBytes.length / frameSizeInBytes);
long milliseconds = (long) ((audioInputStream.getFrameLength() * 1000) / format
.getFrameRate());
duration = milliseconds / 1000.0;
try {
audioInputStream.reset();
} catch (Exception ex) {
ex.printStackTrace();
return;
}
}
} // End class Capture
}
This code don't look so good
else if(obj.equals(closeA)) {
System.exit(0);
}
this will cause the JVM to shutdown. I would have thought that you just want the applet to be in a stopped state.

Stop process of webcam in java netbeans

I want to capture an image using an available webcam. I have successfully accessed the webcam but I couldn't stop the webcam process. I want to stop the webcam process using a stop button. How can I accomplish this? This my code:
public Component componen() throws IOException , NoPlayerException, CannotRealizeException
{
Component comp_video;
MediaLocator loo = new MediaLocator("vfw://0");
try {
broadcast = Manager.createRealizedPlayer(loo);
} catch (IOException ex) {
Logger.getLogger(CapturImage.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoPlayerException ex) {
Logger.getLogger(CapturImage.class.getName()).log(Level.SEVERE, null, ex);
} catch (CannotRealizeException ex) {
Logger.getLogger(CapturImage.class.getName()).log(Level.SEVERE, null, ex);
}
broadcast.start();
if((comp_video = broadcast.getVisualComponent()) != null)
{
comp_video.setSize(321,228);
return comp_video;
}
else
{
return null;
}
}
public void capture_image()
{
FrameGrabbingControl grab = (FrameGrabbingControl) broadcast.getControl("javax.media.control.FrameGrabbingControl");
javax.media.Buffer buff = grab.grabFrame();
BufferToImage buffer =new BufferToImage((VideoFormat) buff.getFormat());
img = buffer.createImage(buff);
}
public void set_iamge_label(final JLabel lb)
{
Thread web = new Thread(){
public void run(){
capture_image();
Rectangle rect = lb.getBounds();
Image img1 = img.getScaledInstance(rect.width,rect.height,Image.SCALE_DEFAULT);
lb.setIcon(new javax.swing.ImageIcon(img1));
}
};
web.start();
}

How do I rework my Java applet code to use a JPanel instead of a JFrame?

I'm a .net programmer just learning Java. I've been working on this issue for the past 2 weeks...
Here is my code to show my security system webcams and update the images in a JFrame running in an applet: (I need to convert this code to work in a JPanel instead!)
public class Streamer extends JApplet {
String PATH = "C:/Security/CamCap/";
Integer UPDATE_INTERVAL = 100;
String CAM1FILE = "current1.png";
String CAM2FILE = "current2.png";
String CAM3FILE = "current3.png";
String CAM4FILE = "current4.png";
String CAM5FILE = "current5.png";
String CAM6FILE = "current6.png";
String CAM7FILE = "current7.png";
String CAM8FILE = "current8.png";
String LOGOFILE = "logo.png";
private String path1 = PATH + CAM1FILE;
private String path2 = PATH + CAM2FILE;
private String path3 = PATH + CAM3FILE;
private String path4 = PATH + CAM4FILE;
private String path5 = PATH + CAM5FILE;
private String path6 = PATH + CAM6FILE;
private String path7 = PATH + CAM7FILE;
private String path8 = PATH + CAM8FILE;
private String pathLogo = PATH + LOGOFILE;
JFrame frame = new JFrame("#Home - Live Video");
boolean loaded = false;
JLabel label1, label2, label3, label4, label5, label6, label7, label8, labelLogo;
public void init()
{
frame.getContentPane().setBackground(Color.BLACK);
frame.setMinimumSize(new Dimension(1087, 777));
frame.setLayout(new GridLayout(3, 3, 2, 2));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1090,780);
frame.getContentPane().setSize(1087, 777);
frame.setLocationRelativeTo ( null );
frame.setVisible(true);
//INITIALIZE CAMERA 1
ImageIcon icon1 = new ImageIcon();
loaded = false;
while(!loaded)
{
try {
icon1 = new ImageIcon(ImageIO.read(new File(path1)));
loaded = true;
} catch (Exception ex) { loaded = false; }
}
label1 = new JLabel(icon1);
frame.add(label1);
//INITIALIZE CAMERA 2
ImageIcon icon2 = new ImageIcon();
loaded = false;
while(!loaded)
{
try {
icon2 = new ImageIcon(ImageIO.read(new File(path2)));
loaded = true;
} catch (Exception ex) { loaded = false; }
}
label2 = new JLabel(icon2);
frame.add(label2);
//INITIALIZE CAMERA 3
ImageIcon icon3 = new ImageIcon();
loaded = false;
while(!loaded)
{
try {
icon3 = new ImageIcon(ImageIO.read(new File(path3)));
loaded = true;
} catch (Exception ex) { loaded = false; }
}
label3 = new JLabel(icon3);
frame.add(label3);
//INITIALIZE CAMERA 4
ImageIcon icon4 = new ImageIcon();
loaded = false;
while(!loaded)
{
try {
icon4 = new ImageIcon(ImageIO.read(new File(path4)));
loaded = true;
} catch (Exception ex) { loaded = false; }
}
label4 = new JLabel(icon4);
frame.add(label4);
//INITIALIZE CAMERA 5
ImageIcon icon5 = new ImageIcon();
loaded = false;
while(!loaded)
{
try {
icon5 = new ImageIcon(ImageIO.read(new File(path5)));
loaded = true;
} catch (Exception ex) { loaded = false; }
}
label5 = new JLabel(icon5);
frame.add(label5);
//INITIALIZE CAMERA 6
ImageIcon icon6 = new ImageIcon();
loaded = false;
while(!loaded)
{
try {
icon6 = new ImageIcon(ImageIO.read(new File(path6)));
loaded = true;
} catch (Exception ex) { loaded = false; }
}
label6 = new JLabel(icon6);
frame.add(label6);
//INITIALIZE CAMERA 7
ImageIcon icon7 = new ImageIcon();
loaded = false;
while(!loaded)
{
try {
icon7 = new ImageIcon(ImageIO.read(new File(path7)));
loaded = true;
} catch (Exception ex) { loaded = false; }
}
label7 = new JLabel(icon7);
frame.add(label7);
//INITIALIZE CAMERA 8
ImageIcon icon8 = new ImageIcon();
loaded = false;
while(!loaded)
{
try {
icon8 = new ImageIcon(ImageIO.read(new File(path8)));
loaded = true;
} catch (Exception ex) { loaded = false; }
}
label8 = new JLabel(icon8);
frame.add(label8);
//INITIALIZE LOGO
ImageIcon iconLogo = new ImageIcon();
try {
iconLogo = new ImageIcon(ImageIO.read(new File(pathLogo)));
loaded = true;
} catch (Exception ex) { loaded = false; }
labelLogo = new JLabel(iconLogo);
frame.add(labelLogo);
frame.setVisible(true);
run();
}
public void run()
{
while(true)
{
try {
ImageIcon icon1 = new ImageIcon(ImageIO.read(new File(path1)));
label1.setIcon(icon1);
label1.repaint();
} catch (Exception ex) {}
try {
ImageIcon icon2 = new ImageIcon(ImageIO.read(new File(path2)));
label2.setIcon(icon2);
label2.repaint();
} catch (Exception ex) {}
try {
ImageIcon icon3 = new ImageIcon(ImageIO.read(new File(path3)));
label3.setIcon(icon3);
label3.repaint();
} catch (Exception ex) {}
try {
ImageIcon icon4 = new ImageIcon(ImageIO.read(new File(path4)));
label4.setIcon(icon4);
label4.repaint();
} catch (Exception ex) {}
try {
ImageIcon icon5 = new ImageIcon(ImageIO.read(new File(path5)));
label5.setIcon(icon5);
label5.repaint();
} catch (Exception ex) {}
try {
ImageIcon icon6 = new ImageIcon(ImageIO.read(new File(path6)));
label6.setIcon(icon6);
label6.repaint();
} catch (Exception ex) {}
try {
ImageIcon icon7 = new ImageIcon(ImageIO.read(new File(path7)));
label7.setIcon(icon7);
label7.repaint();
} catch (Exception ex) {}
try {
ImageIcon icon8 = new ImageIcon(ImageIO.read(new File(path8)));
label8.setIcon(icon8);
label8.repaint();
} catch (Exception ex) {}
try {
Thread.sleep(UPDATE_INTERVAL);
} catch (Exception ex) {}
}
}
}
I've tried everything, and I can't find a way to convert this code to work inside a JPanel. I need to use a JPanel in my applet so that my cameras don't show up in a new, separate window (JFrame).
Does anyone know how to convert (just a small portion of) this code to draw and refresh my images in a JPanel?
Thanks (in advance)!
An example of using a GUI in a JLabel that uses a Swing Timer for animation, and which is displayed in a JApplet:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class SpriteAnimationApplet extends JApplet {
private static final String SPRITE_SHEET_SPEC = "http://www.funorb.com/img/images/game/"
+ "central/dev_diary/sprite_sheet_full.gif";
private static final int SPRITE_ROWS = 8; // an 8 x 8 sprite sheet
#Override
public void init() {
try {
final Icon[] icons = SpriteIO.getSprites(SPRITE_SHEET_SPEC, SPRITE_ROWS);
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
SpriteAnimationPanel spritePanel = new SpriteAnimationPanel(icons);
getContentPane().add(spritePanel);
spritePanel.startAnimation();
}
});
} catch (InvocationTargetException e) {
e.printStackTrace();
System.exit(-1);
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(-1);
} catch (MalformedURLException e) {
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
}
class SpriteIO {
public static Icon[] getSprites(String spriteSheetSpec, int spriteRows)
throws MalformedURLException, IOException {
Icon[] icons = new Icon[spriteRows * spriteRows];
URL spriteSheetUrl = new URL(spriteSheetSpec);
BufferedImage spriteSheet = ImageIO.read(spriteSheetUrl);
double wD = (double) spriteSheet.getWidth() / spriteRows;
double hD = (double) spriteSheet.getHeight() / spriteRows;
int w = (int) wD;
int h = (int) hD;
for (int i = 0; i < spriteRows; i++) {
for (int j = 0; j < spriteRows; j++) {
int x = (int) (i * wD);
int y = (int) (j * hD);
BufferedImage img = spriteSheet.getSubimage(x, y, w, h);
icons[j * spriteRows + i] = new ImageIcon(img);
}
}
return icons;
}
}
#SuppressWarnings("serial")
class SpriteAnimationPanel extends JPanel {
private static final int TIMER_DELAY = 200;
private Icon[] icons;
private JLabel animationLabel = new JLabel();
public SpriteAnimationPanel(Icon[] icons) {
this.icons = icons;
setLayout(new BorderLayout());
add(animationLabel );
}
public void startAnimation() {
Timer spriteTimer = new Timer(TIMER_DELAY, new ActionListener() {
private int iconIndex = 0;
#Override
public void actionPerformed(ActionEvent arg0) {
animationLabel.setIcon(icons[iconIndex]);
iconIndex++;
iconIndex %= icons.length;
}
});
spriteTimer.start();
}
}
ImageIcon icon5 = new ImageIcon(ImageIO.read(new File(path5)));
Applet resources are typically loaded from the run-time class-path or home server of the applet. Avoid using File objects in an applet unless they are provided by the user from a JFileChooser (not the case here).
ImageIcon icon5 = new ImageIcon(this.getClass().getResource(href5));
URLs to resources can be formed relative to the document or code base of the applet.
Tips
When in doubt, print out!
For every catch dump the stack trace.
} catch (Exception ex) {
ex.printStackTrace();
//..
Watch for output
Ensure the Java Console is shown when the browser launches an applet.
Perform animation using a Swing Timer
As discussed/shown by HFoE.
Image caching
Images in applets are typically cached. It seems the applet is loading an image multiple times, expecting it to be different each time (the last frame of the security camera). To get around that, load the image as a byte[] and put it into a ByteArrayInputStream. Then load the image from the stream using ImageIO.
Since the JRE cannot map the byte[] of the image to a File path or URL, it cannot be cached.

Xuggler screenRecording code affecting sound recording

I am working on an application for screencast with audio. screen recording with sound is working fine but the issue is that suppose I do recording of 5 mins then generated video file is of 5 min but generated audio file is of 4 min 45 sec. So basically the issue is that both audio and video are not in sync, audio file duration is less as compared to video file.
Both audio and video file recording are running in separate thread but still something is wrong.
VideoCapturing code:
public void run() {
setVideoParameters();
FRAME_RATE = frameRate;
// let's make a IMediaWriter to write the file.
writer = ToolFactory.makeWriter(movieFile.getName());
screenBounds = new Rectangle(RecorderSettings.m_CapRectX,
RecorderSettings.m_CapRecY,
(int) RecorderSettings.m_CapRectWidth,
(int) RecorderSettings.m_CapRecHeight);
// We tell it we're going to add one video stream, with id 0,
// at position 0, and that it will have a fixed frame rate of
// FRAME_RATE.
// ScreenWidth && ScreenHeight multiplied by 3/4 to reduce pixel to 3/4
// of actual.
// writer.addVideoStream(0, 0, ICodec.ID.CODEC_ID_MPEG4,
// screenBounds.width , screenBounds.height );
writer.addVideoStream(0, 0, vcodec.getID(),
(screenBounds.width * upperLimit) / lowerLimit,
(screenBounds.height * upperLimit) / lowerLimit);
// To have start time of recording
startTime = System.nanoTime();
while (isStopProceesBtnClk) {
try {
if (!isStopProceesBtnClk) {
break;
} else {
synchronized (this) {
while (isPauseProceesBtnClk) {
try {
// catches starting time of pause.
pauseStartTime = System.nanoTime();
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
BufferedImage screen = getDesktopScreenshot();
// convert to the right image type
BufferedImage bgrScreen = convertToType(screen, BufferedImage.TYPE_3BYTE_BGR);
// encode the image to stream #0
if (totalPauseTime > 0) {
writer.encodeVideo(0, bgrScreen, (System.nanoTime() - startTime)- totalPauseTime, TimeUnit.NANOSECONDS);
} else {
writer.encodeVideo(0, bgrScreen, System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
}
// sleep for frame rate milliseconds
try {
Thread.sleep((long) (1000 / FRAME_RATE));
} catch (InterruptedException e) {
// ignore
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
try {
writer.close();
writer = null;
Runtime.getRuntime().gc();
} catch (Exception e) {
// ignore errors
}
// tell the writer to close and write the trailer if needed
}
public static BufferedImage convertToType(BufferedImage sourceImage, int targetType) {
BufferedImage image;
// if the source image is already the target type, return the source
// image
if (sourceImage.getType() == targetType) {
image = sourceImage;
}
// otherwise create a new image of the target type and draw the new
// image
else {
image = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), targetType);
if (true) {
int x = MouseInfo.getPointerInfo().getLocation().x - 25;
int y = MouseInfo.getPointerInfo().getLocation().y - 37;
Graphics2D graphics2D = sourceImage.createGraphics();// getGraphics().drawImage(m_MouseIcon,
// x, y, 48, 48, null);
graphics2D.drawImage(SimpleWebBrowserExample.m_MouseIcon, x, y,
48, 48, null);
}
image.getGraphics().drawImage(sourceImage, 0, 0, null);
}
return image;
}
private BufferedImage getDesktopScreenshot() {
try {
// Robot captures screen shot
Robot robot = new Robot();
Rectangle captureSize = new Rectangle(screenBounds);
return robot.createScreenCapture(captureSize);
} catch (AWTException e) {
e.printStackTrace();
return null;
}
}
AudioCapturing Code:
public void run() {
init();
DataLine.Info info = new DataLine.Info(TargetDataLine.class,audioFormat,(int) (m_AudioFreq * sampleSizeInBytes));
try
{
m_TargetLine = (TargetDataLine) AudioSystem.getLine(info);
m_TargetLine.open(audioFormat, info.getMaxBufferSize());
}
catch(Exception exp){
exp.printStackTrace();
}
AudioFileFormat.Type targetType = AudioFileFormat.Type.WAVE;
try
{
m_outputFile = new File(bufferFileName);
while (m_outputFile.exists() && !m_outputFile.delete())
{
m_outputFile = BerylsUtility.getNextFile(m_outputFile);
}
FileOutputStream outFileStream = new FileOutputStream(m_outputFile);
audioOutStream = new BufferedOutputStream(outFileStream,memoryBufferSize);
}
catch (FileNotFoundException fe){
System.out.println("FileNotFoundException in VoiceCapturing.java :: " + fe);
}
catch (OutOfMemoryError oe){
System.out.println("OutOfMemoryError in VoiceCapturing.java " + oe);
}
while (isStopProceesBtnClk) {
try {
if (!isStopProceesBtnClk) {
break;
} else {
synchronized (this) {
while (isPauseProceesBtnClk) {
try {
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
try
{
m_TargetLine.start();
int cnt = m_TargetLine.read(tempBuffer,0,tempBuffer.length);
if(cnt > 0){
audioOutStream.write(tempBuffer,0,cnt);
}
}
catch (Exception e){
System.out.println("Exception in VoiceCapturing.java :: " + e);
}
/*finally{
finish();
}*/
}
} catch (Exception e) {
e.printStackTrace();
}
}
finish();
}
public synchronized void finish()
{
try
{
System.out.println("AudioFinish");
audioOutStream.close();
FileInputStream audioInAgain = new FileInputStream(m_outputFile);
long sampleBytes = m_outputFile.length();
long sizeOfFrame = (long) m_SampleRate * m_Channels / 8;
BufferedInputStream buffAudioIn = new BufferedInputStream(audioInAgain, memoryBufferSize);
AudioInputStream a_input = new AudioInputStream(buffAudioIn, audioFormat, sampleBytes / sizeOfFrame);
while (m_AudioFile.exists() && !m_AudioFile.canWrite())
{
m_AudioFile = BerylsUtility.getNextFile(m_AudioFile);
}
AudioSystem.write(a_input, m_targetType, m_AudioFile);
buffAudioIn.close();
m_outputFile.delete();
}
catch (Exception e)
{
e.printStackTrace();
}
}
could someone guide me on this...
Thanks.

Categories