Pageviews

Sunday 7 July 2013

Playing audio in Java Applet

by Unknown  |  in Java at  Sunday, July 07, 2013

Applets provide GUI,which is preferred by all users.Java applet supports another good feature of playing music files within the applet.Here are the easy steps,you need to follow in order to run your music files in your Applets.

1.Firstly create a Applet,or you can use the applet code used in the previous post.Then you need to declare the audio you like to output from your Applet using keyword 'AudioClip'.The syntax will be like this;

AudioClip variable_name;

2.Now within the start(),you need to declare your AudioClip using its variable and define its path,where it is located.The syntax will be;

sound=getAudioClip(getCodeBase(),"AudioFile_Path.wav");       //sound-variable name

3.If the audio which you want to play lies within the folder,where you are writing the code,then you need not to specify the path,just simply write its name in " ".But,if you are importing your audio from another drive or folder,then you need to specify its path.

4.In the next step,we need to play our audio clip using play().

Source code for playing audio in Java Applet:

import java.applet.*;
import java.awt.*;

public class applet4 extends Applet
{
AudioClip soundFile1;
Image p;
public void init()
{
p=getImage(getDocumentBase(),"6.jpg");
}
public void start()
{
soundFile1 = getAudioClip (getCodeBase()," 123.wav ");
soundFile1.loop();
soundFile1.play();
}
public void paint(Graphics g)
{
g.drawImage(p,10,10,this);
g.drawString("Music Player",20,20);
}
}

Then you need to compile your java file like this:

Applet

The output will be like this:

Applet music



The work is all done,now you can play your audio files in your Applets.You will not be able to hear anything from this applet,since Java is not installed on our blog,but you will definately hear audio in your device.  The most important point to remember is that,you can only play .wav files in Applets,if you want to play another format,then you can convert it first,then you can play.

0 comments:

Proudly Powered by Blogger.