InputStream and playback more than one time

Hi,
I'm trying to playback multiple times the sound I captured with microphone.
But the method playAudio() manage to listen to the sound just one time. Which way can I use to listen many times the sound ??
I don't want to use Clip !!!!!
Here is my code :
public void captureAudio() {
    try {
        final AudioFormat format = getFormat();
      DataLine.Info info = new DataLine.Info(
        TargetDataLine.class, format);
      final TargetDataLine line = (TargetDataLine)
        AudioSystem.getLine(info);
      line.open(format);
      line.start();
      Runnable runner = new Runnable() {
        int bufferSize = (int)format.getSampleRate()
          * format.getFrameSize();
        byte buffer[] = new byte[bufferSize];
        public void run() {
          out = new ByteArrayOutputStream();
          running = true;
          try {
            while (running) {
              int count =
                line.read(buffer, 0, buffer.length);
              if (count > 0) {
                    out.write(buffer, 0, count);
            out.close();
          } catch (IOException e) {
            System.err.println("I/O problems: " + e);
            System.exit(-1);
      captureThread = new Thread(runner);
      captureThread.start();
    } catch (LineUnavailableException e) {
      System.err.println("Line unavailable: " + e);
      System.exit(-2);
    if(!running){running = true;};
  public void playAudio() {
    try {
      byte audio[] = out.toByteArray();
      InputStream input =
        new ByteArrayInputStream(audio);
      final AudioFormat format = getFormat();
      final AudioInputStream ais =
        new AudioInputStream(input, format,
        audio.length / format.getFrameSize());
      DataLine.Info info = new DataLine.Info(
        SourceDataLine.class, format);
      final SourceDataLine line = (SourceDataLine)
        AudioSystem.getLine(info);
      line.open(format);
      line.start();
      Runnable runner = new Runnable() {
        int bufferSize = (int) format.getSampleRate()
          * format.getFrameSize();
        byte buffer[] = new byte[bufferSize];
        public void run() {
          try {
            int count;
            while ((count = ais.read(
                buffer, 0, buffer.length)) != -1 && !running) {
             if (count > 0) {
                        line.write(buffer, 0, count);
            line.drain();
            line.close();
          } catch (IOException e) {
            System.err.println("I/O problems: " + e);
            System.exit(-3);
      playThread = new Thread(runner);
      playThread.start();
    } catch (LineUnavailableException e) {
      System.err.println("Line unavailable: " + e);
      System.exit(-4);
  }Thanks

I play it back the first time correctly. But if I stop it before the end or let it playing until the end, I'm unable to start it again when I click on the play button.
Here is a piece of the whole code (more than 7500 characters):
class Lecture extends JFrame
     private AudioInputStream lecteurAudio;
     private AudioFileFormat formatFichier;
     private AudioFormat format;
     private SourceDataLine line;
     public boolean running;
     private Thread captureThread;
     private volatile boolean exitRequested;
    private volatile boolean isPaused;
    private volatile boolean isCancelled;     
     public Lecture()
          running=true;
     public void AudioFromFile(File fichier) throws UnsupportedAudioFileException, IOException, LineUnavailableException
      this.lecteurAudio = AudioSystem.getAudioInputStream(fichier);
           this.formatFichier = AudioSystem.getAudioFileFormat(fichier);
           this.format = lecteurAudio.getFormat();
           if((this.format.getEncoding() == AudioFormat.Encoding.ULAW) ||
              (this.format.getEncoding() == AudioFormat.Encoding.ALAW))
             //convertion du format
             AudioFormat tmp = new AudioFormat(
                 AudioFormat.Encoding.PCM_SIGNED,
                 this.format.getSampleRate(),
                 this.format.getSampleSizeInBits() * 2,
                 this.format.getChannels(),
                 this.format.getFrameSize() * 2,
                 this.format.getFrameRate(),
                 true);
             this.lecteurAudio = AudioSystem.getAudioInputStream(tmp, this.lecteurAudio);
             this.format = tmp;
           DataLine.Info info = new DataLine.Info(
               SourceDataLine.class,
               this.lecteurAudio.getFormat(),
               ((int)this.lecteurAudio.getFrameLength() *
                this.format.getFrameSize()));
           line = (SourceDataLine)AudioSystem.getLine(info);
           line.open(format);
           line.start();
           if (line != null) {
              try {
                  line.close();
              } catch (Exception e) {
     public void Piste()
          DataLine.Info info = new DataLine.Info(SourceDataLine.class, this.lecteurAudio.getFormat());
           try {
                 if (line == null) {
                     boolean bIsSupportedDirectly = AudioSystem.isLineSupported(info);
                     if (!bIsSupportedDirectly) {
                         AudioFormat sourceFormat = lecteurAudio.getFormat();
                         AudioFormat targetFormat = new AudioFormat(
                                 AudioFormat.Encoding.PCM_SIGNED,
                                 sourceFormat.getSampleRate(),
                                 sourceFormat.getSampleSizeInBits(),
                                 sourceFormat.getChannels(),
                                 sourceFormat.getChannels() * (sourceFormat.getSampleSizeInBits() / 8),
                                 sourceFormat.getSampleRate(),
                                 sourceFormat.isBigEndian());
                         lecteurAudio = AudioSystem.getAudioInputStream(targetFormat, lecteurAudio);
                         format = lecteurAudio.getFormat();
                     line = getSourceDataLine(format);
                 line.open(format);
             } catch (Exception e) {
                 e.printStackTrace();
                 return;
       Runnable runner = new Runnable(){
        int nRead = 0;
        byte[] abData = new byte[(int)format.getSampleRate()* format.getFrameSize()];
        boolean startResume;
        public void run(){
        do {
            startResume = false;
            line.start();
            while (nRead != -1 && !exitRequested) {
                try {
                    nRead = lecteurAudio.read(abData, 0, abData.length);
                } catch (IOException e) {
                    e.printStackTrace();
                if (nRead >= 0) {
                         line.write(abData, 0, nRead);
            if (exitRequested && !isPaused) {
                //cancel
                line.stop();
                line.flush();
            } else if (isPaused) {
                line.stop();
                line.drain();
                try {
                    while (isPaused) {
                        Thread.sleep(20);
                    startResume = true;
                } catch (InterruptedException ex) {
                    //if interrupted...
                    cancel();
       } while (startResume);
    captureThread = new Thread(runner);
    captureThread.start();
     private SourceDataLine getSourceDataLine(AudioFormat format) {
        Exception audioException = null;
        try {
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
            Mixer.Info [] arr = AudioSystem.getMixerInfo();
            Arrays.sort(arr, new Comparator() {
                public int compare(Object o1, Object o2) {
                    Mixer.Info m1 = (Info) o1;
                    Mixer.Info m2 = (Info) o2;
                    if("Java Sound Audio Engine".equals(m1.getName()))
                        return -1;
                    if("Java Sound Audio Engine".equals(m2.getName()))
                        return 1;
                    return 0;
            for (Mixer.Info mi : arr) {
                SourceDataLine dataline = null;
                try {
                    Mixer mixer = AudioSystem.getMixer(mi);
                    dataline = (SourceDataLine) mixer.getLine(info);
                    dataline.open(format);
                    dataline.start();
                     System.out.println(mi.getName());
                    return dataline;
                } catch (Exception e) {
                    audioException = e;
                if (dataline != null) {
                    try {
                        dataline.close();
                    } catch (Exception e) {
        } catch (Exception e) {
            throw new IllegalStateException("Error trying to aquire dataline.", e);
        if (audioException == null) {
            throw new IllegalStateException("Couldn't aquire a dataline, this computer doesn't seem to have audio output?");
        } else {
            throw new IllegalStateException("Couldn't aquire a dataline, probably because all are in use. Last exception:", audioException);
      public boolean isPaused() {
             return isPaused;
     public void setPaused(boolean pause) {
             if (line != null) {
                 if (pause) {
                     isPaused = true;
                     exitRequested = true;
                 } else {
                     isPaused = false;
                     exitRequested = false;
     public void cancel() {
             isPaused = false;
             exitRequested = true;
             isCancelled = true;
    public boolean isCancelled() {
             return isCancelled;
    public void close() {
             if (line != null) {
                 line.close();
}Edited by: bascyr on 8 mai 2010 16:29

Similar Messages

  • How do you select and move more than one bookmark at a time? Shift+Click does not select multiple items that are next to one another in a list because the item

    How do you select and move more than one bookmark at a time?
    Shift+Click does not select multiple items that are next to one another in a list because the items open in firefox before this happens.

    Use the bookmarks library. You may use Shift +Click, and Ctrl + Click to create groupings of selected bookmarks to drag and drop.
    * one method of opening the bookmarks library is keyboard shortcut <br /> Ctrl+Shift+B (Windows)
    *see also [[How to use bookmarks to save and organize your favorite websites]]
    *and [[Use bookmark folders to organize your bookmarks]]

  • HT201301 How do I "Select All" in a Pages document? I would like to copy and past more than one paragraph at a time.

    How do I "Select All" in a Pages document. I would like to copy and paste more than one paragraph at a time.

    I just tab and hold untill the loop shows then let go and I get the menu with select all in it

  • Can I pair and use more than one set of bluetooth speakers at the same time on my ipod touch 4.0

    can I pair and use more than one set of bluetooth speakers at the same time on my ipod touch 4.0 or Iphone 4s or Ipad 2?

    You can only connect to one device at a time using Bluetooth, See article below for more information.
    http://support.apple.com/kb/ht1664
    While your iOS device can maintain multiple pairing records, it can only connect to one headset or hands-free device at a time. This prevents your iOS device from sending your data to the wrong Bluetooth accessory.

  • Select and Drag More Than One Photo

    I can no longer select and drag more than one photo at a time. With one photo it works fine. If I select more than one, I can't move them, so I have to add pictures to albums one at a time, which is rather tedious.
    This has only started happening recently. Possibly after updating to 10.6.8????
    Anu ideas please?
    iPhoto09, v8.1.2

    Then I would try a reinstall:
    To re-install iPhoto
    1. Put the iPhoto.app in the trash (Drag it from your Applications Folder to the trash)
    2a: On 10.5:  Go to HD/Library/Receipts and remove any pkg file there with iPhoto in the name.
    2b: On 10.6: Those receipts may be found as follows:  In the Finder use the Go menu and select Go To Folder. In the resulting window type
    /var/db/receipts/
    2c: on 10.7 they're at
    /private/var/db/receipts
    A Finder Window will open at that location and you can remove the iPhoto pkg files.
    3. Re-install.
    If you purchased an iLife Disk, then iPhoto is on it.
    If iPhoto was installed on your Mac when you go it then it’s on the System Restore disks that came with your Mac. Insert the first one and opt to ‘Install Bundled Applications Only.
    If you purchased it on the App Store or have a Recent Mac you can find it in your Purchases List.

  • How to deploy a Webapplication on WAS more than one times on same server?

    Hi all,
    I 've a special problem:
    In our web-app (some DC's) also stored propertie-Files. Now we would to deploy this application more than one times at same server using different WebContentRoots. (f.e. http://server/app1 and http://server/app2 a.s.o.)
    We know, that we must create different EAR-Projects and refer the web-Module and configure the application.
    But in the second application there it's recommended to change some properties.
    How we can handle this in JDI without copy the web-application?
    I hope my question can be understood.
    Best Regards
    Sven Rickelt
    Using Netweaver + WAS 6.40 2004 SP 13

    Hi Sven,
    as I'm new to NWDI, I cannot give you a 100 percent, field-tested solution. But have you already thought about using the Configuration-Adapter?
    If you can change the source of your web-app, you could maintain the data formerly stored in property files using the configuration adapter of visual administrator. The SC <a href="http://help.sap.com/saphelp_nw04/helpdata/en/45/e7e14b517b42788a1c166f9f32455e/content.htm">configuration</a> allows you to access this data.
    With this approach you can stick to one web-application and do the configuration work separately for each deployed application.
    Best regards,
    Frank

  • How to share more than one Time Machine folder

    Hi,
    With Snow Leo Server I found how to find how to share more than one Time Machine Folder but I can't see how to do the same with Lion Server, could you help me with that ?
    The goal of that is to offer one TM folder per user which is located on a dedicated partition in order to limit the size of TM backups per user (150Gig).
    In Lion, in can only share one TM folder for everybody and I didn'tfind if I can set a limit size per user...
    Thank you in advance,

    I have figured out a way to enable multiple backup targets.
    However, it's one of these things I wouldn't want to describe to anyone except true programmer types, because everyone else has a 90%+ chance of messing up their system if they do something wrong.
    It involves turning off file sharing, and then editing the plist files in /private/var/db/dslocal/nodes/Default/sharepoints/
    The gist of it is this:
    a) first create all the share points you later want to use for TimeMachine, and set them up for afp-only file sharing, also create one TM target, which you can either use later, or have there so the system has one entry it knows how to handle. I just made a bogus one that I'm not actively using.
    b) turn off file sharing in Server.app
    c) turn off TimeMachine in Server.app
    d) now you can edit the files, the easiest is with Xcode, so you may want to install that first
    e) for each sharpoint you made in a) there will be a corresponding .plist file in the location indicated, these are the files that need to be edited.
    f) for each of these files
         1) the item0 string property in the timeMachineBackup array must be switched from 0 to 1
         2) a new key of type array with the name timeMachineBackupUUID must be created
         3) in the newly created array an item of type string must be placed with the value of a UUID, which can be created with the shell command uuidgen
    g) make sure all the edited plist files are saved
    h) turn on TimeMachine in the Server.app again
    If all went well, you now should be able to go to one of your networked client computers and see all the time machine share points just created as options for being a time machine target.
    Anyway, if you go that route: be careful, don't blame me if you muck things up...

  • Will syncing my iphone 3GS more than one time daily wear out the battery?

    Will syncing my iPhone 3GS more than one time daily with Outlook 2007 wear out the battery? An Apple Care advisor said I should only sync it one time per week, but I need to do it daily as I use the calendars and notes for work.

    CindiS wrote:
    Will syncing my iPhone 3GS more than one time daily with Outlook 2007 wear out the battery?
    No.
    An Apple Care advisor said I should only sync it one time per week
    Whoever you talked to has no idea what they are talking about. Ignore their advise.

  • Execute more than one times external command of OS Windows NT

    Hi all,
            I have to execute more than one times from an ABAP program an exernal command of Operating system windows NT . In order to reach this goal I found the standard program RSBDCOS0 and it works very well if you execute it one time.  Unfortunately I have to execute this external command more than one times. Is there any soluiton?
    thank to all
                        Gino Bonfiglioli

    Well why are you using this report RSBDCOS0 to execute external commands?
    Because SAP provides certain function modules that can be used to call operating system commands; so you can use these functions to do your task.
    Just check the following link
    http://help.sap.com/saphelp_nw2004s/helpdata/en/fa/0971e1543b11d1898e0000e8322d00/frameset.htm
    As you mentioned that you need to execute multiple times, you can easily put the call to function module inside a loop or do/enddo structure. for example consider the following
    do 3 times.
    call function 'SXPG_COMMAND_EXECUTE'                           
          exporting                                                 
               commandname                   = 'Put operating system command here'          
               additional_parameters         = full_filename        
               targetsystem                  = targtsys  
               stdout                        = 'X'                  
               stderr                        = 'X'                  
               terminationwait               = 'X'                  
          importing                                                 
               status                        = sxpg_status          
               exitcode                      = sxpg_exitcode        
          tables                                                    
               exec_protocol                 = sxpg_results         
          exceptions                                                
               no_permission                 = 1                    
               command_not_found             = 2                    
               parameters_too_long           = 3                    
               security_risk                 = 4                    
               wrong_check_call_interface    = 5                    
               program_start_error           = 6                    
               program_termination_error     = 7                    
               x_error                       = 8                    
               parameter_expected            = 9                    
               too_many_parameters           = 10                   
               illegal_command               = 11                   
               wrong_asynchronous_parameters = 12                   
               cant_enq_tbtco_entry          = 13                   
               jobcount_generation_error     = 14                   
               others                        = 15.                  
    write the results
    loop at sxpg_results.
    write:/ sxpg_results-length,
             sxpg_results-message.
    endloop.
    refresh sxpg_results.
    enddo.

  • How to post GR from po more than one time?

    i want to post goods receipt from PO more than one time even the quantity of PO have been totally receipted.

    Hi Dear,
                 whats the problem in that if you have recieved 100 quantity all together, and want to post in break-ups then you can surely do that by changing the quantity in the GR, the system will each time suggest the remaining full quantity, you just need to change it.
    Hope it helps.
    Regards,
    Yawar Khan

  • How to load and unload more than one external swf files in different frames?

    I do not have much experience on Adobe Flash or Action Script 3, but I know the basics.
    I am Arabic language teacher, and I design an application to teach Arabic, I just would like to learn how to load and unload more than one external swf files in different frames.
    Thanks

    Look into using the Loader class to load the swf files.  If you want to have it happen in different frames then you can put the code into the different frames.

  • Can I create and use more than one repository on OVM 2.1.5

    The version of Oracle VM I am using is 2.1.5 .
    I wonder can I create and use more than one repository on OVM 2.1.5. Because I want to install different GOS on different disks.
    I know in Oracle VM 2.2 we can use following commands to realize that.
    a. #/opt/ovs-agent-2.3/utils/repos.py –n /dev/mapper/mpathxp1
    b. #/opt/ovs-agent-2.3/utils/repos.py –r UUID
    c. #/opt/ovs-agent-2.3/utils/repos.py –i
    And other repositories can also be mounted and found under /var/ovs/mount/UUID.
    But in Oracle VM 2.1.5, seems just one repository can be created and mounted. For example:
    At first, I create a repository using mpath1p1:
    a. # mkfs.ocfs2 /dev/mapper/mpath1p1
    b. #/usr/lib/ovs/ovs-makerepo /dev/mapper/mpath1p1 C "cluster root"
    c. I can find the repository has been mounted under /OVS.
    But if I want to use "/usr/lib/ovs/ovs-makerepo /dev/mapper/mpath2p1 C "cluster root" to create another repository, and check the mount status using command "mount", these two disks are all have been mounted under /OVS.
    "# cat /etc/ovs/repositories", only mpath1p1 with UUID was recorded there.
    After reboot, only repository with mpath1p1 was mounted under OVS.
    Can anyone tell me how to use more than one repositories on OVM 2.1.5. Do I have to install all the GOSs on the same disk and repository.
    Thank you very much.

    Now I've known how to create different repository. They will be mounted under /OVS/UUID. Thanks.

  • How to select and copy more than one field in SMARTFORMS

    Hello, I have about 60 fields in my smartforms, I need to copy them and paste once more at the same page. There is a problem, I can not select and copy more than one field. Is there some trick to copy and paste more than one element simultanicly?

    Hi,
    There is no way to copy multiple elements in smartform.
    you have to do one by one only

  • Can we prevent entering the same condition more than one time?

    Hi friends,
    Can we prevent the user for entering the same condition type more than one time in same sales order?
    Rama rao

    /write codes in Include ZXVVAU05/
    /prgm avbl in one of the msg in forum/
    DATA: BEGIN OF tXKOMV OCCURS 50.
    INCLUDE STRUCTURE KOMV.
    DATA: END OF tXKOMV.
    data : tab_name(40) type c ,
    ld_len type i , ld_len1 type i .
    field-symbols : <tab> type any.
    tab_name = '(SAPMV45A)XKOMV[]'.
    assign (tab_name) to <tab>.
    txkomv[] = <tab>.
    describe table txkomv lines ld_len .
    sort txkomv by kposn KSCHL .
    delete adjacent duplicates from txkomv comparing kposn KSCHL .
    describe table txkomv lines ld_len1 .
    if ld_len1 ne ld_len .
    refresh txkomv .
    message e002(zmm) with ' Please remove duplicate condition in item price' .
    endif .

  • Block create type of operation more than one time

    Hello SAP CRM Experts!
    I have a question.
    How do I get block the user create a type of operation more than one time?
    For example, I have a kind of opportunity that can be created only once for each client. How can I do this using the customizing?
    Best Regards!
    Tks!

    Hi,
    you could only limit the assigned internal number range to one object, which would allow only one document to be saved. The next creation would then fail since there is no number available.
    This is the only solution I can think of, otherwise you need to program a BADI.
    Regards, Kai

Maybe you are looking for

  • Acrobat Pro 9.3.2 Update problem

    Hi all. I am running CS5 on my Intel mac which is on system 10.5.8. Today I have updated to the latest version of Adobe Acrobat Pro. In my work I use the "Attach for email Review..." feature alot, to send off to our clients. Ever since I have updated

  • Passing Source Query Variables to Target query in RRI

    Hello, I Creating Jump Queries. In the source query user is entering some variable(Dates), based on these varaibles I am creating formula variable in the source query. I wanted pass the same varible values(which are entered by user) to target values(

  • I have the iPhone 5 trying to restore app with 27 sessions phone crashes

    I bought 27 hypnosis sessions through "sleep soundly" app when I had my iPhone 4 when I upgraded to the 5 and tried to get those sessions on this phone it crashes. It is like too many at one time are downloading at once and it crashes. Then I have to

  • BAPI for Add an item in a requisition

    Hi, Do you know which BAPI can be used to add a new item in an existing requisition? We already trie to use BAPI_PR_CREATE and BAPI_PR_CHANGE but didn't work. Can you help us? Thanks and best regards. Sílvia

  • Applecare international coverage

    My girlfriend and I live here in USA and my sister's gilfriend live in Spain. We just bought a Macbook+applecare using my sister's gilfriend spanish credit card. My sister's girlfriend will use her computer in Spain and maybe in UK. Will she have war