19
Membuat Pemutar MP3 dengan JMF March 30, 2008 Sudah lama tidak update blog… Sekarang kita mau mencoba pemutar MP3 yang sangat sederhana menggunakan Java. Java menyediakan beberapa API (Application Programming Interface) untuk memudahkan pengembang Java membuat aplikasi multimedia. Salah satunya adalah Java Media Framework (JMF) API. http://java.sun.com/products/java-media/jmf/ . Sebelum kita mulai pada pembuatan aplikasi tersebut, berikut adalah prerequisite yang diperlukan. 1. Tentu saja JDK.. 2. Install JMF API yang dapat didownload pada link di atas Jika prerequisite sudah dipenuhi, mari kita mulai pembuatan aplikasinya. Sebelum kita membuat aplikasinya, kita perlu membuat tempat menampungnya. Jadi kita membuat Frame dulu. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class HelloJMF extends JFrame { public HelloJMF() { super(“Demo JMF”); JLabel empty = new JLabel(); /*sementara kita gunakan JLabel untuk memperagakan penempatan sebuah control pada frame*/ this.getContentPane().add(empty, BorderLayout.CENTER); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); this.pack(); this.setSize(new Dimension(300, 100)); this.setVisible(true); }

JMF-PROJEK

Embed Size (px)

Citation preview

Page 1: JMF-PROJEK

Membuat Pemutar MP3 dengan JMFMarch 30, 2008

Sudah lama tidak update blog…

Sekarang kita mau mencoba pemutar MP3 yang sangat sederhana menggunakan Java.

Java menyediakan beberapa API (Application Programming Interface) untuk memudahkan pengembang Java membuat aplikasi multimedia. Salah satunya adalah Java Media Framework (JMF) API. http://java.sun.com/products/java-media/jmf/.Sebelum kita mulai pada pembuatan aplikasi tersebut, berikut adalah prerequisite yang diperlukan.1. Tentu saja JDK..2. Install JMF API yang dapat didownload pada link di atas

Jika prerequisite sudah dipenuhi, mari kita mulai pembuatan aplikasinya.

Sebelum kita membuat aplikasinya, kita perlu membuat tempat menampungnya. Jadi kita membuat Frame dulu.

import javax.swing.*;import java.awt.*;import java.awt.event.*;

public class HelloJMF extends JFrame {public HelloJMF() {super(“Demo JMF”);JLabel empty = new JLabel(); /*sementara kita gunakan JLabel untuk memperagakan penempatan sebuah control pada frame*/this.getContentPane().add(empty, BorderLayout.CENTER);this.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent we) {System.exit(0);}});this.pack();this.setSize(new Dimension(300, 100));this.setVisible(true);}public static void main(String[] args) {HelloJMF helloJMF = new HelloJMF();}}

Page 2: JMF-PROJEK

Setelah kode dieksekusi, maka akan muncul frame seperti berikut:

Sekarang kita gunakan frame untuk menampung pemutar mp3 kita.pertama, tambahkan beberapa statement import

import javax.media.*;import java.net.*;

kemudian buat method play() dan stop()void play() {try {URL url = new URL(“file”,null,”C:\\Coldplay-Fix You.mp3″);myPlayer = Manager.createRealizedPlayer(url);}catch (Exception e) {System.out.println(“Unable to create the audioPlayer :” + e);}}void stop() {myPlayer.stop();myPlayer.close();}

kemudian edit contructor kita menjadi:

public HelloJMF() {super(“Demo JMF”);play();Component control = myPlayer.getControlPanelComponent();this.getContentPane().add(control, BorderLayout.CENTER);this.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent we) {stop();System.exit(0);}});this.pack();this.setSize(new Dimension(300, 100));this.setVisible(true);}

sehingga pada akhirnya kode kita akan berbentuk sebagai berikut:

import javax.swing.*;import java.awt.*;

Page 3: JMF-PROJEK

import java.awt.event.*;import javax.media.*;import java.net.*;

public class HelloJMF extends JFrame {static Player myPlayer = null;public HelloJMF() {super(“Demo JMF”);play();Component control = myPlayer.getControlPanelComponent();this.getContentPane().add(control, BorderLayout.CENTER);this.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent we) {stop();System.exit(0);}});this.pack();this.setSize(new Dimension(300, 100));this.setVisible(true);}public static void main(String[] args) {HelloJMF helloJMF = new HelloJMF();helloJMF.play();}void play() {try {URL url = new URL(“file”,null,”C:\\Coldplay-Fix You.mp3″);myPlayer = Manager.createRealizedPlayer(url);}catch (Exception e) {System.out.println(“Unable to create the audioPlayer :” + e);}}void stop() {myPlayer.stop();myPlayer.close();}}

