June 13, 2014

Security system :Motion Detection System in java

Motion detection system in java : alert when any one pass before system camera

Description : This is a small example for security system in java which send alert through mail and sound while any trespassers pass before your camera connected to system (computer). The program is developed in java media framework. You need jmf.jar and mds.jar to run that code. For sending mail using java mail service application you need to download mail.jar file. The project consist of only 3 packages. Only you have to do is to create a java application in eclipse. copy and paste the following code to your project. compile it and run. Make sure you had added all the jar files to your project. Create a javasecurityalert wave file. Please provide your feed back through comments. Please rate the post.



MainFrame.java
package com.mds.frames;
import java.awt.Container;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import com.mds.serv.AePlayWave;
import com.mds.serv.AlarmSound;
import com.mds.serv.ImageCompare;
import com.mds.serv.MDSMailer;
import com.mds.serv.SwingCapture;
public class MainFrame extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
    private java.awt.Container c = null;
    private com.mds.serv.SwingCapture sc = null;
    private JPanel videoPanel = null;
    private Image refImg = null;
    private Image currentImg = null;
    private File saveImgDir = null;
    private ImageCompare imc = null;
    private AlarmSound as = null;
    private static boolean alarm = true;
    private AePlayWave playWave = null;
    private Thread t2 = null;
    private Thread t1 = null;
    private JButton captureButton = null;
    private static int num = 0;
    private File saveCaptureDir = null;
    private Thread t3 = null;
    private JButton imgSet = null;
    private JButton start = null;
    private JFileChooser jf = null;
    private Thread mainThread = null;
    private JButton stop = null;
   /**
     * This is the default constructor
     */
    public MainFrame() {
        super();
        initialize();
    }
  /**
     * This method initializes this
     *
     * @return void
     */
    private void initialize() {
        this.setSize(900, 550);
        this.setContentPane(getContainer());
        this.setTitle("Motion Detection System");
        this.addWindowListener(new WindowAdapter()
        {
            @Override
            public void windowClosing(WindowEvent e)
            {
//                playerclose();
                System.exit(0);
            }
        });
      
    }
  
    private Container getContainer()
    {
        c = new Container();
       imgSet = new JButton();
        imgSet.setText("Set Reference Image");
        imgSet.setBounds(680,180,200,25);
        imgSet.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                videoPanel.setEnabled(true);
                refImg = sc.imageCapture();
//                sc.saveJPG(refImg, s)
            }
        });
        c.add(imgSet);
      
        jf = new JFileChooser();
        start = new JButton("Start Detection");
        start.setBounds(680,230,200,25);
        start.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                saveImgDir = chooseSaveImgDir().getParentFile();
                if(refImg!=null)
                {
                    if(mainThread == null)
                    {
                        startNewThread();
//                        System.out.println("MainThread Started");
                    }
                    else if(mainThread.isAlive())
                        mainThread.resume();
                }
                else
                    showDialog("Set Reference Image");
              
            }
        });
        c.add(start);
      
        stop = new JButton("Stop");
        stop.setBounds(680,280,200,25);
        stop.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                try {
                  
//                    if(mainThread == null)
                    if(mainThread.isAlive())
                        mainThread.suspend();
                  
                } catch(NullPointerException e1) {
                    showDialog("Detection Not Started Yet");
                }
              
            }
        });
        c.add(stop);
      
        sc = new SwingCapture();
        videoPanel = sc.getPlayerPanel();
        videoPanel.setEnabled(false);
        c.add(videoPanel);

        playWave = new AePlayWave("alarm.wav");
        t2 = new Thread(playWave);
          
      
        try {
            Thread.sleep(10000);
//            refImg = sc.imageCapture();
//            sc.saveJPG(currentImg, "D:\\Backups\\Saved\\img.jpg");
//            sc.saveJPG(refImg, "c:\\RefImg.jpg");
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
      
        captureButton = new JButton();
        captureButton.setText("Capture Frame");
        captureButton.setBounds(680,330,200,25);
        captureButton.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e)
                {
                    saveCaptureDir = chooseSaveImgDir();
                    System.out.println(saveCaptureDir.getAbsolutePath()+saveCaptureDir.getName());
//                    if(!saveCaptureDir.exists())
//                        saveCaptureDir.mkdirs();
                    SwingCapture.saveJPG(sc.imageCapture(),saveCaptureDir.getAbsolutePath());
                    num++;
                }
          
        });
        c.add(captureButton);      
        return c;
      
    }
  
    private void startNewThread()
    {
        mainThread = new Thread(this);
        mainThread.start();
    }
  
    private void showDialog(String message)
    {
        JOptionPane.showMessageDialog(this, message);
    }
  
    private File chooseSaveImgDir()
    {
        File file = null;
        if(jf.showSaveDialog(this)==JFileChooser.APPROVE_OPTION)
        {
            file = jf.getSelectedFile();
//            System.out.println(saveImgDir.getName());
        }
        return file;

    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        int i =0;
//        saveImgDir = new File("D:\\Backups\\Saved");
        if(saveImgDir==null)
        {
            chooseSaveImgDir();
        }
//        if(!saveImgDir.exists())
//            saveImgDir.mkdirs();
        while(true)
        {
            try {
//                Thread.sleep(250);
                currentImg = sc.imageCapture();
                imc = new ImageCompare(refImg,currentImg);
//                t3 = new Thread(imc);
//                t3.run();
                if(!imc.compare())
                {
                  
                    System.out.println("hi");
                    t2.run();
                    SwingCapture.saveJPG(currentImg, saveImgDir+"\\img"+i+".jpg");
                    MDSMailer m = new MDSMailer(saveImgDir+"\\img"+i+".jpg");
                    t3 = new Thread(m);
                    t3.start();
                    refImg = currentImg;
                }
              
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            i++;
        }
    }

  
    public static void main(String[] args) {
      
        MainFrame m = new MainFrame();
        m.setVisible(true);
//        Thread t = new Thread(m);
//        t.start();
    }
  

}

-------------------------------------
LoginFrame.java


