Java Sound

Hi
I am worte this programe which will play a Sound File(.wav) from the directory called FileCheck and delete that file from the directory.
But it's playing the .wav file but not deleting the file from the directory. Please let me know what could be the reason.
If anyone know the answer please modify the program and reply me.
Regards
Arghya Banerjee
import java.io.*;
import javax.swing.*;
import java.applet.*;
public class SoundTest extends Thread {
File ff;
AudioClip clip;
public SoundTest() {
start();
public static void main(String[] args) {
SoundTest fileCheck = new SoundTest();
public void run(){
while(true){
System.out.println("Inside Loop");
fileCheck();
public void fileCheck(){
System.out.println("Inside File Check");
File f = new File("c:\\FileCheck");
try{
String str[] = f.list();
if(str.length > 0) {
System.out.println("Hi");
ff = new File("c:\\FileCheck\\"+ str[0]);
clip = Applet.newAudioClip(ff.toURL());
clip.play();
try{
     sleep(2000);
     catch(Exception e){
clip.stop();
boolean result = ff.delete();
if(result)
System.out.println("Deleted : ");
else
System.out.println("Not Deleted : ");
catch(Exception e){
e.printStackTrace();

ok try this
after this line
String str[] = f.list();
add this line
f=null;
similarly after this line
boolean result = ff.delete();
add this
ff=null;

Similar Messages

  • Simple Java Sound Question...

    Can I draw waveforms while capturing data? If yes, how. If no, why.
    Thanks. I need the answer ASAP, please help.

    Hi nfactorial,
    Can I draw waveforms while capturing data?If you would like to do that in Java you would need to know about how to use the Java language in general and especially about the Java Sound and Java2D APIs.
    If yes, how.It would be too much to explain to answer such a general question. A general answer is, you need to use the Java Sound API to capture the data for which a waveform should be drawn. The Sound API delivers data as a stream of bytes typically encoded in pulse coded modulation (PCM) format. The data stream has digital samples each representing a level of sound pressure for a certain point in time. The stream of samples in the amplitude/time domain need to be transformed to a spectrum of samples in the amplitude/frequency domain, i.e. a number of PCM samples need to be mapped to the frequencies that should be displayed. This is done with the fast fourier transformation algorithm. Each set of amplitude/frequency values can then be displayed as a waveform by using some line drawing logic. The entire process would need to run constantly, i.e. as bytes are received from the sound data stream transformation and drawing is triggered.
    Related readings:
    Java Tutorial
    http://java.sun.com/docs/books/tutorial/
    Java Sound Documentation
    http://java.sun.com/j2se/1.5.0/docs/guide/sound/index.html
    Java Sound API Programmer's Guide
    http://java.sun.com/j2se/1.5.0/docs/guide/sound/programmer_guide/contents.html
    Java Sound Resources
    http.//www.jsresources.org
    Java 2D Graphics Tutorial
    http://java.sun.com/docs/books/tutorial/2d/index.html
    Wikipedia on fast fourier transformation
    http://en.wikipedia.org/wiki/Fast_fourier_transform
    HTH
    Ulrich

  • 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) {
        }

  • Using the 'java.sound.*' libraries and classes

    Hello,
    I am a complete noob to Java. So please forgive me if I seem a little stupid in the things I ask.
    I would like to know which development kit I should download to be able to gain access to the 'java.sound.*' and midi libraries and classes.
    I downloaded the Java SE 6 SDK but I could get access to these classes.
    I use JCreator as my compiler and I kept getting an error along the lines of 'java.sound.* package does not exist'. I have tried compiling the code with NetBeans and also wiuth Eclipse and I still have no luck and I get the same message. I am guessing the compiler is not the problem and it is the SDK as I can access other classes such as javax.swing and java.awt etc.
    If you could give me a link to the relevant SDK and maybe a good compiler, it would be greatly appreciated.
    Also I am using Windows XP and Windows Vista so if you could provide me with support for either of these operating systems then that would be great.
    Thank You
    Lee

    Here's the code for an SSCCE (Small Self Contained Compilable Example) of a working java sound application. If you don't provide a file name, It does expect you to have a wave file of Ballroom Blitz in your javatest directory, but doesn't everybody?
    To build and run it do:
    javac -cp . SoundPlayer.java
    java -cp . SoundPlayer  yourWaveFile.wav  
    import java.io.*;
    import javax.sound.sampled.*;
    import javax.sound.sampled.DataLine.*;
    public class SoundPlayer implements LineListener
         private float bufTime;
         private File soundFile;
         private SourceDataLine line;
         private AudioInputStream stream;
         private AudioFormat format;
         private Info info;
         private boolean opened;
         private int frameSize;
         private long frames;
         private int bufFrames;
         private int bufsize;
         private boolean running;
         private boolean shutdown;
         private long firstFrame, lastFrame;
         private float frameRate;
         private long currentFrame;
         private float currentTime;
         private Thread playThread;
         // constructor, take a path to an audio file
         public SoundPlayer(String path)
              this(path, 2);     // use 2 second buffer
         // or a path and a buffer size
         public SoundPlayer(String path, float bt)
              this(new File(path),bt);
         public SoundPlayer(File sf)
              this(sf, 2);  // use 2 second buffer
         public SoundPlayer(File sf, float bt)
              bufTime = bt;          // seconds per buffer
              soundFile = sf;
              openSound();
         private void openSound()
              System.out.println("Opening file"+soundFile.getName());
              try
                   firstFrame = 0;
                   currentFrame = 0;
                   shutdown = false;
                   running = false;
                   stream=AudioSystem.getAudioInputStream(soundFile);
                   format=stream.getFormat();
                   if(format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED)
                        System.out.println("Converting Audio stream format");
                        stream = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED,stream);
                        format = stream.getFormat();
                   frameSize = format.getFrameSize();
                   frames = stream.getFrameLength();
                   lastFrame = frames;
                   frameRate = format.getFrameRate();
                   bufFrames = (int)(frameRate*bufTime);
                   bufsize = frameSize * bufFrames;
                   System.out.println("frameRate="+frameRate);
                   System.out.println("frames="+frames+" frameSize="+frameSize+" bufFrames="+bufFrames+" bufsize="+bufsize);
                   info=new Info(SourceDataLine.class,format,bufsize);
                   line = (SourceDataLine)AudioSystem.getLine(info);
                   line.addLineListener(this);
                   line.open(format,bufsize);
                   opened = true;
              catch(Exception e)
                   e.printStackTrace();
         public void stop()
              System.out.println ("Stopping");
              if(running)
                   running = false;
                   shutdown = true;
                   if(playThread != null)
                        playThread.interrupt();
                        try{playThread.join();}
                        catch(Exception e){e.printStackTrace();}
              if (opened) close();
         private void close()
              System.out.println("close line");
              line.close();
              try{stream.close();}catch(Exception e){}
              line.removeLineListener(this);
              opened = false;
         // set the start and stop time
         public void setTimes(float t0, float tz)
              currentTime = t0;
              firstFrame = (long)(frameRate*t0);
              if(tz > 0)
                   lastFrame = (long)(frameRate*tz);
              else lastFrame = frames;
              if(lastFrame > frames)lastFrame = frames;
              if(firstFrame > lastFrame)firstFrame = lastFrame;
         public void playAsync(float start, float end)
              setTimes(start,end);
              playAsync();
         // play the sound asynchronously */
         public void playAsync()
              System.out.println("Play async");
              if(!opened)openSound();
              if(opened && !running)
                   playThread = new Thread(new Runnable(){public void run(){play();}});
                   playThread.start();
         public void play(float start, float end)
              setTimes(start,end);
              play();
         // play the sound in the calling thread
         public void play()
              if(!opened)openSound();
              if(opened && !running)
                   running = true;
                   int writeSize = frameSize*bufFrames/2; // amount we write at a time
                   byte buf[] = new byte[writeSize];     // our io buffer
                   int len;
                   long framesRemaining = lastFrame-firstFrame;
                   int framesRead;
                   currentFrame=firstFrame;
                   System.out.println("playing file, firstFrame="+firstFrame+" lastFrame="+lastFrame);
                   try
                        line.start();
                        if(firstFrame > 0)
                             long sa = firstFrame * frameSize;
                             System.out.println("Skipping "+firstFrame+" frames="+sa+" bytes");
                             while(sa > 0)sa -= stream.skip(sa);
                        while (running && framesRemaining > 0)
                             len = stream.read(buf,0,writeSize); // read our block
                             if(len > 0)
                                  framesRead = len/frameSize;
                                  framesRemaining -= framesRead;
                                  currentTime = currentFrame/frameRate;
                                  if(currentTime < 0)throw(new Exception("time too low"));
                                  System.out.println("time="+currentTime+" writing "+len+" bytes");
                                  line.write(buf,0,len);
                                  currentFrame+=framesRead;
                             else framesRemaining = 0;
                        if(running)
                             line.drain();                     // let it play out
                             while(line.isActive() && running)
                                  System.out.println("line active");
                                  Thread.sleep(100);
                             shutdown = true;
                        running = false;
                   catch(Exception e)
                        e.printStackTrace();
                        shutdown = true;
                        running = false;
                   if(shutdown)
                        close();
         // return current time relative to start of sound
         public float getTime()
              return ((float)line.getMicrosecondPosition())/1000000;
         // return total time
         public float getLength()
              return (float)frames / frameRate;
         // stop the sound playback, return time in seconds
         public float  pause()
              running = false;
              line.stop();
              return getTime();
         public void update(LineEvent le)
              System.out.println("Line event"+le.toString());
         // play a short simple PCM encoded clip
         public static void playShortClip(String fnm)
              java.applet.AudioClip clip=null;
              try
                   java.io.File file = new java.io.File(fnm);     // get a file for the name provided
                   if(file.exists())                    // only try to use a real file
                        clip = java.applet.Applet.newAudioClip(file.toURL()); // get the audio clip
                   else
                        System.out.println("file="+fnm+" not found");
              catch(Exception e)
                   System.out.println("Error building audio clip from file="+fnm);
                   e.printStackTrace();
              if(clip != null)     // we may not actually have a clip
                   final java.applet.AudioClip rclip = clip;
                   new Thread
                   (new Runnable()
                             public void run()
                                  rclip.play();
                   ).start();
         public boolean isOpened()
              return opened;
         public boolean isRunning()
              return running;
        public void showControls() {
            Control [] controls = line.getControls();
            for (Control c :controls) {
                System.out.println(c.toString());
        public void setGain(float gain) {
            FloatControl g = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN);
            g.setValue(gain);
        public static void main(String [] args) {
            float gain = 0;
            String file = "c:\\javatest\\BallroomBlitz.wav";
              for(String arg : args) {
                for(int i = 0; i < arg.length(); i++) {
                    char c  = arg.charAt(i);
                    if (c == '-') {
                        gain -= 1;
                    } else if (c == '+') {
                        gain += 1;
                    } else {
                             file = arg;
            SoundPlayer sp = new SoundPlayer(file);
            sp.showControls();
            System.out.println("setting gain to " + gain);
            sp.setGain(gain);
            sp.play();
    }

  • How to implement effects in java sound

    I have read the programmer's guide in java sound and it said there that it can generate effects such as distortion, delay and others. I would like to implement some of those, I can already capture and play sound from a microphone but I don't know how to manipulate the data to get my desired effect. Can someone explain the content of the array of bytes? I also hope you can give me some hints or anything that could help me implement my own effect. Thanks in advance!

    going_infinity wrote:
    The contents of the double array do not exceed the range. They are mostly of -0.07 o 0.07.
    I forgot to post this code, this is how byte was transformed to a double array. I am just extending an existing codeAh, yes...that makes a lot more sense. I assumed you were reading from the line as double, and that wouldn't work. But you're already converting it, which is why everything stays in the range you'd expect.
    "Weirdness" solved.
    If I use the double array or the byte array, how can I implement some effects like echo or reverb? I understand that since the "raw data" provides amplitude, I can get it's frequency and there is some FFT involved. All I can see here is determining the pitch of the sound but still, no effects. I'm still confused on where to start. Well, it depends on the effect. I'm not an effects expert, so you'll probably want to go do some Google-ing for what all of the affects are...but I think I can explain an echo.
    Echo is a function of a variable, decay, which is how quickly an echo will fade away. From a physics perspective, think of decay as friction, it'll eventually stop a moving object.
    So, you might implement an echo kinda like the following
    for (int i = 0; i < buffer.length; i++) {
         double threshhold = 0.01;
         double decay = 0.5;
         double echo = sample;
         int j = i+1;
         while((Math.abs(echo) > threshhold) && (j < buffer.length)) {
              buffer[j++] += echo;
              echo *= decay;
    Where some decreasing-fraction of a sample is added to all samples in the future until it drops below some threshhold.
    That may or may not be an "echo" effect, necessarily, as I think that a "true" echo also has a peroid (the delay between the sound and its echo) that I'm not taking into effect, so that effect is probably more like overdrive...but it illistrates the point. You'll have to figure out what each effect "adds" or "subtracts" from the sound, and then loop-through the sound data sequentially adding the effects of the effect.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to get / view Java Sound source code

    Hi All,
    I'm curious to view the Java Sound source code, is that possible? Let me know what I have done so far,
    1. In eclipse I have mapped the src.zip from the JDK directory, now I am able to view most of the source code.
    2. When I try to view AudioSystem.getProviders method it returns value from JDK13Services.getProviders
    But I dont have source code for JDK13Services class, indeed i don't have com.sun.media package source code, in the src.zip
    Do anyone know how to get com.sun.media package source code?
    Thanks in advance,
    Karthikeyan R

    It appears that the 3rd entry of this search
    [http://www.google.com/search?q=JDK13Services]
    give both the javadoc and source for JDK13Services, as follows:
    [http://www.docjar.org/docs/api/com/sun/media/sound/JDK13Services.html]
    The other search listings appear to contain useful information, also.

  • Where can i get a e-book on java sound?

    I want to know where i can download a ebook on java sound.

    [http://java.sun.com/j2se/1.5.0/docs/guide/sound/programmer_guide/contents.html]

  • Cannot recognise any sound devices in Linux using Java sound!

    Hi there - I'm new to Java sound, and can't even get my foot in the door on my Linux system. Even thought my speakers and microphone are fully functional on my system (I can record, playback, etc. using other programs) I cannot get Java to find the microphone, speaker, anything. I've tried calling "AudioSystem.isLineSupported(Port.Info.MICROPHONE)", which returns false, as with all the other Port.Info.... objects.
    I'm sure there are no programs using my audio devices (used lsof | grep snd and lsof | grep dsp, then killed the only program that had anything open) and I've tried running my Java program as the super-user too, but to no avail.
    One thing I CAN do is get sound from /dev/dsp - I can put this into a byte array and play it back later, but I don't know how to find out what sort of codec it uses, how to merge it with Java sound, or anything like that.
    Any help would be much appreciated!
    If it makes any difference, I'm using Xubuntu 8.10, and I normally don't use a microphone or flashy surround-sound speakers, so I've not touched the sound system since I installed Linux.

    Ports are tricky...and by tricky, I don't mean complicated so much as a pain.
    Try using Line.Info objects instead of Port.Info objects and see if you can get any lines.

  • Using Java Sound in Eclipse.

    Can anyone tell me where to put the java soundbanks that i downloaded in order to use Java sound in Eclipse?

    I'm not familiar with this particular issue, but I believe jsresources.org has lots of information on installing soundbanks.

  • An I18N bug from java sound should be fixed.

    When you try to list some audio related names (such as mix name, port name, control name) by using java sound api, and if the names are writtened by non-ascii character such as Chinese, you will get the strange characters, that means java sound api does not support internationalization character. Here is the sample:
    *     SystemMixerFrame.java
    * Copyright (c) 2001 - 2002 by Matthias Pfisterer
    * All rights reserved.
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions
    * are met:
    * - Redistributions of source code must retain the above copyright notice,
    * this list of conditions and the following disclaimer.
    * - Redistributions in binary form must reproduce the above copyright
    * notice, this list of conditions and the following disclaimer in the
    * documentation and/or other materials provided with the distribution.
    * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
    * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
    * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
    * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
    * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
    * OF THE POSSIBILITY OF SUCH DAMAGE.
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.BooleanControl;
    import javax.sound.sampled.CompoundControl;
    import javax.sound.sampled.Control;
    import javax.sound.sampled.EnumControl;
    import javax.sound.sampled.FloatControl;
    import javax.sound.sampled.Line;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.Mixer;
    import javax.sound.sampled.Port;
    IDEAS:
    - user setting tab style vs. show complete windows for multiple mixers (horicontal/vertical)
    - user setting unix style (L/R volume) vs. windows style (volume/balance)
    /**     TODO:
    public class TestSystemMixer {
         /**     TODO:
         private static final Port.Info[]     EMPTY_PORT_INFO_ARRAY = new Port.Info[0];
         public static void main(String[] args) {
              new TestSystemMixer();
              System.exit(0);
         /**     TODO:
         public TestSystemMixer()
              List portMixers = getPortMixers();
              if (portMixers.size() == 0) {
                   out("There are no mixers that support Port lines.SystemMixer: Error");
                   System.exit(1);
              Iterator iterator = portMixers.iterator();
              while (iterator.hasNext())
                   Mixer     mixer = (Mixer) iterator.next();
                   String     strMixerName = mixer.getMixerInfo().getName();
                   out("mixername:" + strMixerName);
                   createMixerPanel(mixer);
         /**     Returns the Mixers that support Port lines.
         private List getPortMixers()
              List supportingMixers = new ArrayList();
              Mixer.Info[]     aMixerInfos = AudioSystem.getMixerInfo();
              for (int i = 0; i < aMixerInfos.length; i++)
                   Mixer     mixer = AudioSystem.getMixer(aMixerInfos);
                   boolean     bSupportsPorts = arePortsSupported(mixer);
                   if (bSupportsPorts)
                        supportingMixers.add(mixer);
              return supportingMixers;
         /**     TODO:
         // should be implemented by:
         // Mixer.isLineSupported(new Line.Info(Port.class))
         private boolean arePortsSupported(Mixer mixer)
              Line.Info[]     infos;
              infos = mixer.getSourceLineInfo();
              for (int i = 0; i < infos.length; i++)
                   if (infos[i] instanceof Port.Info)
                        return true;
              infos = mixer.getTargetLineInfo();
              for (int i = 0; i < infos.length; i++)
                   if (infos[i] instanceof Port.Info)
                        return true;
              return false;
         /**     TODO:
         private void createMixerPanel(Mixer mixer)
              Port.Info[]     infosToCheck = getPortInfo(mixer);
              for (int i = 0; i < infosToCheck.length; i++)
                   Port     port = null;
                   try
                        port = (Port) mixer.getLine(infosToCheck[i]);
                        port.open();
                   catch (LineUnavailableException e)
                        e.printStackTrace();
                   if (port != null)
                        createPortPanel(port);
         /**     TODO:
         private Port.Info[] getPortInfo(Mixer mixer)
              Line.Info[]     infos;
              List portInfoList = new ArrayList();
              infos = mixer.getSourceLineInfo();
              for (int i = 0; i < infos.length; i++)
                   if (infos[i] instanceof Port.Info)
                        portInfoList.add((Port.Info) infos[i]);
              infos = mixer.getTargetLineInfo();
              for (int i = 0; i < infos.length; i++)
                   if (infos[i] instanceof Port.Info)
                        portInfoList.add((Port.Info) infos[i]);
              Port.Info[]     portInfos = (Port.Info[]) portInfoList.toArray(EMPTY_PORT_INFO_ARRAY);
              return portInfos;
         /**     TODO:
         private void createPortPanel(Port port)
              String     strPortName = ((Port.Info) port.getLineInfo()).getName();
              out("Portname:" + strPortName);
              Control[]     aControls = port.getControls();
    //          for (int i = 0; i < aControls.length; i++)
              if (aControls.length > 1) {
                   // In fact in the windows system, it named SPEAKER port, and it contains play controls.
                   out("ignore the port " + strPortName + " that contains more than one control.");
              } else {
                   // this is record control.
                   out("control:" + aControls[0].toString());
                   createControlComponent(aControls[0]);
                   if (aControls[0] instanceof FloatControl)
                   else
         /**     TODO:
         private void createControlComponent(Control control)
              if (control instanceof BooleanControl)
              String          strControlName = control.getType().toString();
              out("sub control type BooleanControl:" + strControlName);
              else if (control instanceof EnumControl)
              String     strControlName = control.getType().toString();
              out("sub control type EnumControl:" + strControlName);
              System.out.println("WARNING: EnumControl is not yet supported");
              else if (control instanceof FloatControl)
              String     strControlName = control.getType().toString();
              out("sub control type FloatControl:" + strControlName);
              else if (control instanceof CompoundControl)
              String     strControlName = control.getType().toString();
              out("sub control type CompoundControl:" + strControlName);
              Control[]     aControls = ((CompoundControl)control).getMemberControls();
              for (int i = 0; i < aControls.length; i++)
                   Control con = aControls[i];
                   if (con instanceof BooleanControl) {
                        out("sub sub control type BooleanControl:" + con.getType().toString());
                        if (strControlName.equalsIgnoreCase("Stereo Mix")) {
                             ((BooleanControl) con).setValue(true);
                   else if (con instanceof EnumControl) {
                        out("sub sub control type EnumControl:" + con.getType().toString());
                   else if (con instanceof FloatControl)
                        if (isBalanceOrPan((FloatControl) con))
                        out("sub sub control type FloatControl balance:" + con.getType().toString());
                        else
                        out("sub sub control type FloatControl pan:" + con.getType().toString());
                   else
         /** Returns whether the type of a FloatControl is BALANCE or PAN.
         private static boolean isBalanceOrPan(FloatControl control)
              Control.Type type = control.getType();
              return type.equals(FloatControl.Type.PAN) || type.equals(FloatControl.Type.BALANCE);
         private static void out(String message)
              System.out.println(message);
    /*** SystemMixerFrame.java ***/
    Compile and run the code below on non-ascii Windows OS, you will catch the problem.
    The solution I provide:
    Download the jdk 1.4.2 source, search the files named PortMixer.c && PortMixerProvider.c and replace the method "NewStringUTF" with the method below:
    jstring WindowsTojstring2( JNIEnv* env, char* str )
    jstring rtn = 0;
    int slen = strlen(str);
    unsigned short* buffer = 0;
    if( slen == 0 )
    rtn = (*env)->NewStringUTF(env,str );
    else
    int length = MultiByteToWideChar( CP_ACP, 0, (LPCSTR)str, slen, NULL, 0 );
    buffer = malloc( length*2 + 1 );
    if( MultiByteToWideChar( CP_ACP, 0, (LPCSTR)str, slen, (LPWSTR)buffer, length ) >0 )
    rtn = (*env)->NewString( env, (jchar*)buffer, length );
    if( buffer )
    free( buffer );
    return rtn;
    Rebuild jdk source code as per sun build document. Got the result files and pick up jsound.dll, replace the original jsound.dll in your JRE with the fixed file.
    Then the problem solved. I also hope sun will fix the problem in the future version of JDK.
    Or any one can help me to submit this article to the sun JDK team.
    Jiawei Zhang
    From Chinese, The city of Shanghai.
    MSN: [email protected]

    If you only wanted to get a beep you could have used Toolkit.beep
    Very simple and fast.
    Rommie.

  • Capturing audio through applet using Java Sound

    hi fellows i need ur help.
    I am working on a voice project to Capture & Play the sound using java sound API instead of JMF. I can capture , play and transmit the sound through application. It works pretty fine but when i convert it to the applet, it is not working.
    I got the full system permissions and also signed the applet for Internet Explorer. Also i packed the
    javax.sound.midi.*
    javax.sound.sampled.*
    classes in the signed cab.
    After doing all this i am getting the AudioFormat not supported exception. I changed the format and used all the combinations but still getting this error
    No line matching interface TargetDataLine supporting format PCM_SIGNED, 16000.0 Hz, 16 bit, mono, big-endian, audio data is supported.
    java.lang.IllegalArgumentException: No line matching interface TargetDataLine supporting format PCM_SIGNED, 16000.0 Hz, 16 bit, mono, big-endian, audio data is supported.
         at javax/sound/sampled/AudioSystem.getLine (AudioSystem.java:312)
         at com/vsoft/voice/VoiceRecord.run (VoiceApplet.java:93)
         at java/lang/Thread.run (Thread.java)plz help me to sort out this problem.

    plz have a look over this problem

  • Audio capture delayed with Java Sound and JWS

    Hi.
    I am experiencing quite a strange problem with Java Sound in my Java Web Start application. I am acquiring sound from the microphone through Java Sound, using a code which looks like this:
    ==============================
    AudioFormat audioFormat = new AudioFormat(11025, 8, 1, true, false);
    // Get a TargetDataLine from the appropriate mixer
    DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, audioFormat);
    TargetDataLine targetDataLine = (TargetDataLine) AudioSystem.getLine(dataLineInfo);
    // Prepare the line for use
    targetDataLine.open(audioFormat);
    targetDataLine.start();
    targetDataLine.addLineListener(myLineListener);
    // Build an input stream from the line
    AudioInputStream audioInStream = new AudioInputStream(targetDataLine);
    // Create the output file
    File outputFile = new File("C:\\MySampleAudioFile.wav");
    // Start the actual audio file-writing operation
    AudioFileFormat.Type targetFileFormatType = AudioFileFormat.Type.WAVE;
    AudioSystem.write(audioInStream, targetFileFormatType, outputFile);
    ==============================
    This code is executed in an independent thread. As you can see from the code reported above, I add a LineListener to my TargetDataLine.
    The problem is that in my JWS application several seconds (about 5-6 seconds) elapse from the call to AudioSystem.write() and the reception of the START LineEvent on my LineListener. This delay only occurs when my JWS application is downloaded from my public internet website, while it is not present when I test my JWS application on my local LAN server.
    It looks like the call to AudioSystem.write() causes some kind of network connection to the remote web server of the JWS app, and this operation takes some time. In fact, if I download my JWS app to my client from the public web server, then I disable all network connections on my client, then the START event is received immediately after the call to AudioSystem.write()... This is STRANGE, isn't it???
    Do you believe the call to AudioSystem.write(), or any other Java Sound call, may cause a network connection to the server from which the JWS application has been downloaded?
    A final addition to the above picture: I also have a "Java Applet" version of this application, which is exactly identical to the JWS version and uses the same exact code to do audio acquisition from the microphone. But, in this case the delay is not present, even when running the applet from the public web server!
    Any help / suggestion would be highly appreciated.
    Best regards,
    Marco.

    Hi
    Just Visit the following link and download sample source code for rtp in java
    http://javasolution.blogspot.com/2007/04/rtp-using-java.html
    if u want know basic simple java voice chat then visit
    http://javasolution.blogspot.com/2007/04/voice-chat-using-java.html

  • Emulating sox trim using java sound APIs

    Hi,
    I would like to know if there is a way to split large wave files into smaller ones (approx 5 min clips, similar to "sox trim") using java sound APIs? I tried the following, but it doesn't seem to work for me
    1. Open a wave file using AudioSystem.getAudioInputStream();
    2. Read 300 * sample_rate * bytes_per_sample bytes into a buffer.
    3. Read the written bytes back using AudioSystem.getAudioInputStream().
    4. Write the stream using AudioSystem.write();
    I can't get step 3 to work, possibly because headers are not written into the buffer and AudioSystem complains about unknown audio format. How do I get this working?
    TIA.

    Okay, I figured a way to do this without using the sound APIs. Now, I am reading the header and data separately, splitting the data and copying the header on each segment. Sorry to have bothered everyone.

  • Quick & dirty concerning Java sound?

    I want to capture a song from a CD and play it in a Java applet- no problem capturing it as a .wav file or whatever, using RealJukebox, etc.
    My question is what kind of compression to use, since an uncompressed CD wave file would be tough on 56k connections (even though Java sound apparently can stream) and take up a lot of disk space. Is JMStudio useful for compressing?

    Thanks- I've seen that. I've also seen some contradictory (presumably older) documentation at http://java.sun.com/docs/books/tutorial/applet/appletsonly/sound.html claiming that Java sound only supports the .au format. I'm not familiar with .au or .aiff and I was hoping maybe somebody knows what's useful for conpressing a song from CD to fair quality & low bit-rate. On the other hand, this tidbit:
    "Problem: Some of my audio files won't play.
    Solution: You cannot play WAV, AU, AIFF, or AU files compressed using ADPCM or other compression schemes. The Java Sound engine supports only linear PCM audio files."
    makes it sound as if I can forget about low bit-rate...

  • Linux and Java sound - map mixers to devices

    Hi,
    I have a question regarding Java Sound API and Linux. I need to query a list of sound devices and let the user choose one of them for further audio operations. This works using the
    AudioSystem.getMixerInfo()call. However, the names of the mixers are not very useful. I find the following mixers:
    Intel [plughw:0,0], version 1.0.23
    Intel [plughw:0,2], version 1.0.23Is there a way to get better names, similar to what Gnone or KDE sound panels display?
    When I run the same code under Windows, the output is much better.

    Try the code from the following article:
    http://www.developerfusion.com/article/84314/wired-for-sound/

  • Basic Java Sound Example.

    Hi,
    Can some one give me a basic java sound application( not applet ) to play a wav file.
    Thanks a lot.
    zia

    I did this search
    http://search.java.sun.com/search/java/index.jsp?qp=&nh=10&qt=%2Bplay+%2Bsound+%2Bwav+%2Bapplication&col=jdc&x=14&y=10
    looks like the answer should be there somewhere

Maybe you are looking for

  • Print out for Goods Issue

    SAP Experts, Can anyone tell me about T.code for goods issue print out? Full scenario we need. thanks babu

  • OC Crashed (I Think)

    So this is what's happened so far: I took an old Blackberry Pearl 8220 flip phone with no battery and ordered a battery for it online. When it arrived and I put it in, the same thing happens. It powers on momentarily, displays an analog clock icon fo

  • HT4623 Having problems with my iMessage activation,

    Good Day, I have updated to the ios7 and I am trying to finish the activation with my Imessage I keep getting this message "IMessage acitivation Could not sign in. Please check your network connectio and try again OK" I have checked with Apple Suppor

  • Urgent: While exporting got error

    hi all While exporting triggers i m getting the following problem EXP-00056: ORACLE error 6550 encountered ORA-06550: line 1, column 30: PLS-00905: object XDB.DBMS_XDBUTIL_INT is invalid ORA-06550: line 1, column 14: PL/SQL: Statement ignored EXP-000

  • CPICTRC File Generation from RFC Server application

    My company has developed a Windows Service that acts as a RFC Server application and pings SAP for remote function calls every so often. We have been running into an issue with the generation of a trace file when the SAP client is shut down. We have