File mp3 yang akan kita putar dapat diletakkan di C:\ColdPlay-Fix You.mp3 (absolute path) seperti contoh. Tapi, bisa juga diletakkan di directory yang sama seperti file .class (hasil compile) sehingga kita hanya menulis “ColdPlay-Fix You.mp3″ Dengan demikian, kita sudah dapat membuat pemutar mp3 sederhana. Pengembangan berikutnya kita bisa menggunakan pemutar mp3 yang sudah beredar sebagai benchmark untuk membuat pemutar mp3 yang lebih lengkap fiturnya.Selamat membuat

Page 4: JMF-PROJEK

Membuat Pemutar Video dengan JMFMarch 30, 2008

Di post sebelumnya kita sudah belajar membuat pemutar mp3, sekarang kita menambahkan fitur pemutar video.

Perlu diingat bahwa tidak semua format video didukung oleh JMF.

Kita dapat menambahkan source code dari post sebelumya pada pemutar mp3.

Berikut adalah tambahannya.

Pada constructor, kita tambahkan component berikut:

Component visualComponent = myPlayer.getVisualComponent();this.getContentPane().add(visualComponent, BorderLayout.CENTER);

ukuran frame juga kita ubah untuk menampung visual.

this.setSize(new Dimension(500, 400));

kita juga menambah method play() sebagai berikut:

myPlayer.start();

sehingga pada akhirnya, berikut source code lengkapnya:

import javax.swing.*;import java.awt.*;import java.awt.event.*;import javax.media.*;import java.net.*;

public class HelloJMF extends JFrame {static Player myPlayer = null;public HelloJMF() {super(“Demo JMF”);play();Component panelControl = myPlayer.getControlPanelComponent();Component visualComponent = myPlayer.getVisualComponent();this.getContentPane().add(panelControl, BorderLayout.SOUTH);this.getContentPane().add(visualComponent, BorderLayout.CENTER);this.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent we) {stop();System.exit(0);}});

Page 5: JMF-PROJEK

this.pack();this.setSize(new Dimension(500, 400));this.setVisible(true);}public static void main(String[] args) {HelloJMF helloJMF = new HelloJMF();}void play() {try {URL url = new URL(“file”,null,”C:\\Dani California.mpg”);myPlayer = Manager.createRealizedPlayer(url);myPlayer.start();}catch (Exception e) {System.out.println(“Unable to create the audioPlayer :” + e);}}void stop() {myPlayer.stop();myPlayer.close();}}Selamat memutar video

Membuat Aplikasi Video Conference dengan JMF bagian 1: MenuMarch 30, 2008

Sekarang kita mencoba membuat aplikasi Video Conference menggunakan JMF.

Langkah awal, kita harus mengatur sistem kita agar dapat menjalankan JMF API.

Caranya install jdk kemudian JMF API dari Sun Microsystem. Lebih jelasnya lihat di post mengenai membuat pemutar mp3 dengan JMF di blog ini.

Langkah pertama, kita buat dulu GUI (Graphical User Interface) dari aplikasi tersebut.

Post ini akan mengulas pembuatan menu dulu. Selanjutnya akan dibuat secara bertahap.  Karena sambil dibuat sambil dipost, maka mungkin akan banyak perubahan dari awal. Jadi silahkan disimak bertahap.

Berikut adalah source code untuk menu nya:

import java.awt.*;import java.awt.event.ActionListener;

Page 6: JMF-PROJEK

import java.awt.event.ActionEvent;import javax.swing.*;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JFrame;

