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

Similar Messages

  • Simple Java Coding Question

    I know this is a simple question, but I can't search for the answer to this because it involves syntax that Google and the like don't seem to search for..
    I am trying to figure out some Java code that I have found. I would like to know what:
    a[--i] and a[++j] mean.
    My first thought was that they meant to look at the position in the array one less (or more) than i (j). But that doesn't seem to be the case. A is an array of Strings, if that matters...
    Thanks for you help.

    muiajc wrote:
    I know this is a simple question, but I can't search for the answer to this because it involves syntax that Google and the like don't seem to search for..
    I am trying to figure out some Java code that I have found. I would like to know what:
    a[--i] and a[++j] mean.
    It mean increase/decrease the int i/j by 1. This is done before it gets you the value of a[]. for example if i=5 and you said a[--i] it is really a[4] and i is now equal to 4;

  • Simple Java EJB question.

    When it comes to EJB v3 Remote and Local interfaces,
    (With JBoss EJB Container Software in mind, for this question,)
    -Does the Remote interface for the EJB include method signatures from the Bean class
    -that are to be seen
    -that are to be hidden?
    -Does the Local interface for the EJB include method signatures from the Bean class
    -that are to be seen
    -that are to be hidden?
    Which is which for
    -EJB 2.1 ?
    -EJB 3.x ?
    - is EJB 3.x reverse compatible in that it allows use of the javax.ejb.* interfaces,
    and would accept a EJB 2.1 approach, or does it force one to use Annotations
    exclusively?
    Edited by: Zac1234 on Jul 21, 2010 5:21 PM

    muiajc wrote:
    I know this is a simple question, but I can't search for the answer to this because it involves syntax that Google and the like don't seem to search for..
    I am trying to figure out some Java code that I have found. I would like to know what:
    a[--i] and a[++j] mean.
    It mean increase/decrease the int i/j by 1. This is done before it gets you the value of a[]. for example if i=5 and you said a[--i] it is really a[4] and i is now equal to 4;

  • Plzzz write prog to this simple java threads question

    Write a program in C to create four processes. The original processes creates
    two children before it prints out "PARENT". The children processes print
    "CHILD1" and "CHILD2" respectively. The first child process creates a child
    process that prints out "GRANDCHILD".
    Note: The output must be guaranteed to print out in the following order each
    time it is executed:
    GRANDCHILD
    CHILD2
    CHILD1
    PARENT
    a. Write the program using C or C++ and forks to create the children processes.
    b. Write a second program using Java and Threads for the children processes.
    The output statements for CHILD1, CHILD2 and GRANDCHILD must come from print
    statements in the run method of the thread.

    Most people here will not do your homework for you. If you post a reasonable question that shows you've made some effort, and what the results of that effort were, and provides details about what parts you're having trouble with, then somebody will probably provide guidance so that [you can complete the work.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Simple Java SDK question for server group assignment

    I have a snippet of code below in which I am trying to apply the setProcessingServerGroup() and setProcessingServerGroupChoice() methods to my report object. My question should be relatively simple: I believe I need to cast(?) my iObject report object to iProcessingServerGroupInfo per the API in order to use the setProcessingServerGroup() and setProcessingServerGroupChoice() methods, but I'm not sure how to do so.
    Can someone please advise how to cast my iObject to iProcessingServerGroupInfo?
    Thanks in advance...
    Code:
    IInfoObject iObject = (IInfoObject) childReports.get(i); 
    int sgID_view = Integer.parseInt(serverGroupID_view);
    int sgPref_view = Integer.parseInt(serverGroupPref_view);
    !!!!!  CONVERSION / CAST NEEDED HERE !!!!!
    iProcessingServerGroupInfo.setProcessingServerGroup(sgID_view);
    iProcessingServerGroupInfo.setProcessingServerGroupChoice(sgPref_view);

    To followup, I've been able to cast to IShedulingInfo in order to use the setServerGroup() and setServerGroupChoice() methods successfully:
    IInfoObject iObject = (IInfoObject) iObjects.get(i);    
    ISchedulingInfo iSchedulingInfo = iObject.getSchedulingInfo();
    iSchedulingInfo.setServerGroup(427);
    iSchedulingInfo.setServerGroupChoice(2);
    But I don't know how to perform the cast to be able to access the setProcessingServerGroup(), sterProcessingServerGroupChoice() methods.
    Any help appreciated.
    Thanks!

  • Simple java architecture question

    This should be a simple question to answer but I haven't been able to find a good answer.
    I have an application that establishes a network connection with a server and registers event listeners on that connection.
    What I want to do is find a way without a busy-wait/while loop to keep the main() thread running so that the listeners can do their job.
    Here is a sample of what I've got:
    public static void main(String[] args)
    SomeConnection conn1 = null;
    try
    conn1 = new SomeConnection("someaddress");
    TrafficManager tm = conn1.getTraffictManager();
    TrafficHandler th = tm.createTraffichandler(new MessageListener()
                        public void processMessage(Message message)
                             System.out.println("Received: " + message.toString());
         catch (Exception e)
              e.printStackTrace(System.out);
         conn1.disconnect();
    The problem is that the application doesn't stay running to respond to traffic coming across the connection.
    Any guidance would be appreciated.
    Thanks

    Well, what is the job of the MessageListener if it isn't to listen for messages? And apparently it isn't doing that because your application terminates.
    Bear in mind that I don't have any idea how any of those four classes work, or even how they are supposed to work. So let me just quote this line from the API documentation of the Thread class which says when your application will terminate:
    "All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method."
    That must be the case in your application.

  • Simple Java Array Question

    // This is how I was taught to make a simple array. You have to define the size first.
    String [] test1 = new String[4];
    test1[0] = "1";
    test1[1] = "2";
    test1[2] = "3";
    test1[3] = "4";
    out.println(test1[0]);
    out.println(test1[1]);
    out.println(test1[2]);
    out.println(test1[3]);
    //If the size is not defined in this second example, why does it still work?
    String [] test2 = {"1","2","3","4"};
    out.println(test2[0]);
    out.println(test2[1]);
    out.println(test2[2]);
    out.println(test2[3]);
    They both produce the same results.

    // This is how I was taught to make a simple array.
    You have to define the size first.
    String [] test1 = new String[4];
    test1[0] = "1";
    test1[1] = "2";
    test1[2] = "3";
    test1[3] = "4";
    out.println(test1[0]);
    out.println(test1[1]);
    out.println(test1[2]);
    out.println(test1[3]);
    //If the size is not defined in this second example,
    why does it still work?
    String [] test2 = {"1","2","3","4"};
    out.println(test2[0]);
    out.println(test2[1]);
    out.println(test2[2]);
    out.println(test2[3]);
    They both produce the same results.Umm..the size is just as well defined in your second as in your first...it is a four element array.
    The second way is akin to the first...also
    String[] s = new String[]{"Hello","I","contain","five","elements"};
    System.out.println(s[5]); Will compile..you will get a run-time ArrayIndexOutOfBoundsException (it is a 5 element array, 0-4, but java will not assume that the variable s is not changed between those two lines of code)..
    Array index/boundary checking is done at run-time, not compile-time.
    In fact:
    String[] s;
    //let's say up in the program
    //and
    public void printS(int i)
    System.out.println(s);
    Will also compile...and if something else happens to set s as a 10 element String array:
    printS(9);would work
    ~David

  • Simple java pgm - question

    Hallo,
    to the following pgm I had question:
    static void printPrimes (int max) (= wavy bracket;
    boolean(should be angular brackets) sieve = new booolean (angular br max+1
    angular br)
    int i,j;
    for (i=2; i = max;i++)sieve(angluarbr i angular br)= true
    i= 2
    while (i= <= max;) (=wavy bracket Out.println (i+ " "); // is prime
    for (j=i; j <= j+i) sieve(angular br j angularb.) = false;
    while (i <= maxAmpersandAmpersand !sieve (angular br angular br)I++;
    ) wavy br ) wavy br.
    I hope this is still kind of readable.
    Q's are:
    after the first "for" there is a new i=2, which seems to staty at 2 all the time; the following while does not change this value ( the beginning for i++ does not change this) and so seems to print 2 at all times (??)
    then the inner loop seems to count up all the doubbles of the new prime number and thrwoes it out as false at the end of it;
    the i values (increased with i++ seemsto refere at all times to the unit numbers and only indirect to the un it values, which are written/ assigned to it (??)
    I seem to wonder how the pgm can print out anythings else the 2's.
    I would appreciate any help to that.
    ml
    griz

    I hope this is still kind of readable.No, it's not. http://forum.java.sun.com/help.jspa?sec=formatting
    Why are you omitting the braces and brackets? And why don't you type "program"? Aren't we worth the additional time it takes?
    Q's are:
    after the first "for" there is a new i=2, which
    seems to staty at 2 all the time; the following
    while does not change this value Why should it? You don't tell it to.
    ( the beginning for
    i++ does not change this)It does. It just gets re-set to 2 after the for loop-
    and so seems to print 2 at
    all times (??)Yeah. What else?
    then the inner loop seems to count up all the
    doubbles of the new prime number and thrwoes it out
    as false at the end of it; That part is definitely unreadable.

  • Simple Java regex question

    I have a file with set of Name:Value pairs
    e.g
    Action1:fail
    Action2:pass
    Action3:fred
    Using regex package I Want to get value of Name "Action1"
    I have tried diff things but I cannot figure out how I can do it. I can find Action1: is present or not but dont know how I can get value associated with it.
    I have tried:
    Pattern pattern = Pattern.compile("Action1");
    CharSequence charSequence = CharSequenceFromFile(fileName); // method retuning charsq from a file
    Matcher matcher = pattern.matcher(charSequence);
    if(matcher.find()){
         int start = matcher.end(0);
         System.out.println("matcher.group(0)"+ matcher.group(0));
    how I can get value associated with specific tag?
    thanks
    anmol

    read the data from the text file on a line basis and you can do:
    String line //get this somehow
    String[] keyPair = line.split(":")g
    System.out.println(keyPair[0]); //your name
    System.out.println(keyPair[1]); //your valueor if you've got the text file in one big string:
    String pattern = "(\\a*):(\\a*)$"; //{alpha}:{alpha}newline //?
    //then
    //do some things with match objects
    //look in the API at java.util.regex

  • Problem with getNodeValue() - simple Java XPath question

    I am trying to extract the node values from a XML file:
    <root>
      <frame>
         <boxes>
           <box>
              <spec>22</spec>
              <spec>2222</spec>
           </box>
           <box>
              <spec id="BA" value="short"/>
              <spec id="BB" value="thin"/>
              <spec id="BC" value="black"/>
              <spec id="BD" value="full"/>
              <spec id="BE" value="7"/>
              <spec id="BF" value="deactive"/>
           </box>                
         </boxes>
         <circles>
           <circle id="CA" value="blue"/>
           <circle id="CB" value="green"/>
         </circles>
      </frame>
    </root>I use this code:
             XPathFactory factory = XPathFactory.newInstance();
             XPath xpath = factory.newXPath();
             XPathExpression xPathExpression = xpath.compile("/root/frame/boxes/box/spec");            
             Object result = xPathExpression.evaluate(doc, XPathConstants.NODESET);
             NodeList nodes = (NodeList) result;
             for (int i = 0; i < nodes.getLength(); i++) {
                 System.out.println(nodes.item(i).getNodeValue());
             }But only:
    null
    null
    null
    null
    null
    null
    null
    null
    get printed. I would have assumed:
    22
    2222
    null
    null
    null
    null
    null
    null
    since the two first spec nodes contains the above numbers. Any ideas?

    change this:
    XPathExpression xPathExpression = xpath.compile("/root/frame/boxes/box/spec");to this:
    XPathExpression xPathExpression = xpath.compile("/root/frame/boxes/box/spec/text()");Need to xpath all the way down to the text of the node.
    You could use
    System.out.println(nodes.item(i).getTextContent());with your current xpath but if the spec node has children, these will also be included in the output.

  • Efficiency Question: Simple Java DC vs Used WD Component

    Hello guys,
    The scenario is - I want to call a function that returns a FileInputStream object so I can process it on my WD view. I can think of two approaches - one is to simply write a simple Java DC that does so and just use it as a used DC so I can call the functionality from there. Or create another WD DC that exposes the value (as binary) via component interface.
    I'm leaning on the simple Java DC approach - its easier to create. But I'm just curious on what would be the Pro-side (if there's any) if I use the WD Component interface approach? Is there a plus for the efficiency? (Though I doubt) Or is it just a 'best/recommended practice' approach?
    Thanks!
    Regards,
    Jan

    Hi Jan
    >one is to simply write a simple Java DC that does so and just use it as a used DC so I can call the functionality from there
    Implemented Java  API for the purpose mentioned in your question is the right way, I think. The Java API can be even located in the same WebDynpro DC as your WebDynpro components. There is not strongly necessity to put it into separate Java DC.
    >Or create another WD DC that exposes the value (as binary) via component interface
    You should not do this because in general WD components' purpose is UI, not API. Implementing WD component without any UI, but with some component interface has very-very restricted use cases. Such WD component shall only be a choice in the cases when the API is WebDynpro based and if you have to strongly use WebDynpro Runtime API in order to implement your own API.
    If your API does not require WebDynpro Runtime API invocations or anything else related to WebDynpro then your choice is simple Java API.
    >But I'm just curious on what would be the Pro-side (if there's any) if I use the WD Component interface approach? Is there a plus for the efficiency?
    No. Performance will be better in simple Java API then in WebDynpro component interface. The reason is the API will not pass thought heavy WebDynpro engine.
    BR, Siarhei

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

  • Can we call a simple java application from ESB

    Please let me know how this can be done by using a ESB. The application jar exists on the host server. How we can pass parameters etc and receive results from this application.
    Any help will be greatly appreciated.
    Prakash

    Not sure if I completely understand your question, but you can certainly try following ways:
    - call your java application via WSIF. ESB with JAVA wsif is available in 10.1.3.3.1 only (it is not supported in 10.1.3.3 very well).
    - you will have to include this jar file in server.xml or bpel/system/classes so that it is available to the SOA jvm.
    - You mentioned it is simple java application, but if your java API has complex (object) input and output, you will need some work
    HTH,
    Chintan

  • Re: Using simple java class in an .war file.

    Hi All,
    I have a simple question,
    Can I access an simple java class from a jsp file that I have written by putting it in the "classes" folder?? What entry should go in the web.xml file?
    Here is my directory structure:
    sample.war
    |
    ----test.jsp <file>
    |
    ----WEB-INF <folder>
    | |
    | ----classes<folder>
    | | |
    | | ----simpleJavaClass.class<file>
    | |
    | ----lib<folder>
    | |
    | ----web.xml
    I want to access the simpleJavaClass.class from the jsp test.jsp.
    Please suggest.
    Thanks and regards
    Ayusman

    It is possible to access the class in u r classes folder from u r jsp file.
    For example
    <%@ page import="com.test.service.PricingSolution,
    com.test.core.PhoneNumber
    %>
    <% PricingSolution solution = (PricingSolution)session.getAttribute("solution"); %>
    This is a simple scriplet example. You do the same using jstl tags also.
    --Shinoy

  • 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();
    }

Maybe you are looking for

  • The restore previous session button is not working on Firefox on any of my three machines. How can I fix this?

    I have a desktop at work, and a desktop and laptop at home and just recently the "restore previous session" button that comes up when I use the desktop icon to start a Firefox Web browser session does not work. It is there and I click it but nothing

  • How many times can I use a form?

    Hi Everyone, Can anyone explain what this means? (text below) If I make a form in LiveCycle Designer and then I extend it so that other users can fill it out...Does that mean that only 500 people can use the form? If so, then...I am dumbfounded and d

  • Attachment List details

    Hi all, I am using cl_gos_manager (using custom SW01 object ) to attach files to a custom dialog program. My requirement is i am writing a report that list the document number and number of attachments attached to that document number. Example Docume

  • BPEL FTP Adapter problems

    Hi! I have two problem using the FTP Adapter in a BPEL process. The first can be described as follow: I have a BPEL process that incapsulates the FTP Adapter and it is deployed correctly on the BPEL default domain. It's working fine in a normal conte

  • 6500 slide freezes when receiving SMS

    hi, I own a brand new 6500 slider, its only a few weeks old and it has a very upsetting bug. when the music player is on and the keys lock automatically (set for 1 minute), and i receive an SMS, the phone simply freezes. The keys are useless, the lig