package com.mds.frames;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
public class LoginFrame extends JFrame {
    private static final long serialVersionUID = 1L;
    private JPanel jContentPane = null;
    private JLabel NameLabel = null;
    private JLabel PassLabel = null;
    private JTextField NameTextField = null;
    private JPasswordField PasswordField = null;
    private JButton LoginButton = null;
    private JButton ClearButton = null;
    /**
     * This is the default constructor
     */
    public LoginFrame() {
        super();
        initialize();
    }
    /**
     * This method initializes this
     *
     * @return void
     */
    private void initialize() {
        this.setSize(500, 400);
        this.setContentPane(getJContentPane());
       
        this.setTitle("Login");
    }
    /**
     * This method initializes jContentPane
     *
     * @return javax.swing.JPanel
     */
    private JPanel getJContentPane() {
        if (jContentPane == null) {
            PassLabel = new JLabel();
            PassLabel.setBounds(new Rectangle(75, 170, 100, 30));
            PassLabel.setText("Password : ");
            NameLabel = new JLabel();
            NameLabel.setBounds(new Rectangle(75, 120, 100, 30));
            NameLabel.setText("Name : ");
            jContentPane = new JPanel();
            jContentPane.setLayout(null);
            jContentPane.add(NameLabel, null);
            jContentPane.add(PassLabel, null);
            jContentPane.add(getNameTextField(), null);
            jContentPane.add(getPasswordField(), null);
            jContentPane.add(getLoginButton(), null);
            jContentPane.add(getClearButton(), null);
           
        }
        return jContentPane;
    }
    /**
     * This method initializes NameTextField   
     *    
     * @return javax.swing.JTextField   
     */
    private JTextField getNameTextField() {
        if (NameTextField == null) {
            NameTextField = new JTextField();
            NameTextField.setBounds(new Rectangle(225, 120, 180, 30));
        }
        return NameTextField;
    }
    /**
     * This method initializes PasswordField   
     *    
     * @return javax.swing.JPasswordField   
     */
    private JPasswordField getPasswordField() {
        if (PasswordField == null) {
            PasswordField = new JPasswordField();
            PasswordField.setBounds(new Rectangle(225, 170, 180, 30));
        }
        return PasswordField;
    }
    /**
     * This method initializes LoginButton   
     *    
     * @return javax.swing.JButton   
     */
    private JButton getLoginButton() {
        if (LoginButton == null) {
            LoginButton = new JButton();
            LoginButton.setBounds(new Rectangle(140, 230, 80, 25));
            LoginButton.setText("Login");
            LoginButton.addActionListener(new ActionListener () {
                public void actionPerformed(ActionEvent e) {
                   
                   
                    if(NameTextField.getText().compareTo("admin")==0)
                    {
//                        System.out.println("clicked");
                        if(String.valueOf(PasswordField.getPassword()).equals("mds"))
                        {
                       
                            MainFrame m = new MainFrame();
//                            m.setBounds(0,0,900,600);
                            m.setVisible(true);
                            closeWindow();
                        }
                        else
                            showMessageDialog("Invalid Username or Password");
                    }
               
                }
            });
        }
        return LoginButton;
    }
   
    private void showMessageDialog(String message)
    {
        JOptionPane.showMessageDialog(this, message);
    }
   
    private void closeWindow()
    {
        setVisible(false);
        dispose();
    }
   

    /**
     * This method initializes ClearButton   
     *    
     * @return javax.swing.JButton   
     */
    private JButton getClearButton() {
        if (ClearButton == null) {
            ClearButton = new JButton();
            ClearButton.setBounds(new Rectangle(240, 230, 80, 25));
            ClearButton.setText("Clear");
            ClearButton.addActionListener(new ActionListener () {
                public void actionPerformed(ActionEvent e) {
                    NameTextField.setText("");
                    PasswordField.setText("");
                }
            });
        }
       
        return ClearButton;
    }
   
    public static void main(String[] args) {
       
        LoginFrame l = new LoginFrame();
        l.setVisible(true);
    }}

-------------------

AePlayWave.java


package com.mds.serv;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
public class AePlayWave extends Thread {
    private String filename;
    private Position curPosition;
    private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb
    enum Position {
        LEFT, RIGHT, NORMAL
    };

    public AePlayWave(String wavfile) {
        filename = wavfile;
        curPosition = Position.NORMAL;
    }

    public AePlayWave(String wavfile, Position p) {
        filename = wavfile;
        curPosition = p;
    }