public class JConference extends JFrame {

public JConference() {super(“JConference v1.0″);//Beginning of File MenuJMenu fileMenu = new JMenu(“File”);fileMenu.setMnemonic(‘F’);//File–>OpenJMenuItem openItem = new JMenuItem(“Open File”);openItem.setMnemonic(‘O’);fileMenu.add(openItem);//Action for File–>OpenopenItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {System.out.println(“Sementara”);}});//File–>CaptureJMenuItem captureItem = new JMenuItem(“Capture”);captureItem.setMnemonic(‘P’);fileMenu.add(captureItem);//Action for File–>CapturecaptureItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {System.out.println(“Sementara”);}});//File–>ExitJMenuItem exitItem = new JMenuItem(“Exit”);exitItem.setMnemonic(‘X’);fileMenu.add(exitItem);//Action for File–>ExitexitItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {System.exit(0);}});//End of File Menu//Beginning of Player MenuJMenu playerMenu = new JMenu(“Player”);playerMenu.setMnemonic(‘P’);

Page 7: JMF-PROJEK

//Player–>SnapShotJMenuItem snapItem = new JMenuItem(“SnapShot”);snapItem.setMnemonic(‘S’);playerMenu.add(snapItem);//Action for Player–>SnapShotsnapItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {System.out.println(“Sementara”);}});//End of Player Menu//Beginning of Conference MenuJMenu conferenceMenu = new JMenu(“Conference”);conferenceMenu.setMnemonic(‘C’);//Conference–>Join SessionJMenuItem joinItem = new JMenuItem(“Join Session”);joinItem.setMnemonic(‘J’);conferenceMenu.add(joinItem);//Action for Player–>Join SessionjoinItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {System.out.println(“Sementara”);}});//Conference–>Terminate SessionJMenuItem terminateItem = new JMenuItem(“Terminate Session”);terminateItem.setMnemonic(‘T’);conferenceMenu.add(terminateItem);//Action for Player–>Terminate SessionterminateItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent event) {System.out.println(“Sementara”);}});//End of Conference Menu//Adding Menus to Menu BarJMenuBar bar = new JMenuBar();setJMenuBar(bar);bar.add(fileMenu);bar.add(playerMenu);bar.add(conferenceMenu);//Display Properties of MenusetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setSize(500, 500);}public static void main(String[] args) {JConference JConf = new JConference();

Page 8: JMF-PROJEK

JConf.setVisible(true);}

}

Membuat Aplikasi Video Conference dengan JMF bagian 2: PlayerMarch 30, 2008

Di bagian 1 kita sudah membuat menu, sekarang kita akan membuat Player untuk memainkan media yang dipilih dari Menu File –> Open

Kita membuat satu class yang bertugas untuk memainkan file. Class ini adalah class MediaPlayer. Berikut adalah source code nya:

import javax.media.*;import javax.media.Manager;import javax.media.Player;import java.net.URL;import javax.swing.JPanel;import java.awt.*;import java.io.IOException;

public class MediaPlayer extends JPanel {

public MediaPlayer(URL mediaURL) {setLayout( new BorderLayout() );try {//Create a player to play the media specified in the URLPlayer thePlayer = Manager.createRealizedPlayer(mediaURL);Component video = thePlayer.getVisualComponent(); //Add visual componentComponent controls = thePlayer.getControlPanelComponent(); //Add audio componentthis.add(video, BorderLayout.CENTER);this.add(controls, BorderLayout.SOUTH);thePlayer.start();}catch (NoPlayerException noPlayerException){System.err.println( “No media player found” + noPlayerException );}catch (CannotRealizeException cannotRealizeException){System.err.println( “Could not realize media player” + cannotRealizeException);}catch (IOException iOException){

Page 9: JMF-PROJEK

System.err.println( “Error reading from the source” +iOException);}}}

Kemudian, kita edit JConference kita.

Masukkan method openPlayFile() pada action menu File–>Open

Ganti

System.out.println(“Sementara”);

Dengan

openPlayFile();

Kemudian tambahkan method openPlayFile();

void openPlayFile() {URL theURL = null;JFileChooser fileChooser = new JFileChooser();int result = fileChooser.showOpenDialog(null);if (result == JFileChooser.APPROVE_OPTION) {try{theURL = fileChooser.getSelectedFile().toURL();}catch ( MalformedURLException malformedURLException ){System.err.println( “Could not create URL for the file” + malformedURLException);}}if (theURL != null){MediaPlayer thePlayer = new MediaPlayer(theURL);this.add(thePlayer, BorderLayout.CENTER);this.setVisible(true);}}

Sekarang kita sudah membuat player untuk aplikasi kita. Post berikutnya akan menambahkan fasilitas capture untuk menampilkan dan menyimpan video dari web cam.

Membuat Aplikasi Video Conference dengan JMF bagian 3: CaptureMarch 31, 2008

Page 10: JMF-PROJEK

Di post sebelum ini kita sudah membahas bagaimana memainkan multimedia dari local disk. Sekarang kita akan membahas bagaimana caranya untuk capture video dan audio dari web cam dan microphone dan menampilkannya di aplikasi kita.

