|
-
Nov 19th, 2008, 11:12 AM
#1
Thread Starter
Member
Playing WAV files
Hello,
I am trying to figure out how to play .WAV files in my Java program. Here is the code. I get no errors when I compile but no sound plays. I placed the wav file in the same directory as my java and class files. I also tried to compile through the command line, passing the name of the file as the argument. I also instantuated my Sound class in the main of my driver program - Sound sound = new Sound("nightingale2.wav"); . Not sure what I did wrong. Any assistence will be greatly appreciated!
Code:
import java.io.*;
import javax.sound.sampled.*;
import javax.swing.JOptionPane;
public class Sound
{
File soundFile;
public Sound( String file)
{
soundFile = new File(file);
}
public void play()
{
try
{
AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile);
AudioFormat format = ais.getFormat();
JOptionPane.showMessageDialog(null, "Format: " + format);
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
SourceDataLine source = (SourceDataLine) AudioSystem.getLine(info);
source.open(format);
source.start();
int read = 0;
byte[] audioData = new byte[16384];
while (read > -1)
{
read = ais.read(audioData, 0, audioData.length);
if (read >=0)
{
source.write(audioData, 0, read);
}
}
source.drain();
source.close();
}catch (Exception exc)
{
JOptionPane.showMessageDialog(null, "Error: " + exc.getMessage());
exc.printStackTrace();
}
System.exit(0);
}
public static void main( String [] arguments)
{
if (arguments.length > 1)
{
JOptionPane.showMessageDialog(null, "Usage: Java Speaker Filename");
System.exit(-1);
}
Sound sound = new Sound(arguments[0]);
sound.play();
}
}
Last edited by 01010011; Nov 19th, 2008 at 11:19 AM.
-
Nov 19th, 2008, 01:53 PM
#2
Fanatic Member
Re: Playing WAV files
sound = new Sound(".\nightingale2.wav");
maybe..? if thats what you mean, i dont really understand the question.
-
Nov 19th, 2008, 03:54 PM
#3
Thread Starter
Member
Re: Playing WAV files
 Originally Posted by Justa Lol
sound = new Sound(".\nightingale2.wav");
maybe..? if thats what you mean, i dont really understand the question.
I was trying to play the wav file by passing the name of the file as an argument, and by creating a new instance of the class Sound to get it to play.
-
Nov 19th, 2008, 05:27 PM
#4
Re: Playing WAV files
 Originally Posted by Justa Lol
sound = new Sound(".\nightingale2.wav");
maybe..? if thats what you mean, i dont really understand the question.
I think you should read about Escape characters
"I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
My Blog
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|