    @Override
    public void run() {

        File soundFile = new File(filename);
        if (!soundFile.exists()) {
            System.err.println("Wave file not found File not found exception in java: " + filename);
            return;
        }

        AudioInputStream audioInputStream = null;
        try {
            audioInputStream = AudioSystem.getAudioInputStream(soundFile);
        } catch (UnsupportedAudioFileException e1) {
            e1.printStackTrace();
            return;
        } catch (IOException e1) {
            e1.printStackTrace();
            return;
        }

        AudioFormat format = audioInputStream.getFormat();
        SourceDataLine auline = null;
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

        try {
            auline = (SourceDataLine) AudioSystem.getLine(info);
            auline.open(format);
        } catch (LineUnavailableException e) {
            e.printStackTrace();
            return;
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        if (auline.isControlSupported(FloatControl.Type.PAN)) {
            FloatControl pan = (FloatControl) auline
                    .getControl(FloatControl.Type.PAN);
            if (curPosition == Position.RIGHT)
                pan.setValue(1.0f);
            else if (curPosition == Position.LEFT)
                pan.setValue(-1.0f);
        }

        auline.start();
        int nBytesRead = 0;
        byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];

        try {
            while (nBytesRead != -1) {
                nBytesRead = audioInputStream.read(abData, 0, abData.length);
                if (nBytesRead >= 0)
                    auline.write(abData, 0, nBytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        } finally {
            auline.drain();
            auline.close();
        }

    }
   
    public static void main(String[] args) {
       
        new AePlayWave("alarm.wav").start();
    }
}

------------------------------------
Alarmsound.java


package com.mds.serv;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class AlarmSound implements Runnable {
   
    int hz=200;
    int msecs=200;
    int volume=20;
    boolean addHarmonic=true; 
   
    /** Generates a tone.
      @param hz Base frequency (neglecting harmonic) of the tone in cycles per second
      @param msecs The number of milliseconds to play the tone.
      @param volume Volume, form 0 (mute) to 100 (max).
      @param addHarmonic Whether to add an harmonic, one octave up. */
      public void generateTone()
        throws LineUnavailableException {
   
        float frequency = 44100;
        byte[] buf;
        AudioFormat af;
        if (addHarmonic) {
          buf = new byte[2];
          af = new AudioFormat(frequency,8,2,true,false);
        } else {
          buf = new byte[1];
          af = new AudioFormat(frequency,8,1,true,false);
        }
        SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
        sdl = AudioSystem.getSourceDataLine(af);
        sdl.open(af);
        sdl.start();
        for(int i=0; i<msecs*frequency/1000; i++){
          double angle = i/(frequency/hz)*2.0*Math.PI;
          buf[0]=(byte)(Math.sin(angle)*volume);
   
          if(addHarmonic) {
            double angle2 = (i)/(frequency/hz)*2.0*Math.PI;
            buf[1]=(byte)(Math.sin(2*angle2)*volume*0.6);
            sdl.write(buf,0,2);
          } else {
            sdl.write(buf,0,1);
          }
        }
        sdl.drain();
        sdl.stop();
        sdl.close();
      }
     
     
     
      public static void main(String[] args) {
       
         AlarmSound as = new AlarmSound();
         try {
            as.generateTone();
        } catch (LineUnavailableException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
    }



    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            generateTone();
        } catch (LineUnavailableException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

--------------------------------
ImageCompare.java


package com.mds.serv;

import javax.swing.*;
import java.io.*;
//import java.util.*;
import java.awt.*;
import java.awt.image.*;
import com.sun.image.codec.jpeg.*;

 public class ImageCompare{

    protected BufferedImage img1 = null;
    protected BufferedImage img2 = null;
    protected BufferedImage imgc = null;
    protected int comparex = 0;
    protected int comparey = 0;
    protected int factorA = 0;
    protected int factorD = 10;
    protected File saveImgDir = null;
    protected boolean match = false;
    protected static int i=0;
    protected int debugMode = 0; // 1: textual indication of change, 2: difference of factors

    /* create a runable demo thing. */
    public static void main(String[] args) {
        // Create a compare object specifying the 2 images for comparison.
        ImageCompare ic = new ImageCompare("c:\\test1.jpg", "c:\\test2.jpg");
        // Set the comparison parameters.
        //   (num vertical regions, num horizontal regions, sensitivity, stabilizer)
        ic.setParameters(8, 6, 5, 10);
        // Display some indication of the differences in the image.
        ic.setDebugMode(2);
        // Compare.
        ic.compare();
        // Display if these images are considered a match according to our parameters.
        System.out.println("Match: " + ic.match());
        // If its not a match then write a file to show changed regions.
        if (!ic.match()) {
            saveJPG(ic.getChangeIndicator(), "c:\\changes.jpg");
        }
    }
   

    // constructor 1. use filenames
    public ImageCompare(String file1, String file2) {
        this(loadJPG(file1), loadJPG(file2));
    }

    // constructor 2. use awt images.
    public ImageCompare(Image img1, Image img2) {
        this(imageToBufferedImage(img1), imageToBufferedImage(img2));
        autoSetParameters();
    }

    // constructor 3. use buffered images. all roads lead to the same place. this place.
    public ImageCompare(BufferedImage img1, BufferedImage img2) {
        this.img1 = img1;
        this.img2 = img2;
        autoSetParameters();
    }

    // like this to perhaps be upgraded to something more heuristic in the future.
    protected void autoSetParameters() {
        comparex = 10;
        comparey = 10;
        factorA = 10;
        factorD = 10;
    }
   
    // set the parameters for use during change detection.
    public void setParameters(int x, int y, int factorA, int factorD) {
        this.comparex = x;
        this.comparey = y;
        this.factorA = factorA;
        this.factorD = factorD;
    }
   
    // want to see some stuff in the console as the comparison is happening?
    public void setDebugMode(int m) {
        this.debugMode = m;
    }
   
    // compare the two images in this object.
    public boolean compare() {
        // setup change display image
        imgc = imageToBufferedImage(img2);
        Graphics2D gc = imgc.createGraphics();
        gc.setColor(Color.RED);
        // convert to gray images.
        img1 = imageToBufferedImage(GrayFilter.createDisabledImage(img1));
        img2 = imageToBufferedImage(GrayFilter.createDisabledImage(img2));
        // how big are each section
        int blocksx = (img1.getWidth() / comparex);
        int blocksy = (img1.getHeight() / comparey);
        // set to a match by default, if a change is found then flag non-match
        this.match = true;
        // loop through whole image and compare individual blocks of images
        for (int y = 0; y < comparey; y++) {
            if (debugMode > 0) System.out.print("|");
            for (int x = 0; x < comparex; x++) {
                int b1 = getAverageBrightness(img1.getSubimage(x*blocksx, y*blocksy, blocksx - 1, blocksy - 1));
                int b2 = getAverageBrightness(img2.getSubimage(x*blocksx, y*blocksy, blocksx - 1, blocksy - 1));
                int diff = Math.abs(b1 - b2);
                if (diff > factorA) { // the difference in a certain region has passed the threshold value of factorA
                    // draw an indicator on the change image to show where change was detected.
                    gc.drawRect(x*blocksx, y*blocksy, blocksx - 1, blocksy - 1);
                    this.match = false;
                }
                if (debugMode == 1) System.out.print((diff > factorA ? "X" : " "));
                if (debugMode == 2) System.out.print(diff + (x < comparex - 1 ? "," : ""));
            }
            if (debugMode > 0) System.out.println("|");
        }
        return this.match;
    }
   
    // return the image that indicates the regions where changes where detected.
    public BufferedImage getChangeIndicator() {
        return imgc;
    }
   
    // returns a value specifying some kind of average brightness in the image.
    protected int getAverageBrightness(BufferedImage img) {
        Raster r = img.getData();
        int total = 0;
        for (int y = 0; y < r.getHeight(); y++) {
            for (int x = 0; x < r.getWidth(); x++) {
                total += r.getSample(r.getMinX() + x, r.getMinY() + y, 0);
            }
        }
        return (total / ((r.getWidth()/factorD)*(r.getHeight()/factorD)));
    }
   

    // returns true if image pair is considered a match
    public boolean match() {
        return this.match;
    }

    // buffered images are just better.
    protected static BufferedImage imageToBufferedImage(Image img) {
        BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bi.createGraphics();
        g2.drawImage(img, null, null);
        return bi;
    }
   
    // write a buffered image to a jpeg file.
    protected static void saveJPG(Image img, String filename) {
        BufferedImage bi = imageToBufferedImage(img);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filename);
        } catch (java.io.FileNotFoundException io) {
            System.out.println("File Not Found");
        }
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
        param.setQuality(0.8f,false);
        encoder.setJPEGEncodeParam(param);
        try {
            encoder.encode(bi);
            out.close();
        } catch (java.io.IOException io) {
            System.out.println("IOException");
        }
    }
   
    // read a jpeg file into a buffered image
    protected static Image loadJPG(String filename) {
        FileInputStream in = null;
        try {
            in = new FileInputStream(filename);
        } catch (java.io.FileNotFoundException io) {
            System.out.println("File Not Found");
        }
        JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
        BufferedImage bi = null;
        try {
            bi = decoder.decodeAsBufferedImage();
            in.close();
        } catch (java.io.IOException io) {
            System.out.println("IOException");
        }
        return bi;
    }


//    @Override
//    public void run() {
//        // TODO Auto-generated method stub
//        saveImgDir = new File("D:\\Backups\\Saved");
//        if(!saveImgDir.exists())
//            saveImgDir.mkdirs();
//        this.compare();
//        if(!this.match)
//        {
//            saveJPG(this.img2, "D:\\Backups\\Saved\\img"+i+".jpg");
//            i++;
//        }
//    }
   
}

----------------------------
MDSMailer.java


package com.mds.serv;

import java.security.Security;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;


public class MDSMailer extends Thread {

    private String recipient="mdsmailer@gmail.com";
    private String from="mdsmailer@gmail.com";
//    private String subject="MDS PIC";
//    private String msg;
    private String fileAttachment = "C:\\test1.jpg";
//    public void send( String subject, String msg, String recipient) throws Exception
//    {
//        this.recipient=recipient;
//        this.msg=msg;
//        this.subject=subject;
//        start();
//    }
   
    public MDSMailer(String file)
    {
        this.fileAttachment = file;
    }
   
    @Override
    public void run(){
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        Properties props = new Properties();

        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.quitwait", "false");
       
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");

        Session session = Session.getInstance(props,
        new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("mdsmailer@gmail.com", "mdsproject");
                }
            });
       
        try {
            // Define message
            MimeMessage message =
              new MimeMessage(session);
            message.setFrom(
              new InternetAddress(from));
            message.addRecipient(
              Message.RecipientType.TO,
              new InternetAddress(recipient));
            message.setSubject(
              "MDS Picture Attachment");

            // create the message part
            MimeBodyPart messageBodyPart =
              new MimeBodyPart();

            //fill message
            messageBodyPart.setText("Hi");

            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            // Part two is attachment
            messageBodyPart = new MimeBodyPart();
            DataSource source =
              new FileDataSource(fileAttachment);
            messageBodyPart.setDataHandler(
              new DataHandler(source));
            messageBodyPart.setFileName(fileAttachment);
            multipart.addBodyPart(messageBodyPart);

            // Put parts in message
            message.setContent(multipart);

            // Send message
            Transport.send(message);
        } catch(Exception e){}
        finally{}
    }   
   