Pertama, kita buat class untuk menangani format dari video dan audio kita.

import java.awt.*;import java.awt.event.*;import java.util.Vector;import javax.media.*;import javax.media.format.*;import javax.media.protocol.DataSource;import javax.swing.*;

public class CaptureDeviceDialog extends Dialog implements ActionListener, ItemListener {

boolean configurationChanged = false;Vector devices;Vector audioDevices;Vector videoDevices;Vector audioFormats;Vector videoFormats;Choice audioDeviceCombo;Choice videoDeviceCombo;Choice audioFormatCombo;Choice videoFormatCombo;

public CaptureDeviceDialog(Frame parent, String title, boolean mode) {super(parent, title, mode);init();}

private void init() {setSize(450, 180);Panel p = new Panel();p.setLayout(null);

Label l1 = new Label(“Audio Device(s)”);Label l2 = new Label(“Video Device(s)”);Label l3 = new Label(“Audio Format(s)”);Label l4 = new Label(“Video Format(s)”);audioDeviceCombo = new Choice();videoDeviceCombo = new Choice();audioFormatCombo = new Choice();videoFormatCombo = new Choice();

Button OKbutton = new Button(“OK”);Button cancelButton = new Button(“Cancel”);

Page 11: JMF-PROJEK

p.add(l1);l1.setBounds(5, 5, 100, 20);p.add(audioDeviceCombo);audioDeviceCombo.setBounds(115, 5, 300, 20);p.add(l3);l3.setBounds(5, 30, 100,20);p.add(audioFormatCombo);audioFormatCombo.setBounds(115, 30, 300,20);p.add(l2);l2.setBounds(5, 55, 100, 20);p.add(videoDeviceCombo);videoDeviceCombo.setBounds(115, 55, 300, 20);p.add(l4);l4.setBounds(5, 80, 100, 20);p.add(videoFormatCombo);videoFormatCombo.setBounds(115, 80, 300, 20);p.add(OKbutton);OKbutton.setBounds(280, 115, 60, 25);p.add(cancelButton);cancelButton.setBounds(355, 115, 60, 25);

add(p, “Center”);audioDeviceCombo.addItemListener(this);videoDeviceCombo.addItemListener(this);OKbutton.addActionListener(this);cancelButton.addActionListener(this);

//get all the capture devicesdevices = CaptureDeviceManager.getDeviceList ( null );CaptureDeviceInfo cdi;if (devices!=null && devices.size()>0) {int deviceCount = devices.size();audioDevices = new Vector();videoDevices = new Vector();

Format[] formats;for ( int i = 0;  i < deviceCount;  i++ ) {cdi = (CaptureDeviceInfo) devices.elementAt ( i );formats = cdi.getFormats();for ( int j=0;  j<formats.length; j++ ) {if ( formats[j] instanceof AudioFormat ) {audioDevices.addElement(cdi);break;}else if (formats[j] instanceof VideoFormat ) {videoDevices.addElement(cdi);break;}}}

Page 12: JMF-PROJEK

//populate the choices for audiofor (int i=0; i<audioDevices.size(); i++) {cdi  = (CaptureDeviceInfo) audioDevices.elementAt(i);audioDeviceCombo.addItem(cdi.getName());}

//populate the choices for videofor (int i=0; i<videoDevices.size(); i++) {cdi  = (CaptureDeviceInfo) videoDevices.elementAt(i);videoDeviceCombo.addItem(cdi.getName());}

displayAudioFormats();displayVideoFormats();

} // end if devices!=null && devices.size>0else {//no devices found or something bad happened.}}

void displayAudioFormats() {//get audio formats of the selected audio device and repopulate the audio format comboCaptureDeviceInfo cdi;audioFormatCombo.removeAll();

int i = audioDeviceCombo.getSelectedIndex();//i = -1 –> no selected index

if (i!=-1) {cdi = (CaptureDeviceInfo) audioDevices.elementAt(i);if (cdi!=null) {Format[] formats = cdi.getFormats();audioFormats = new Vector();for (int j=0; j<formats.length; j++) {audioFormatCombo.add(formats[j].toString());audioFormats.addElement(formats[j]);}}}}

void displayVideoFormats() {//get audio formats of the selected audio device and repopulate the audio format comboCaptureDeviceInfo cdi;videoFormatCombo.removeAll();

int i = videoDeviceCombo.getSelectedIndex();//i = -1 –> no selected index

Page 13: JMF-PROJEK

if (i!=-1) {cdi = (CaptureDeviceInfo) videoDevices.elementAt(i);if (cdi!=null) {Format[] formats = cdi.getFormats();videoFormats = new Vector();for (int j=0; j<formats.length; j++) {videoFormatCombo.add(formats[j].toString());videoFormats.addElement(formats[j]);}}}}

public CaptureDeviceInfo getAudioDevice() {CaptureDeviceInfo cdi = null;if (audioDeviceCombo!=null) {int i = audioDeviceCombo.getSelectedIndex();cdi = (CaptureDeviceInfo) audioDevices.elementAt(i);}return cdi;}

public CaptureDeviceInfo getVideoDevice() {CaptureDeviceInfo cdi = null;if (videoDeviceCombo!=null) {int i = videoDeviceCombo.getSelectedIndex();cdi = (CaptureDeviceInfo) videoDevices.elementAt(i);}return cdi;}

public Format getAudioFormat() {Format format = null;if (audioFormatCombo!=null) {int i = audioFormatCombo.getSelectedIndex();format = (Format) audioFormats.elementAt(i);}return format;}

public Format getVideoFormat() {Format format = null;if (videoFormatCombo!=null) {int i = videoFormatCombo.getSelectedIndex();format = (Format) videoFormats.elementAt(i);}return format;}

Page 14: JMF-PROJEK

public boolean hasConfigurationChanged() {return configurationChanged;}

public void actionPerformed(ActionEvent ae) {String command = ae.getActionCommand().toString();if (command.equals(“OK”)) {configurationChanged = true;}dispose();}

public void itemStateChanged(ItemEvent ie) {System.out.println(ie.getSource().toString());if (ie.getSource().equals(audioDeviceCombo))displayAudioFormats();elsedisplayVideoFormats();

}}Itu adalah class untuk menangani user yang akan memilih format dari video dan audio yang akan di capture. Selanjutnya, kita tambahkan method capture pada JConference kita.

