SimpleAudioPlayer
hi guys, could someone tell me how this code works? where does the code get the file name from?
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.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
/** <titleabbrev>SimpleAudioPlayer</titleabbrev>
<title>Playing an audio file (easy)</title>
<formalpara><title>Purpose</title>
<para>Plays a single audio file.</para></formalpara>
<formalpara><title>Usage</title>
<cmdsynopsis>
<command>java SimpleAudioPlayer</command>
<replaceable class="parameter">wayhardcore</replaceable>
</cmdsynopsis>
</formalpara>
<formalpara><title>Parameters</title>
<variablelist>
<varlistentry>
<term><option><replaceable class="parameter">audiofile</replaceable></option></term>
<listitem><para>the name of the
audio file that should be played</para></listitem>
</varlistentry>
</variablelist>
</formalpara>
<formalpara><title>Bugs, limitations</title>
<para>Only PCM encoded files are supported. A-law, μ-law,
ADPCM, ogg vorbis, mp3 and other compressed data formats are not
supported. For playing these, see <olink targetdoc="AudioPlayer"
targetptr="AudioPlayer">AudioPlayer</olink>.</para>
</formalpara>
<formalpara><title>Source code</title>
<para>
<ulink url="SimpleAudioPlayer.java.html">SimpleAudioPlayer.java</ulink>
</para>
</formalpara>
public class SimpleAudioPlayer
private static final int EXTERNAL_BUFFER_SIZE = 128000;
public static void main(String[] args)
We check that there is exactely one command-line
argument.
If not, we display the usage message and exit.
if (args.length != 1)
printUsageAndExit();
Now, that we're shure there is an argument, we
take it as the filename of the soundfile
we want to play.
String strFilename = args[0];
File soundFile = new File(strFilename);
We have to read in the sound file.
AudioInputStream audioInputStream = null;
try
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
catch (Exception e)
In case of an exception, we dump the exception
including the stack trace to the console output.
Then, we exit the program.
e.printStackTrace();
System.exit(1);
From the AudioInputStream, i.e. from the sound file,
we fetch information about the format of the
audio data.
These information include the sampling frequency,
the number of
channels and the size of the samples.
These information
are needed to ask Java Sound for a suitable output line
for this audio file.
AudioFormat audioFormat = audioInputStream.getFormat();
Asking for a line is a rather tricky thing.
We have to construct an Info object that specifies
the desired properties for the line.
First, we have to say which kind of line we want. The
possibilities are: SourceDataLine (for playback), Clip
(for repeated playback) and TargetDataLine (for
recording).
Here, we want to do normal playback, so we ask for
a SourceDataLine.
Then, we have to pass an AudioFormat object, so that
the Line knows which format the data passed to it
will have.
Furthermore, we can give Java Sound a hint about how
big the internal buffer for the line should be. This
isn't used here, signaling that we
don't care about the exact size. Java Sound will use
some default value for the buffer size.
SourceDataLine line = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class,
audioFormat);
try
line = (SourceDataLine) AudioSystem.getLine(info);
The line is there, but it is not yet ready to
receive audio data. We have to open the line.
line.open(audioFormat);
catch (LineUnavailableException e)
e.printStackTrace();
System.exit(1);
catch (Exception e)
e.printStackTrace();
System.exit(1);
Still not enough. The line now can receive data,
but will not pass them on to the audio output device
(which means to your sound card). This has to be
activated.
line.start();
Ok, finally the line is prepared. Now comes the real
job: we have to write data to the line. We do this
in a loop. First, we read data from the
AudioInputStream to a buffer. Then, we write from
this buffer to the Line. This is done until the end
of the file is reached, which is detected by a
return value of -1 from the read method of the
AudioInputStream.
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
while (nBytesRead != -1)
try
nBytesRead = audioInputStream.read(abData, 0, abData.length);
catch (IOException e)
e.printStackTrace();
if (nBytesRead >= 0)
int nBytesWritten = line.write(abData, 0, nBytesRead);
Wait until all data are played.
This is only necessary because of the bug noted below.
(If we do not wait, we would interrupt the playback by
prematurely closing the line and exiting the VM.)
Thanks to Margie Fitch for bringing me on the right
path to this solution.
line.drain();
All data are played. We can close the shop.
line.close();
There is a bug in the jdk1.3/1.4.
It prevents correct termination of the VM.
So we have to exit ourselves.
System.exit(0);
private static void printUsageAndExit()
out("SimpleAudioPlayer: usage:");
out("\tjava SimpleAudioPlayer <soundfile>");
System.exit(1);
private static void out(String strMessage)
System.out.println(strMessage);
/*** SimpleAudioPlayer.java ***/i cant make anything out form it, so if someone could just tell me how im meant to use it this would be great :D
You have to provide the sound file's name as a commandline argument, like this:
java SimpleAudioPlayer <soundfile name>
this code processes that name:
We check that there is exactely one command-line
argument.
If not, we display the usage message and exit.
if (args.length != 1)
printUsageAndExit();
Now, that we're shure there is an argument, we
take it as the filename of the soundfile
we want to play.
String strFilename = args[0];
File soundFile = new File(strFilename);
Similar Messages
-
Simon game. buttons wont flash... help!
This is a simple "Simon" memory game, produced in GUI...........
The main(); invokes the FIRE(); which generates random numbers , which in turns invokes one of four COLOR methods, red(), green(), yellow(), blue(); .... These methods flash one of the four buttons and are assigned their own values. when they are invoked, they pass that value to Pattern();
Pattern (); fills an array with the random values passed from the color methods, As well as compares users entry against the array and IF user entry is accurate then increase difficulty++
(Pattern method has poor logic in it. I would like tips on this.)
PROBLEM: it executes nearly perfect the first time the code cycles. After that the buttons no longer flash when the FIRE(); invokes COLOR(); methods.
THANKS IN ADVANCE FOR YOUR HELP.
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.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class Simon extends JFrame implements MouseListener,ActionListener
//static int pat=1;
private static final int EXTERNAL_BUFFER_SIZE = 128000;
static JButton but1 = new JButton("Green");
static JButton but2 = new JButton("Blue");
static JButton but3 = new JButton("Orange");
static JButton but4 = new JButton("Red");
static JPanel pane1 = new JPanel();
static JPanel pane2 = new JPanel();
static JPanel pane3 = new JPanel();
static JPanel pane4 = new JPanel();
static JPanel pane5 = new JPanel();
static JButton but5 = new JButton("Start");
//static JLabel lab1 = new JLabel("Simon Says");
Container con = getContentPane();
static File soundFile = new File("hiho.wav");
static File utopia = new File("utopia.wav");
static File cowbell = new File("cowbell.wav");
static File slap = new File("sound16.wav");
static int G1=1,B2=2,Y3=3,R4=4;
static int[] array = new int[256]; // maximum value
static int difficulty = 3; //initial value
static int count;
static int x=0;
static boolean click=false;
public Simon()
super("Simon Says");
con.setLayout(new BorderLayout());
con.add(pane5,BorderLayout.CENTER);
con.add(pane4,BorderLayout.NORTH);
con.add(pane3,BorderLayout.SOUTH);
con.add(pane2,BorderLayout.EAST);
con.add(pane1,BorderLayout.WEST);
pane1.add(but1);
pane2.add(but2);
pane3.add(but3);
pane4.add(but4);
pane5.add(but5);
but1.addMouseListener(this);
but2.addMouseListener(this);
but3.addMouseListener(this);
but4.addMouseListener(this);
but1.addActionListener(this);
but2.addActionListener(this);
but3.addActionListener(this);
but4.addActionListener(this);
but5.addActionListener(this);
public static void main(String[]args)
JFrame af = new Simon();
af.setSize(275,135);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
af.setLocation( (screenSize.width - af.getWidth())/2,
(screenSize.height - af.getHeight())/2 );
af.setVisible(true);
af.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
af.setResizable(false);
but1.setContentAreaFilled(false);
but1.setOpaque(true);//enabling button to changed with mouse events.
but2.setContentAreaFilled(false);
but2.setOpaque(true);
but3.setContentAreaFilled(false);
but3.setOpaque(true);
but4.setContentAreaFilled(false);
but4.setOpaque(true);
but1.setBackground(Color.darkGray);
but1.setForeground(Color.WHITE);
but2.setBackground(Color.darkGray);
but2.setForeground(Color.WHITE);
but3.setBackground(Color.darkGray);
but3.setForeground(Color.WHITE);
but4.setBackground(Color.darkGray);
but4.setForeground(Color.WHITE);
// everytime the pattern fires a button it invokes a method which
// recieves an int ... fills an array with digits. and before the int
// is assigned a subscript a variable is incremented so the array continues
// to cycle.
//store the last pattern in an array then, and do a check if they match generate new pattern.
FIRE();
public static void FIRE()
for(x=0;x<difficulty;++x)
double rnd = Math.random()*10;
if (rnd<2.5)
play(soundFile);
green();
else if (rnd>=2.5&&rnd<=5.0)
play(utopia);
blue();
else if (rnd>5.0&&rnd<=7.5)
play(cowbell);
yellow();
else //if (rnd>7.5);
play(slap);
red();
if(x==difficulty)
count=0;
public static void green()///////////////////////////////////////////////////////
but1.setBackground(Color.GREEN);
but1.setForeground(Color.WHITE);
try
Thread.sleep(200);
catch(InterruptedException e){}
but1.setBackground(Color.darkGray);
but1.setForeground(Color.WHITE);
try
Thread.sleep(200);
catch(InterruptedException e){}
Pattern(G1);
public static void blue()////////////////////////////////////////////////////
but2.setBackground(Color.BLUE);
but2.setForeground(Color.WHITE);
try
Thread.sleep(200);
catch(InterruptedException e){}
but2.setBackground(Color.darkGray);
but2.setForeground(Color.WHITE);
try
Thread.sleep(200);
catch(InterruptedException e){}
Pattern(B2);
public static void yellow()///////////////////////////////////////////////////////
but3.setBackground(Color.ORANGE);
but3.setForeground(Color.WHITE);
try
Thread.sleep(200);
catch(InterruptedException e){}
but3.setBackground(Color.darkGray);
but3.setForeground(Color.WHITE);
try
Thread.sleep(200);
catch(InterruptedException e){}
Pattern(Y3);
public static void red()//////////////////////////////////////////////////////////
but4.setBackground(Color.RED);
but4.setForeground(Color.WHITE);
try
Thread.sleep(200);
catch(InterruptedException e){}
but4.setBackground(Color.darkGray);
but4.setForeground(Color.WHITE);
try
Thread.sleep(200);
catch(InterruptedException e){}
Pattern(R4);
public void mousePressed(MouseEvent e)////////////////////////////////////////////////////////////////
//System.out.println(" Count Equals before Fire()"+count);
Object source = e.getSource();
if (source==but1)
click = true;
but1.setBackground(Color.GREEN);
but1.setForeground(Color.WHITE);
play(soundFile);
Pattern(G1);
if(source==but2)
click = true;
but2.setBackground(Color.BLUE);
but2.setForeground(Color.WHITE);
play(utopia);
Pattern(B2);
if (source==but3)
click = true;
but3.setBackground(Color.orange);
but3.setForeground(Color.WHITE);
play(cowbell);
Pattern(Y3);
if (source==but4)
click = true;
but4.setBackground(Color.RED);
but4.setForeground(Color.WHITE);
play(slap);
Pattern(R4);
public void mouseReleased(MouseEvent e)/////////////////////////////////////////////////////////////
Object source = e.getSource();
if(source==but1)
but1.setBackground(Color.darkGray);
but1.setForeground(Color.WHITE);
else if (source==but2)
but2.setBackground(Color.darkGray);
but2.setForeground(Color.WHITE);
else if (source==but3)
but3.setBackground(Color.darkGray);
but3.setForeground(Color.WHITE);
else if (source==but4)
but4.setBackground(Color.darkGray);
but4.setForeground(Color.WHITE);
public static void Pattern(int A)/////////////////////////////////////////////////////////////
if (x<difficulty)
array[count]=A;
System.out.println("Randomly generated array position "+count+"'s value is, "+A);
++count;
if (x==difficulty)
System.out.println(".....User entry at array position "+count+"'s value is, "+A);
if (array[count]==A&&count==difficulty-1) //if user entry is correct and the array has reached
NEXT();
//array.length then invoke NEXT();
if (A!=array[count]/*&&count<difficulty*/&&count!=0)//poor logic: at anytime if array[count] is not equal to user entry, LOSE();
LOSE();
if (click==true)
count++;
click =false;
public static void LOSE()
System.out.println("YOU LOSE");
System.exit(0);
public static void NEXT()
// String[] s = null;
System.out.println("NEXT LEVEL");
++difficulty;
count=0;
x=0;
// Simon.main((s = new String[] {"N"}));
FIRE();
public static void play(File soundFile)////////////////////////////////// AUDIO PLAYER
AudioInputStream audioInputStream = null;
try
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
catch (Exception e)
e.printStackTrace();
System.exit(1);
AudioFormat audioFormat = audioInputStream.getFormat();
SourceDataLine line = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class,audioFormat);
try
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(audioFormat);
catch (LineUnavailableException e)
e.printStackTrace();
System.exit(1);
catch (Exception e)
e.printStackTrace();
System.exit(1);
line.start();
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
while (nBytesRead != -1)
try
nBytesRead = audioInputStream.read(abData, 0, abData.length);
catch (IOException e)
e.printStackTrace();
if (nBytesRead >= 0)
int nBytesWritten = line.write(abData, 0, nBytesRead);
// line.drain();
// line.close();
//System.exit(0);
private void printUsageAndExit()
out("SimpleAudioPlayer: usage:");
out("\tjava SimpleAudioPlayer <soundfile>");
System.exit(1);
private void out(String strMessage)
System.out.println(strMessage);
public void actionPerformed(ActionEvent e)//OVERRIDDEN INTERFACE METHODS
public void mouseClicked(MouseEvent e)
public void mouseEntered(MouseEvent e)
public void mouseExited(MouseEvent e)
}In the future, Swing related questions should be posted in the Swing forum.
You don't use the Thread.sleep(...) method in the GUI Event Thread, it prevents the GUI from responding to events and repainting itself.
Use a Swing Timer to schedule the frequency of whatever you are doing. -
Issues with Sound Clip.getMicrosecondPosition in Mac OS X
Hi All
I am trying to implement sound player in Java as following.
public void play() throws Exception
AudioInputStream stream = AudioSystem.getAudioInputStream( new FileInputStream(new File(m_path)));
AudioFormat format = stream.getFormat();
DataLine.Info info = new DataLine.Info( Clip.class, stream.getFormat(), ((int)stream.getFrameLength()*format.getFrameSize()));
soundClip = (Clip) AudioSystem.getLine(info);
soundClip.open(stream);
soundClip.addLineListener(new LineListener() {
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP)
System.out.println("playcomplete event: " + soundClip.getMicrosecondPosition());
soundClip.start();
}'soundClip' is instance of javax.sound.sampled.Clip.
After completion of play LineEvent.Type.STOP event is fired.
Method call soundClip.getMicrosecondPosition() displays the proper values in windows but in Mac OSX it always prints 0.
Did any face the similar issue?
Do we have any other approach to know whether the sound play is finished?
Please help me out
Thanks in advance
-SurendharMacOS is notoriously bad for support for JavaSound as Apple (1) rolls their own JVM (2) doesn't like for things to compete with their products, AKA QuickTime...
Your best bet would be to handle the playing yourself at the Mixer level, and then you'll know you're done playing when you're done writing (plus whatever time it takes to finish playing the buffer, which you can just code a static delay for if you'd like)
[http://www.jsresources.org/examples/SimpleAudioPlayer.html] -
Uploading Recorded Sound to Server (PHP) & Retrieve to play
Hello friends, i want to capture audio from an applet and send that byte array to server where php will be at the server side. I also want to use an combobox in applet to choose the files already uploaded to server for listen purpose.if anyone having related resources or codes please help me....
[http://www.jsresources.org/examples/SimpleAudioRecorder.html]
Modify the AudioSystem.write to write to an OutputStream instead of a file, and then just write it using normal socket procedures.
[http://www.jsresources.org/examples/SimpleAudioPlayer.html]
Modify the AudioInputStream to take in an InputStream instead of a file, and then just use normal socket procedure to download the file from the server. -
Question about Java Sound example?
Hello,
I found this example AudioPlayer, when searching for an example of how to play .wav files in Java.
The code seems quite long, and wondered if anyone could advise if this is the best way to play a wav file?
And could anyone explain if the EXTERNAL_BUFFER_SIZE should allows be set to 128000;
Thank you
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.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
public class SimpleAudioPlayer
private static final int EXTERNAL_BUFFER_SIZE = 128000;
public static void main(String[] args)
We check that there is exactely one command-line
argument.
If not, we display the usage message and exit.
if (args.length != 1)
printUsageAndExit();
Now, that we're shure there is an argument, we
take it as the filename of the soundfile
we want to play.
String strFilename = args[0];
File soundFile = new File(strFilename);
We have to read in the sound file.
AudioInputStream audioInputStream = null;
try
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
catch (Exception e)
In case of an exception, we dump the exception
including the stack trace to the console output.
Then, we exit the program.
e.printStackTrace();
System.exit(1);
From the AudioInputStream, i.e. from the sound file,
we fetch information about the format of the
audio data.
These information include the sampling frequency,
the number of
channels and the size of the samples.
These information
are needed to ask Java Sound for a suitable output line
for this audio file.
AudioFormat audioFormat = audioInputStream.getFormat();
Asking for a line is a rather tricky thing.
We have to construct an Info object that specifies
the desired properties for the line.
First, we have to say which kind of line we want. The
possibilities are: SourceDataLine (for playback), Clip
(for repeated playback) and TargetDataLine (for
recording).
Here, we want to do normal playback, so we ask for
a SourceDataLine.
Then, we have to pass an AudioFormat object, so that
the Line knows which format the data passed to it
will have.
Furthermore, we can give Java Sound a hint about how
big the internal buffer for the line should be. This
isn't used here, signaling that we
don't care about the exact size. Java Sound will use
some default value for the buffer size.
SourceDataLine line = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class,
audioFormat);
try
line = (SourceDataLine) AudioSystem.getLine(info);
The line is there, but it is not yet ready to
receive audio data. We have to open the line.
line.open(audioFormat);
catch (LineUnavailableException e)
e.printStackTrace();
System.exit(1);
catch (Exception e)
e.printStackTrace();
System.exit(1);
Still not enough. The line now can receive data,
but will not pass them on to the audio output device
(which means to your sound card). This has to be
activated.
line.start();
Ok, finally the line is prepared. Now comes the real
job: we have to write data to the line. We do this
in a loop. First, we read data from the
AudioInputStream to a buffer. Then, we write from
this buffer to the Line. This is done until the end
of the file is reached, which is detected by a
return value of -1 from the read method of the
AudioInputStream.
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
while (nBytesRead != -1)
try
nBytesRead = audioInputStream.read(abData, 0, abData.length);
catch (IOException e)
e.printStackTrace();
if (nBytesRead >= 0)
int nBytesWritten = line.write(abData, 0, nBytesRead);
Wait until all data are played.
This is only necessary because of the bug noted below.
(If we do not wait, we would interrupt the playback by
prematurely closing the line and exiting the VM.)
Thanks to Margie Fitch for bringing me on the right
path to this solution.
line.drain();
All data are played. We can close the shop.
line.close();
There is a bug in the jdk1.3/1.4.
It prevents correct termination of the VM.
So we have to exit ourselves.
System.exit(0);
private static void printUsageAndExit()
out("SimpleAudioPlayer: usage:");
out("\tjava SimpleAudioPlayer <soundfile>");
System.exit(1);
private static void out(String strMessage)
System.out.println(strMessage);
}I didnot go thru the code you posted but I know that the following workstry {
// From file
AudioInputStream stream = AudioSystem.getAudioInputStream(new File("audiofile"));
// From URL
stream = AudioSystem.getAudioInputStream(new URL("http://hostname/audiofile"));
// At present, ALAW and ULAW encodings must be converted
// to PCM_SIGNED before it can be played
AudioFormat format = stream.getFormat();
if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
format = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
format.getSampleRate(),
format.getSampleSizeInBits()*2,
format.getChannels(),
format.getFrameSize()*2,
format.getFrameRate(),
true); // big endian
stream = AudioSystem.getAudioInputStream(format, stream);
// Create the clip
DataLine.Info info = new DataLine.Info(
Clip.class, stream.getFormat(), ((int)stream.getFrameLength()*format.getFrameSize()));
Clip clip = (Clip) AudioSystem.getLine(info);
// This method does not return until the audio file is completely loaded
clip.open(stream);
// Start playing
clip.start();
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (LineUnavailableException e) {
} catch (UnsupportedAudioFileException e) {
} -
Java playback of multiple wav files in sequence - without overlap
Hi there
I am asking for suggestions on how to do simple consecutive playback of multiple wavefiles using java. Right now I have each wavefile loaded into a clip, and the playback almost works, but with occasional errors where two or more of the files are played back simultaneously. I am doing busy-waiting using the clip.isActive() method in a while-loop in order to detect when a clip has finished playing so that the next one can start. I know that there are most likely some smarter methods of doing this, and I have tried some of them - e.g. linelistener but without getting it to work. If anyone can supply me with some example code on how to do this the right way, or could point me to some literature, it would be greatly appreciated.
Thx in advance.
Jacobhttp://www.jsresources.org/examples/SimpleAudioPlayer.html
That example plays a file by opening it with an AudioInputStream and copying the contents to a SourceDataLine to play it...
It can be easily modified to allow for multiple files to be opened & copied to a single SDL, and is what I'd consider the "proper" way to do it. Clips are mostly useful for things like making a button go "beep" and things of that nature. Not especially useful for normal multimedia applications. -
Hi,
I am writting a program involving a JComboBox.
My Question is:
How can jComboBox1.getSelectedIndex() return 1 if the previous line was jComboBox1.setSelectedIndex(0).
My code:
File f=null;
int at=0;
boolean dontdoit=false;
@SuppressWarnings("static-access")
private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
System.out.println(jComboBox1.getSelectedIndex()+" "+dontdoit);
if(jComboBox1.getSelectedIndex()==1 && at!=1 && !dontdoit) {
at=1;
JFileChooser jfc=new JFileChooser();
int i=jfc.showOpenDialog(null);
f=jfc.getSelectedFile();
if(i==jfc.CANCEL_OPTION) {System.out.println("H");
f=null;
at=0;
dontdoit=true;
jComboBox1.setSelectedIndex(0);
System.out.println(jComboBox1.getSelectedIndex());
jComboBox1ItemStateChanged(null);
return;
try {
SimpleAudioPlayer sap=new SimpleAudioPlayer(f.toURI().toURL().getPath());
sap.audioPlayer.close();
}catch(Exception e) {
JOptionPane.showConfirmDialog(null,"This file is not a valid audio file.\nPlease select another.","Invalid",-1);
jComboBox1ItemStateChanged(null);
else {
f=null;
at=0;
dontdoit=false;
}I can't get it to work. Please HelpSorry:
(Part 1)
* Options.java
* Created on May 19, 2009, 3:28 PM
package chatx;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
* @author Michael
public class Options extends javax.swing.JFrame {
/** Creates new form Options */
public Options() {
initComponents();
if(!new File("C:\\ChatX\\Options\\RINGLEN.txt").exists()) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("C:\\ChatX\\Options\\RINGLEN.txt");
fos.write("20".getBytes());
fos.close();
} catch (Exception ex) {
else {
FileInputStream fos = null;
try {
fos = new FileInputStream("C:\\ChatX\\Options\\RINGLEN.txt");
byte[] b = new byte[fos.available()];
fos.read(b);
jSpinner1.setValue(Integer.parseInt(new String(b)));
fos.close();
} catch (Exception ex) {
Logger.getLogger(Options.class.getName()).log(Level.SEVERE, null, ex);
if(new File("C:\\ChatX\\Options\\RINGTONE").exists()) {
jComboBox1.setSelectedIndex(1);
at=1;
public void copyFile(File in, File out) throws Exception {
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);
byte[] buf = new byte[1024];
int i = 0;
while((i=fis.read(buf))!=-1) {
fos.write(buf, 0, i);
fis.close();
fos.close();
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jSpinner1 = new javax.swing.JSpinner();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox();
jLabel4 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Options", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));
jLabel1.setText("Ring Length:");
jSpinner1.setValue(new Integer(20));
jLabel2.setText("seconds");
jLabel3.setText("Ring Tone:");
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Standard Ringing", "Custom" }));
jComboBox1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBox1ItemStateChanged(evt);
jLabel4.setText("IP Address:");
jTextField1.setEditable(false);
jTextField1.setText("YOURIP");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField1)
.addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jSpinner1, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addContainerGap(158, Short.MAX_VALUE))
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(155, Short.MAX_VALUE))
); -
Below code is a simple audio player using command line argument. But I am unable to run this code. When i try to compile, it gives me an error
SimpleAudioPlayer.java uses or overrides a deprecated API. Recompile with -Xlint:deprecation for details.
I am a newbie in JMF, so correct the errors in the code with explanation. Thanks!
Here is the code:
import javax.media.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;
public class SimpleAudioPlayer
private Player audioPlayer = null;
public SimpleAudioPlayer(URL url) throws IOException, NoPlayerException, CannotRealizeException
audioPlayer = Manager.createRealizedPlayer(url);
public SimpleAudioPlayer(File file) throws IOException, NoPlayerException, CannotRealizeException
this(file.toURL());
public void play()
audioPlayer.start();
public void stop()
audioPlayer.stop();
audioPlayer.close();
File audioFile = new File(args[0]);
SimpleAudioPlayer player = new SimpleAudioPlayer(audioFile);
player.play();
player.stop();
}Thanks!
I am getting one more error which says *"IOException; must be caught or declared to be thrown SimpleAudioPlayer player = _new_ SimpleAudioPlayer(audioFile);*"
It also sometimes gives an error on player.play(); says expected. I checked the parenthesis.
Also i have put this code inside the main like this:
public static void main(String args[]) throws IOException
File audioFile = new File(args[0]);
SimpleAudioPlayer player = new SimpleAudioPlayer(audioFile); // I getting Error here (new)
player.play();
player.stop();
} -
Make a voice transmitter over the network?
Hi i have read that it is possible in javax.sound to send or transmit live audio over the network or simply make a VoIP phone using the javax.sound api. I would like to ask if how can I be able to send the sound of the network. I have this step by step instruction about capturing and sending the voice in the network:
Use TargetDataLine for streaming capture
The TargetDataLine is wrapped in an AudioInputStream so that it can be converted to the network format with AudioSystem
a capture thread reads from the converted AudioInputStream and writes it to the network connection's OutputStream.
Here is my code:
audioFormat = getAudioFormat();
DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, audioFormat);
targetDataLine = (TargetDataLine)AudioSystem.getLine(dataLineInfo);
audioInputStream = new AudioInputStream(targetDataLine);I am not sure about this code but I am sure that there must be a targetDataLine associated in sending the voice. Please help me with this. Thank you.TargetDataLines are for reading from, SourceDataLines are for writing to, and AudioInputStreams are for loading/saving from a file.
That said, there will be a TargetDataLine you can read from that's associated with your microphone. You create an AudioInputStream to read from the TargetDataLine (which is just an argument in the constructor), and then you can do...
AudioSystem.write
Give it the AIS associated with hte TDL, and you can either have it write it to a file or to an output stream. If that output stream was, say...an IP socket stream...then you could send it over the network to the other side...where you'd then need to construct an AudioInputStream to read it from the IP socket stream, and then to play it, you'd read some data from the AIS and write it to a SourceDataLine.
Here are some resources to help you with the JavaSound stuff.
JavaSound Example code (take a look at SimpleAudioPlayer & SimpleAudioRecorder in the Audio Playback and Recording section)
[http://www.jsresources.org/examples/]
Programmer's guide
[http://java.sun.com/j2se/1.5.0/docs/guide/sound/programmer_guide/contents.html]
And then just the normal Java SE6 API
[http://java.sun.com/javase/6/docs/api/] -
Problem with AudioPlayer?
Hello,
I wrote this simple audio player to play .wav files, the other day it was working. But I must have changed sometime and now the code, will not run the wav.
And will not display any exception, any thoughts?
The java session in windows dos will not end itself.
Thank you
import java.io.*;
import java.io.File;
import javax.sound.sampled.*;
public class SimpleAudioPlayer{
AudioInputStream audioInputStream = null;
AudioFormat audioFormat;
DataLine.Info info;
Clip clips = null;
SimpleAudioPlayer(){
void play(String clip){
try{
audioInputStream = AudioSystem.getAudioInputStream(new File(clip));
audioFormat = audioInputStream.getFormat();
if((audioFormat.getEncoding() == AudioFormat.Encoding.ULAW) ||
(audioFormat.getEncoding() == AudioFormat.Encoding.ALAW)){
AudioFormat tmp = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
audioFormat.getSampleRate(),
audioFormat.getSampleSizeInBits()*2,
audioFormat.getChannels(),
audioFormat.getFrameSize()*2,
audioFormat.getFrameRate(),true);
audioInputStream = AudioSystem.getAudioInputStream(tmp, audioInputStream);
audioFormat = tmp;
info = new DataLine.Info(Clip.class, audioInputStream.getFormat(),
((int) audioInputStream.getFrameLength() *
audioFormat.getFrameSize()));
clips = (Clip) (AudioSystem.getLine(info));
clips.open(audioInputStream);
clips.start();
catch(Exception e){
System.out.println(e.getMessage());
System.exit(0);
finally{
clips.close();
try{
audioInputStream.close();
}catch(IOException ex){
System.out.println(ex.getMessage());
System.exit(0);
public static void main(String args[]){
SimpleAudioPlayer player = new SimpleAudioPlayer();
player.play("welcome.wav");
}Hi, Beverley.
Thank you for visiting Apple Support Communities.
I understand that you are unable to trim clips using iMovie. I would need a little more information on how you were attempting to trim a clip to provide a better answer. However, make sure you have the movie project open and are selecting the clip that you wish to trim as this will activate the clip trimmer.
Trim clips
-Jason H. -
I'm am busy creating a simple game. I want the user to be able to play wav files while the game is running. Could someone possible point me to a very basic Class that plays wav files. Basically i want to be able to create a new instance of this class and send it the filename, and it must then play the file. Try as i might, JavaSound just confuses me.
thanks.have you seen this?
[url http://www.jsresources.org/examples/SimpleAudioPlayer.java.html]sample
sourcecode sample / demo -
I'm new to sound. I saw this program on the internet, but i'm not sure how to use it exactly. It says it needs a parameter (the name of the audio file) can anyone show me how to connect it to the main program?
public class SimpleAudioPlayer
private static final int EXTERNAL_BUFFER_SIZE = 128000;
public static void main(String[] args)
if (args.length != 1)
printUsageAndExit();
String strFilename = args[0];
File soundFile = new File(strFilename);
AudioInputStream audioInputStream = null;
try
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
catch (Exception e)
e.printStackTrace();
System.exit(1);
AudioFormat audioFormat = audioInputStream.getFormat();
SourceDataLine line = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class,
audioFormat);
try
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(audioFormat);
catch (LineUnavailableException e)
e.printStackTrace();
System.exit(1);
catch (Exception e)
e.printStackTrace();
System.exit(1);
line.start();
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
while (nBytesRead != -1)
try
nBytesRead = audioInputStream.read(abData, 0, abData.length);
catch (IOException e)
e.printStackTrace();
if (nBytesRead >= 0)
int nBytesWritten = line.write(abData, 0, nBytesRead);
line.drain();
line.close();
System.exit(0);
private static void printUsageAndExit()
out("SimpleAudioPlayer: usage:");
out("\tjava SimpleAudioPlayer <soundfile>");
System.exit(1);
private static void out(String strMessage)
System.out.println(strMessage);
}I'm not really sure what you mean by connecting it to the main program. That's a nearly complete program in itself. It's only missing two lines from the top:
import javax.sound.sampled.*;
import java.io.*;
Once you've added those (and compiled) it should run just fine from the command line: type "java SimpleAudioPlayer yoursoundfile.wav". -
Play audio file with jmf on linux?
a simple audio player as flow:
import javax.media.*;
import java.io.File;
import java.net.URL;
public class SimpleAudioPlayer {
private Player audioPlayer = null;
public SimpleAudioPlayer(URL url) throws Exception {
audioPlayer = Manager.createRealizedPlayer(url);
public SimpleAudioPlayer(File file) throws Exception {
this(file.toURL());
public void play() {
audioPlayer.start();
public void stop() {
audioPlayer.close();
public static void main(String[] args) throws Exception {
File file = new File("/usr/local/download/1.wav");
SimpleAudioPlayer sap = new SimpleAudioPlayer(file);
sap.play();
}when run the program
javac -cp jmf.jar SimpleAudioPlayer.java
java -cp .:jmf.jar SimpleAudioPlayer
the output as flow:
Unable to handle format: ima4/ms, 8000.0 Hz, 4-bit, Mono, Unsigned, 4027.0 frame rate, FrameSize=4096 bits
Failed to prefetch: com.sun.media.PlaybackEngine@defa1a
Error: Unable to prefetch com.sun.media.PlaybackEngine@defa1a
How can I play wav file with jmf on linux?(OS is debian5 and jmf cross-platform pack)thanks for your reply.
I tried to replace the wav file "1.wav" with the linear encoded WAV download from pscode.org,and run the code again,but
BasicTrackControl:prefetchTrack():96 1 bm = com.sun.media.BasicRendererModule@1186fab
BasicRendererModule.doPrefetch:155 Render : true
Render buffer size: 32768
BasicRenderModule.doPrefetch:159
javax.media.ResourceUnavailableException: Cannot intialize audio device for playback
at com.sun.media.renderer.audio.JavaSoundRenderer.open(JavaSoundRenderer.java:93)
at com.sun.media.BasicRendererModule.doPrefetch(BasicRendererModule.java:158)
at com.sun.media.BasicTrackControl.prefetchTrack(BasicTrackControl.java:99)
at com.sun.media.PlaybackEngine.doPrefetch1(PlaybackEngine.java:682)
at com.sun.media.PlaybackEngine.doPrefetch(PlaybackEngine.java:658)
at com.sun.media.PrefetchWorkThread.process(BasicController.java:1430)
!!!!!!!§§§§§§§§§§§ BasicTrackControl:prefetchTrack():96
at com.sun.media.StateTransitionWorkThread.run(BasicController.java:1339)
Unable to handle format: LINEAR, 16000.0 Hz, 16-bit, Mono, LittleEndian, Signed, 32000.0 frame rate, FrameSize=16 bits
Failed to prefetch: com.sun.media.PlaybackEngine@26e431
Error: Unable to prefetch com.sun.media.PlaybackEngine@26e431
Maybe you are looking for
-
I've only had this iphone 5 for a few months, i was able to talk to people perfectly fine but now for some reason, i have to put them on speaker phone or use my headset to hear them, if i don't have them on either, i can't hear anything they are sayi
-
Best iPod conversion programs? from AVI, etc. to MPEG-4
Some of the programs I've downloaded for trial do not work with Vista Home Premium. And if they do work it will only convery a 5MB file or so. My question is what is the best program for converting video files for play with an iPod touch while the OS
-
"FI: Postings" is not allowed (WBS 2008/00697/01/01)
Hi SAP Guru's, When i try to post G/L(F-02) with WBS element,System shows this error. "FI: Postings" is not allowed (WBS 2008/00697/01/01)... Please help us...... Thanks in advance... Thanks & Regards, Sri
-
Nokia 720 volume down button not working and both three lights not working..back button light windows light and search button light even in darkness not working....i need a replacement nokia...
-
Connect facebook 'Events' feed to Adobe Muse website
I need help connecting facebook 'Events' feed to Adobe Muse website.... Help?