    public static void main(String[] args) {
       
        MDSMailer r = new MDSMailer("C:\\test1.jpg");
        Thread t = new Thread(r);
        r.start();
    }
}

----------------
Run.java

+Nidhin Sasankan 

package com.mds.serv;

import java.awt.Component;

import javax.media.Player;

public class Run {
   
    private SwingCapture sc = null;
    private Player p = null;
   
    public Run()
    {
        sc = new SwingCapture();
    }
   
    public void grabFrame()
    {
        p = sc.getPlayer();
//        sc.
    }
   
    public static void main(String[] args) {
       
        SwingCapture sc = new SwingCapture();
        Player p = sc.getPlayer();
        Component c = null;
        try {
            Thread.sleep(10000);
            c = p.getVisualComponent();
            sc.imageCapture();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
       
    }

}

----------------------
SwingCapture.java


package com.mds.serv;

import javax.swing.*;
//import javax.swing.event.*;
import java.io.*;

import javax.media.*;
import javax.media.format.*;
import javax.media.util.*;
import javax.media.control.*;
//import javax.media.protocol.*;
//import java.util.*;
import java.awt.*;
import java.awt.image.*;
import com.sun.image.codec.jpeg.*;

public class SwingCapture
{
    public static Player p = null;
    public CaptureDeviceInfo di = null;
    public MediaLocator ml = null;
    public JButton capture = null;
    public Buffer buf = null;
    public Image img = null;
    public VideoFormat vf = null;
    public BufferToImage btoi = null;
    public JPanel panel = null;

 
    public JPanel getPlayerPanel()
    {
        if(panel == null)
        {
            panel = new JPanel();
            panel.setBounds(10, 10, 400, 300);
            panel.setLayout(null);
            Component comp;
            p = getPlayer();
            if ((comp = p.getVisualComponent()) != null)
            {
//                comp.setBounds(120, 100, 400, 300);
                comp.setSize(400,300);
                panel.add(comp);
            }
           

        }
        return panel;
     }