Pada action File–>Capture, kita ubah

System.out.println(“Sementara”);

menjadi

capture();

Selanjutnya kita tambahkan method capture() dan method-method yang mendukungnya

void registerDevices() {CaptureDeviceDialog cdDialog = newCaptureDeviceDialog(this, “Capture Device”, true);cdDialog.setVisible(true);if (!cdDialog.hasConfigurationChanged())return;//configuration has changed, update variables.audioCDI = cdDialog.getAudioDevice();if (audioCDI!=null) {audioDeviceName = audioCDI.getName();System.out.println(“Audio Device Name: ” + audioDeviceName);}videoCDI = cdDialog.getVideoDevice();if (videoCDI!=null) {videoDeviceName = videoCDI.getName();System.out.println(“Video Device Name: ” + videoDeviceName);

Page 15: JMF-PROJEK

}//Get formats selected, to be used for creating DataSourcevideoFormat = cdDialog.getVideoFormat();audioFormat = cdDialog.getAudioFormat();}public synchronized void controllerUpdate(ControllerEvent event) {System.out.println(event.toString());if (event instanceof RealizeCompleteEvent) {Component comp;System.out.println(“Adding visual component”);if ((comp = dualPlayer.getVisualComponent()) != null)add (“Center”, comp);System.out.println(“Adding control panel”);if ((comp = dualPlayer.getControlPanelComponent()) != null)add(“South”, comp);validate();}}void capture() {if (audioCDI==null && videoCDI==null)registerDevices();

try {if (!(audioCDI==null && videoCDI==null)) {DataSource[] dataSources = new DataSource[2];System.out.println(“Creating data sources.”);dataSources[0] = Manager.createDataSource(audioCDI.getLocator());dataSources[1] = Manager.createDataSource(videoCDI.getLocator());DataSource ds = Manager.createMergingDataSource(dataSources);dualPlayer = Manager.createPlayer(ds);dualPlayer.addControllerListener(this);dualPlayer.start();}elseSystem.out.println(“CDI not found.”);}catch (Exception e) {System.out.println(e.toString());}}

Post selanjutnya kita akan membahas tentang transmit receive paket-paket RTP (Real Time Protocol), protokol yang kita pakai untuk aplikasi kita.

EDIT : Saya sudah tidak programming tentang ini lagi dan sudah lupa juga.Tapi saya masih ada source code yang dulu saya pakai develop dengan netbeans.