    public Player getPlayer()
    {
        Player player = null;
        String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
        di = CaptureDeviceManager.getDevice(str2);
        ml = di.getLocator();
        try {
            player = Manager.createRealizedPlayer(ml);
            player.start();
        } catch (NoPlayerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (CannotRealizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return player;

    }
 
 
   
    public static void playerclose()
    {
        p.close();
        p.deallocate();
    }
   
    public Image imageCapture()
    {
        // Grab a frame
        FrameGrabbingControl fgc = (FrameGrabbingControl)
        p.getControl("javax.media.control.FrameGrabbingControl");
        buf = fgc.grabFrame();
 
        // Convert it to an image
        btoi = new BufferToImage((VideoFormat)buf.getFormat());
        img = btoi.createImage(buf);
 
        return img;
       
    }
 

    public static void saveJPG(Image img, String s)
    {
        BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bi.createGraphics();
        g2.drawImage(img, null, null);
       
        FileOutputStream out = null;
        try
        {
            out = new FileOutputStream(s);
        }
        catch (java.io.FileNotFoundException io)
        {
            System.out.println("File Not Found");
        }
   
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
        param.setQuality(0.5f,false);
        encoder.setJPEGEncodeParam(param);
   
        try
        {
            encoder.encode(bi);
            out.close();
        }
        catch (java.io.IOException io)
        {
            System.out.println("IOException");
        }
    }
 
}


----------------------
AttachedMail.java


package com.mds.tryout;

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class AttachedMail {
  public static void main (String args[])
      throws Exception {
    String host = args[0];
    String from = args[1];
    String to = args[2];
    String fileAttachment = args[3];

    // Get system properties
    Properties props = System.getProperties();

    // Setup mail server
    props.put("mail.smtp.host", host);

    // Get session
    Session session =
      Session.getInstance(props, null);

    // Define message
    MimeMessage message =
      new MimeMessage(session);
    message.setFrom(
      new InternetAddress(from));
    message.addRecipient(
      Message.RecipientType.TO,
      new InternetAddress(to));
    message.setSubject(
      "Hello JavaMail Attachment");

    // create the message part
    MimeBodyPart messageBodyPart =
      new MimeBodyPart();

    //fill message
    messageBodyPart.setText("Hi");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    // Part two is attachment
    messageBodyPart = new MimeBodyPart();
    DataSource source =
      new FileDataSource(fileAttachment);
    messageBodyPart.setDataHandler(
      new DataHandler(source));
    messageBodyPart.setFileName(fileAttachment);
    multipart.addBodyPart(messageBodyPart);

    // Put parts in message
    message.setContent(multipart);

    // Send the message
    Transport.send( message );
  }
}

-----------------------
Camagain.java


package com.mds.tryout;

import javax.swing.*;
import java.io.*;
import javax.media.*;
import javax.media.format.*;
import javax.media.util.*;
import javax.media.control.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import com.sun.image.codec.jpeg.*;

public class Camagain extends Panel implements ActionListener
{
    public static Player player;
    public CaptureDeviceInfo DI;
    public MediaLocator ML;
    public JButton CAPTURE;
    public Buffer BUF;
    public Image img;
    public VideoFormat VF;
    public BufferToImage BtoI;
    public ImagePanel imgpanel;

    public Camagain()
    {
        setLayout(new BorderLayout());
        setSize(320,550);

        imgpanel = new ImagePanel();
        CAPTURE = new JButton("Capture");
        CAPTURE.addActionListener(this);

        String str1 = "vfw:Logitech USB Video Camera:0";
        String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
        DI = CaptureDeviceManager.getDevice(str2);
        ML = new MediaLocator("vfw://0");

        try
        {
            player = Manager.createRealizedPlayer(ML);
            player.start();
            Component comp;
            if( (comp = player.getVisualComponent()) != null )
            {
                add(comp,BorderLayout.NORTH);
            }
            add(CAPTURE,BorderLayout.CENTER);
            add(imgpanel,BorderLayout.SOUTH);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String[] args)
    {
        Frame f = new Frame("SwingCapture");
        SwingCapture cf = new SwingCapture();

        f.addWindowListener(new WindowAdapter()
        {
            @Override
            public void windowClosing(WindowEvent e)
            {
                playerclose();
                System.exit(0);
            }
        });

        f.add("Center",cf);
        f.pack();
        f.setSize(new Dimension(320,550));
        f.setVisible(true);
    }

    public static void playerclose()
    {
        player.close();
        player.deallocate();
    }

    public void actionPerformed(ActionEvent e)
    {
        JComponent c = (JComponent) e.getSource();

        if(c == CAPTURE)
        {
            // Grab a frame
            FrameGrabbingControl fgc = (FrameGrabbingControl)
            player.getControl("javax.media.control.FrameGrabbingControl");
            BUF = fgc.grabFrame();

            // Convert it to an image
            BtoI = new BufferToImage((VideoFormat)BUF.getFormat());
            img = BtoI.createImage(BUF);

            // show the image
            imgpanel.setImage(img);

            // save image
            saveJPG(img,"c:\\test.jpg");
        }
    }

    class ImagePanel extends Panel
    {
        public Image myimg = null;

        public ImagePanel()
        {
            setLayout(null);
            setSize(320,240);
        }

        public void setImage(Image img)
        {
            this.myimg = img;
            //repaint();
        }

        @Override
        public void paint(Graphics g)
        {
            g.drawImage(myimg, 0, 0, this);
        }

    }

    public static void saveJPG(Image img, String s)
    {
        BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bi.createGraphics();
        g2.drawImage(img, null, null);
        FileOutputStream out = null;
        try
        {
            out = new FileOutputStream(s);
        }
        catch (java.io.FileNotFoundException io)
        {
            System.out.println("File Not Found");
        }

        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
        param.setQuality(0.5f,false);
        encoder.setJPEGEncodeParam(param);

        try
        {
            encoder.encode(bi);
            out.close();
        }
        catch (java.io.IOException io)
        {
            System.out.println("IOException");
        }
    }
}


------------------------------
MainFrame.java


package com.mds.tryout;

import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import com.sun.image.codec.jpeg.*;

 public class ImageCompare {

    protected BufferedImage img1 = null;
    protected BufferedImage img2 = null;
    protected BufferedImage imgc = null;
    protected int comparex = 0;
    protected int comparey = 0;
    protected int factorA = 0;
    protected int factorD = 10;
    protected boolean match = false;
    protected int debugMode = 0; // 1: textual indication of change, 2: difference of factors

    /* create a runable demo thing. */
    public static void main(String[] args) {
        // Create a compare object specifying the 2 images for comparison.
        ImageCompare ic = new ImageCompare("c:\\test1.jpg", "c:\\test2.jpg");
        // Set the comparison parameters.
        //   (num vertical regions, num horizontal regions, sensitivity, stabilizer)
        ic.setParameters(8, 6, 5, 10);
        // Display some indication of the differences in the image.
        ic.setDebugMode(2);
        // Compare.
        ic.compare();
        // Display if these images are considered a match according to our parameters.
        System.out.println("Match: " + ic.match());
        // If its not a match then write a file to show changed regions.
        if (!ic.match()) {
            saveJPG(ic.getChangeIndicator(), "c:\\changes.jpg");
        }
    }
   
    // constructor 1. use filenames
    public ImageCompare(String file1, String file2) {
        this(loadJPG(file1), loadJPG(file2));
    }

    // constructor 2. use awt images.
    public ImageCompare(Image img1, Image img2) {
        this(imageToBufferedImage(img1), imageToBufferedImage(img2));
    }

    // constructor 3. use buffered images. all roads lead to the same place. this place.
    public ImageCompare(BufferedImage img1, BufferedImage img2) {
        this.img1 = img1;
        this.img2 = img2;
        autoSetParameters();
    }

    // like this to perhaps be upgraded to something more heuristic in the future.
    protected void autoSetParameters() {
        comparex = 10;
        comparey = 10;
        factorA = 10;
        factorD = 10;
    }
   
    // set the parameters for use during change detection.
    public void setParameters(int x, int y, int factorA, int factorD) {
        this.comparex = x;
        this.comparey = y;
        this.factorA = factorA;
        this.factorD = factorD;
    }
   
    // want to see some stuff in the console as the comparison is happening?
    public void setDebugMode(int m) {
        this.debugMode = m;
    }
   
    // compare the two images in this object.
    public void compare() {
        // setup change display image
        imgc = imageToBufferedImage(img2);
        Graphics2D gc = imgc.createGraphics();
        gc.setColor(Color.RED);
        // convert to gray images.
        img1 = imageToBufferedImage(GrayFilter.createDisabledImage(img1));
        img2 = imageToBufferedImage(GrayFilter.createDisabledImage(img2));
        // how big are each section
        int blocksx = (img1.getWidth() / comparex);
        int blocksy = (img1.getHeight() / comparey);
        // set to a match by default, if a change is found then flag non-match
        this.match = true;
        // loop through whole image and compare individual blocks of images
        for (int y = 0; y < comparey; y++) {
            if (debugMode > 0) System.out.print("|");
            for (int x = 0; x < comparex; x++) {
                int b1 = getAverageBrightness(img1.getSubimage(x*blocksx, y*blocksy, blocksx - 1, blocksy - 1));
                int b2 = getAverageBrightness(img2.getSubimage(x*blocksx, y*blocksy, blocksx - 1, blocksy - 1));
                int diff = Math.abs(b1 - b2);
                if (diff > factorA) { // the difference in a certain region has passed the threshold value of factorA
                    // draw an indicator on the change image to show where change was detected.
                    gc.drawRect(x*blocksx, y*blocksy, blocksx - 1, blocksy - 1);
                    this.match = false;
                }
                if (debugMode == 1) System.out.print((diff > factorA ? "X" : " "));
                if (debugMode == 2) System.out.print(diff + (x < comparex - 1 ? "," : ""));
            }
            if (debugMode > 0) System.out.println("|");
        }
    }
   
    // return the image that indicates the regions where changes where detected.
    public BufferedImage getChangeIndicator() {
        return imgc;
    }
   
    // returns a value specifying some kind of average brightness in the image.
    protected int getAverageBrightness(BufferedImage img) {
        Raster r = img.getData();
        int total = 0;
        for (int y = 0; y < r.getHeight(); y++) {
            for (int x = 0; x < r.getWidth(); x++) {
                total += r.getSample(r.getMinX() + x, r.getMinY() + y, 0);
            }
        }
        return (total / ((r.getWidth()/factorD)*(r.getHeight()/factorD)));
    }
   

    // returns true if image pair is considered a match
    public boolean match() {
        return this.match;
    }

    // buffered images are just better.
    protected static BufferedImage imageToBufferedImage(Image img) {
        BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bi.createGraphics();
        g2.drawImage(img, null, null);
        return bi;
    }
   
    // write a buffered image to a jpeg file.
    protected static void saveJPG(Image img, String filename) {
        BufferedImage bi = imageToBufferedImage(img);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filename);
        } catch (java.io.FileNotFoundException io) {
            System.out.println("File Not Found");
        }
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
        param.setQuality(0.8f,false);
        encoder.setJPEGEncodeParam(param);
        try {
            encoder.encode(bi);
            out.close();
        } catch (java.io.IOException io) {
            System.out.println("IOException");
        }
    }
   
    // read a jpeg file into a buffered image
    protected static Image loadJPG(String filename) {
        FileInputStream in = null;
        try {
            in = new FileInputStream(filename);
        } catch (java.io.FileNotFoundException io) {
            System.out.println("File Not Found");
        }
        JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
        BufferedImage bi = null;
        try {
            bi = decoder.decodeAsBufferedImage();
            in.close();
        } catch (java.io.IOException io) {
            System.out.println("IOException");
        }
        return bi;
    }
   
}

-------------
SwingCapture.java


package com.mds.tryout;

import javax.swing.*;
import java.io.*;
import javax.media.*;
import javax.media.format.*;
import javax.media.util.*;
import javax.media.control.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import com.sun.image.codec.jpeg.*;

public class SwingCapture extends Panel implements ActionListener
{
    public static Player player = null;
    public CaptureDeviceInfo di = null;
    public MediaLocator ml = null;
    public JButton capture = null;
    public Buffer buf = null;
    public Image img = null;
    public VideoFormat vf = null;
    public BufferToImage btoi = null;
    public ImagePanel imgpanel = null;
 
    public SwingCapture()
    {
        setLayout(new BorderLayout());
        setSize(320,550);
   
        imgpanel = new ImagePanel();
        capture = new JButton("Capture");
        capture.addActionListener(this);
   
        String str1 = "vfw:Logitech USB Video Camera:0";
        String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
        di = CaptureDeviceManager.getDevice(str2);
        ml = di.getLocator();
   
        try
        {
            player = Manager.createRealizedPlayer(ml);
            player.start();
            Component comp;
     
            if ((comp = player.getVisualComponent()) != null)
            {
                add(comp,BorderLayout.NORTH);
            }
            add(capture,BorderLayout.CENTER);
            add(imgpanel,BorderLayout.SOUTH);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }


 
    public static void main(String[] args)
    {
        Frame f = new Frame("SwingCapture");
        SwingCapture cf = new SwingCapture();
   
        f.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                playerclose();
                System.exit(0);}});
   
        f.add("Center",cf);
        f.pack();
        f.setSize(new Dimension(320,550));
        f.setVisible(true);
    }
 
 
    public static void playerclose()
    {
        player.close();
        player.deallocate();
    }
 

    public void actionPerformed(ActionEvent e)
    {
        JComponent c = (JComponent) e.getSource();
   
        if (c == capture)
        {
            // Grab a frame
            FrameGrabbingControl fgc = (FrameGrabbingControl)
            player.getControl("javax.media.control.FrameGrabbingControl");
            buf = fgc.grabFrame();
     
            // Convert it to an image
            btoi = new BufferToImage((VideoFormat)buf.getFormat());
            img = btoi.createImage(buf);
     
            // show the image
            imgpanel.setImage(img);
     
            // save image
            saveJPG(img,"c:\\test.jpg");
        }
    }
 
    class ImagePanel extends Panel
    {
        public Image myimg = null;
   
        public ImagePanel()
        {
            setLayout(null);
            setSize(320,240);
        }
   
        public void setImage(Image img)
        {
            this.myimg = img;
            repaint();
        }
   
        @Override
        public void paint(Graphics g)
        {
            if (myimg != null)
            {
                g.drawImage(myimg, 0, 0, this);
            }
        }
    }
 

    public static void saveJPG(Image img, String s)
    {
        BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bi.createGraphics();
        g2.drawImage(img, null, null);
       
        FileOutputStream out = null;
        try
        {
            out = new FileOutputStream(s);
        }
        catch (java.io.FileNotFoundException io)
        {
            System.out.println("File Not Found");
        }
   
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
        param.setQuality(0.5f,false);
        encoder.setJPEGEncodeParam(param);
   
        try
        {
            encoder.encode(bi);
            out.close();
        }
        catch (java.io.IOException io)
        {
            System.out.println("IOException");
        }
    }
 
}

------------------
SwingCapture.java


package com.mds.tryout;

import javax.swing.*;
import java.io.*;
import javax.media.*;
import javax.media.format.*;
import javax.media.util.*;
import javax.media.control.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import com.sun.image.codec.jpeg.*;

public class SwingCapture extends Panel implements ActionListener
{
    public static Player player = null;
    public CaptureDeviceInfo di = null;
    public MediaLocator ml = null;
    public JButton capture = null;
    public Buffer buf = null;
    public Image img = null;
    public VideoFormat vf = null;
    public BufferToImage btoi = null;
    public ImagePanel imgpanel = null;
 
    public SwingCapture()
    {
        setLayout(new BorderLayout());
        setSize(320,550);
   
        imgpanel = new ImagePanel();
        capture = new JButton("Capture");
        capture.addActionListener(this);
   
        String str1 = "vfw:Logitech USB Video Camera:0";
        String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
        di = CaptureDeviceManager.getDevice(str2);
        ml = di.getLocator();
   
        try
        {
            player = Manager.createRealizedPlayer(ml);
            player.start();
            Component comp;
     
            if ((comp = player.getVisualComponent()) != null)
            {
                add(comp,BorderLayout.NORTH);
            }
            add(capture,BorderLayout.CENTER);
            add(imgpanel,BorderLayout.SOUTH);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }


 
    public static void main(String[] args)
    {
        Frame f = new Frame("SwingCapture");
        SwingCapture cf = new SwingCapture();
   
        f.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                playerclose();
                System.exit(0);}});
   
        f.add("Center",cf);
        f.pack();
        f.setSize(new Dimension(320,550));
        f.setVisible(true);
    }
 
 
    public static void playerclose()
    {
        player.close();
        player.deallocate();
    }
 

    public void actionPerformed(ActionEvent e)
    {
        JComponent c = (JComponent) e.getSource();
   
        if (c == capture)
        {
            // Grab a frame
            FrameGrabbingControl fgc = (FrameGrabbingControl)
            player.getControl("javax.media.control.FrameGrabbingControl");
            buf = fgc.grabFrame();
     
            // Convert it to an image
            btoi = new BufferToImage((VideoFormat)buf.getFormat());
            img = btoi.createImage(buf);
     
            // show the image
            imgpanel.setImage(img);
     
            // save image
            saveJPG(img,"c:\\test.jpg");
        }
    }
 
    class ImagePanel extends Panel
    {
        public Image myimg = null;
   
        public ImagePanel()
        {
            setLayout(null);
            setSize(320,240);
        }
   
        public void setImage(Image img)
        {
            this.myimg = img;
            repaint();
        }
   
        @Override
        public void paint(Graphics g)
        {
            if (myimg != null)
            {
                g.drawImage(myimg, 0, 0, this);
            }
        }
    }
 

    public static void saveJPG(Image img, String s)
    {
        BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bi.createGraphics();
        g2.drawImage(img, null, null);
       
        FileOutputStream out = null;
        try
        {
            out = new FileOutputStream(s);
        }
        catch (java.io.FileNotFoundException io)
        {
            System.out.println("File Not Found");
        }
   
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
        param.setQuality(0.5f,false);
        encoder.setJPEGEncodeParam(param);
   
        try
        {
            encoder.encode(bi);
            out.close();
        }
        catch (java.io.IOException io)
        {
            System.out.println("IOException");
        }
    }
 
}

-----------------------
MainFrame.java


package com.mds.tryout;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.LineUnavailableException;

import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.Image;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JSlider;
import javax.swing.JCheckBox;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import javax.swing.border.TitledBorder;

import java.net.URL;

/**
Audio tone generator, using the Java sampled sound API.
@author vipin
@version 2014
*/
public class Tone extends JFrame {

  static AudioFormat af;
  static SourceDataLine sdl;

  public Tone() {
    super("To play sound file in java");
    // Use current OS look and feel.
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            SwingUtilities.updateComponentTreeUI(this);
        } catch (Exception e) {
            System.err.println("Internal Look And Feel Setting Error.");
            System.err.println(e);
        }

    JPanel pMain=new JPanel(new BorderLayout());

    final JSlider sTone=new JSlider(SwingConstants.VERTICAL,200,2000,441);
    sTone.setPaintLabels(true);
    sTone.setPaintTicks(true);
    sTone.setMajorTickSpacing(200);
    sTone.setMinorTickSpacing(100);
    sTone.setToolTipText(
      "Tone (in Hertz or cycles per second - middle C is 441 Hz)");
    sTone.setBorder(new TitledBorder("Frequency"));
    pMain.add(sTone,BorderLayout.CENTER);

    final JSlider sDuration=new JSlider(SwingConstants.VERTICAL,0,2000,1000);
    sDuration.setPaintLabels(true);
    sDuration.setPaintTicks(true);
    sDuration.setMajorTickSpacing(200);
    sDuration.setMinorTickSpacing(100);
    sDuration.setToolTipText("Duration in milliseconds");
    sDuration.setBorder(new TitledBorder("Length"));
    pMain.add(sDuration,BorderLayout.EAST);

    final JSlider sVolume=new JSlider(SwingConstants.VERTICAL,0,100,20);
    sVolume.setPaintLabels(true);
    sVolume.setPaintTicks(true);
    sVolume.setSnapToTicks(false);
    sVolume.setMajorTickSpacing(20);
    sVolume.setMinorTickSpacing(10);
    sVolume.setToolTipText("Volume 0 - none, 100 - full");
    sVolume.setBorder(new TitledBorder("Volume"));
    pMain.add(sVolume,BorderLayout.WEST);

    final JCheckBox cbHarmonic  = new JCheckBox( "Add Harmonic", true );
    cbHarmonic.setToolTipText("..else pure sine tone");

    JButton bGenerate = new JButton("Generate Tone");
    bGenerate.addActionListener( new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
          try{
            generateTone(sTone.getValue(),
              sDuration.getValue(),
              (int)(sVolume.getValue()*1.28),
              cbHarmonic.isSelected());
          }catch(LineUnavailableException lue){
            System.out.println(lue);
          }
        }
      } );

    JPanel pNorth = new JPanel(new BorderLayout());
    pNorth.add(bGenerate,BorderLayout.WEST);

    pNorth.add( cbHarmonic, BorderLayout.EAST );

    pMain.add(pNorth, BorderLayout.NORTH);
    pMain.setBorder( new javax.swing.border.EmptyBorder(5,3,5,3) );

    getContentPane().add(pMain);
    pack();
    setLocation(0,20);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);

    String address = "/image/tone32x32.png";
    URL url = getClass().getResource(address);

    if (url!=null) {
      Image icon = Toolkit.getDefaultToolkit().getImage(url);
      setIconImage(icon);
    }
  }

  /** Generates a tone.
  @param hz Base frequency (neglecting harmonic) of the tone in cycles per second
  @param msecs The number of milliseconds to play the tone.
  @param volume Volume, form 0 (mute) to 100 (max).
  @param addHarmonic Whether to add an harmonic, one octave up. */
  public static void generateTone(int hz,int msecs, int volume, boolean addHarmonic)
    throws LineUnavailableException {

    float frequency = 44100;
    byte[] buf;
    AudioFormat af;
    if (addHarmonic) {
      buf = new byte[2];
      af = new AudioFormat(frequency,8,2,true,false);
    } else {
      buf = new byte[1];
      af = new AudioFormat(frequency,8,1,true,false);
    }
    SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
    sdl = AudioSystem.getSourceDataLine(af);
    sdl.open(af);
    sdl.start();
    for(int i=0; i<msecs*frequency/1000; i++){
      double angle = i/(frequency/hz)*2.0*Math.PI;
      buf[0]=(byte)(Math.sin(angle)*volume);

      if(addHarmonic) {
        double angle2 = (i)/(frequency/hz)*2.0*Math.PI;
        buf[1]=(byte)(Math.sin(2*angle2)*volume*0.6);
        sdl.write(buf,0,2);
      } else {
        sdl.write(buf,0,1);
      }
    }
    sdl.drain();
    sdl.stop();
    sdl.close();
  }

  public static void main(String[] args){
    Runnable r = new Runnable() {
      public void run() {
        Tone t = new Tone();
        t.setVisible(true);
      }
    };
    SwingUtilities.invokeLater(r);
  }
}

----------------
AePlayWave.java


package com.mds.tryout;

import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

public class AePlayWave implements Runnable {

    private String filename;

    private Position curPosition;

    private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb

    enum Position {
        LEFT, RIGHT, NORMAL
    };

    public AePlayWave(String wavfile) {
        filename = wavfile;
        curPosition = Position.NORMAL;
    }

    public AePlayWave(String wavfile, Position p) {
        filename = wavfile;
        curPosition = p;
    }

    public void run() {

        File soundFile = new File(filename);
        if (!soundFile.exists()) {
            System.err.println("Wave file not found: " + filename);
            return;
        }

        AudioInputStream audioInputStream = null;
        try {
            audioInputStream = AudioSystem.getAudioInputStream(soundFile);
        } catch (UnsupportedAudioFileException e1) {
            e1.printStackTrace();
            return;
        } catch (IOException e1) {
            e1.printStackTrace();
            return;
        }

        AudioFormat format = audioInputStream.getFormat();
        SourceDataLine auline = null;
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

        try {
            auline = (SourceDataLine) AudioSystem.getLine(info);
            auline.open(format);
        } catch (LineUnavailableException e) {
            e.printStackTrace();
            return;
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        if (auline.isControlSupported(FloatControl.Type.PAN)) {
            FloatControl pan = (FloatControl) auline
                    .getControl(FloatControl.Type.PAN);
            if (curPosition == Position.RIGHT)
                pan.setValue(1.0f);
            else if (curPosition == Position.LEFT)
                pan.setValue(-1.0f);
        }

        auline.start();
        int nBytesRead = 0;
        byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];

        try {
            while (nBytesRead != -1) {
                nBytesRead = audioInputStream.read(abData, 0, abData.length);
                if (nBytesRead >= 0)
                    auline.write(abData, 0, nBytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        } finally {
            auline.drain();
            auline.close();
        }

    }
   
    public static void main(String[] args) {
        AePlayWave a = new AePlayWave("javasecurityalert.wav");
        new Thread(a).start();
    }
}




jar files : mds.jar, mail.jar and jmf.jar  has to be downloaded. for playing sound a wave file : Here i used javasecurityalert.wav

Please provide your feedback through comment and rate the post

http://javabelazy.blogspot.in/

Facebook comments