Making Sound More Efficient

I got this code to play some audio clips and it works alright. The only issue is that when I call the play method it lags the rest of my game pretty badly. Is there anything in the play method you guys think could be moved to the constructor to make it more efficient?
btw I know I posted this in the sound section already but it had like 17 views there and no responses after like a week on the front page so I decided to bring it here.
package main;
import java.io.*;
import javax.sound.sampled.*;
public class Sound
     private AudioFormat format;
    private byte[] samples;
    private String name;
     public Sound(String filename)
          name=filename;
          try
            AudioInputStream stream =AudioSystem.getAudioInputStream(new File("sounds/"+filename));
            format = stream.getFormat();
            samples = getSamples(stream);
        }catch (Exception e){System.out.println(e);}
     public byte[] getSamples()
        return samples;
    private byte[] getSamples(AudioInputStream audioStream)
        int length=(int)(audioStream.getFrameLength()*format.getFrameSize());
        byte[] samples = new byte[length];
        DataInputStream is = new DataInputStream(audioStream);
        try
            is.readFully(samples);
        }catch (Exception e){System.out.println(e);}
        return samples;
    public void play()
         InputStream stream =new ByteArrayInputStream(getSamples());
        int bufferSize = format.getFrameSize()*Math.round(format.getSampleRate() / 10);
        byte[] buffer = new byte[bufferSize];
        SourceDataLine line;
        try
            DataLine.Info info=new DataLine.Info(SourceDataLine.class, format);
            line=(SourceDataLine)AudioSystem.getLine(info);
            line.open(format, bufferSize);
        }catch (Exception e){System.out.println(e);return;}
        line.start();
        try
            int numBytesRead = 0;
            while (numBytesRead != -1)
                numBytesRead =
                    stream.read(buffer, 0, buffer.length);
                if (numBytesRead != -1)
                   line.write(buffer, 0, numBytesRead);
        }catch (Exception e){System.out.println(e);}
        line.drain();
        line.close();
    public String getName()
         return name;
}

BammRocket wrote:
I got this code to play some audio clips and it works alright. The only issue is that when I call the play method it lags the rest of my game pretty badly. Is there anything in the play method you guys think could be moved to the constructor to make it more efficient?you got this code from chapter 4 of [Developing Games in Java|http://www.brackeen.com/javagamebook/] right?
are you playing the sounds in a different thread?
if not, your program will just freeze until the sound is finished.

Similar Messages

  • Making code more efficient

    I am having a lot of trouble getting my code to work fast enough. I have 4 sonic anemometers and currently my code is only efficient enough to collect data from one. I have programs that run 2 sonic anemometers and save the data, but bites pile up at the port. The instruments are in unprompted mode and send data at 10hz. I find that using the wait command dose not work well for some reason so I have the loop continuously running. The first version of my code (V3a) worked for one sonic and bites did not pile up at the port. So I made (V3b) and tried to make a more efficient program. I tried separating things into multiple loops but, it still does not work well and was hoping to get some ideas to make things work better.
    I attached the 2 versions of my code. I am not sure if I should attach the subVIs, let me know.
    Thanks!
    Attachments:
    fo3csat_unprompted_v3a.vi ‏23 KB
    fo3csat_unprompted_v3b.vi ‏27 KB

    I'm going to ask you a very important question about that occurrence in the top loop: by using the occurrence the way you have, have you eliminated the possibility of a race condition? The answer is NO... study it, and you'll see why. If you can't figure it out, post back and I'll tell you why the race condition is still present.
    Also, if you ever are coding and thinking to yourself, "WOW, I can't believe the guys who developed LabVIEW made it so hard to do this simple task!", odds are, you're making it hard yourself! Rather than making 4 parallel branches of a numeric, converting to an ASCII string, then reinterpreting as 4 separate numerics, consider the following code. It's nearly equivalent, except my seconds has more significant digits (maybe good, maybe not):
    I'm going to argue that even splitting the discrete components of time is unnecessary, unless your logging protocol specifically requires that format. Instead, simply write the timestamp directly to file with the data points.
    Also, remember to use a standard 4x2x2x4 connector pane on your SubVIs. Refer to the LabVIEW Style Guide (search, and you will find it).
    Finally, I'm going to disagree with the other guys, it's not evident why you split the one loop into three loops. The only "producer/consumer" architecture has the top loop as the "producer", and all it's producing is a timestamp! This is not a typical or intended use of the producer/consumer architecture. Your VI is intended to only save a data point once every 30 minutes (presumably), so it's no big deal of both of your serial devices are in the same loop.
    The single biggest problem why your VI is completely railing out a CPU core (you didn't state this, but I'm guessing the reason you posting is because you noticed a core running at 100%!) is the unmetered loop rate... like the other guys say, drop a "Wait Until Next ms Multiple" and slow the loop rate down significantly. 10msec is probably too fast for your application.... actually, a loop rate of once every 30 minutes (that's 1800000msec) might be best.
    Let us know how it goes!
    a.lia-user-name-link[href="/t5/user/viewprofilepage/user-id/88938"] {color: black;} a.lia-user-name-link[href="/t5/user/viewprofilepage/user-id/88938"]:after {content: '';} .jrd-sig {height: 80px; overflow: visible;} .jrd-sig-deploy {float:left; opacity:0.2;} .jrd-sig-img {float:right; opacity:0.2;} .jrd-sig-img:hover {opacity:0.8;} .jrd-sig-deploy:hover {opacity:0.8;}

  • Making it more efficient

    I will be using this function
                   private function inter_1a(evt:MouseEvent):void {
                    var popUpInterDisplay:interactionexporter;
                    popUpInterDisplay = new interactionexporter();
                    popUpInterDisplay.source = "lessons/lessonone/interactions/inter1a.swf";
                    PopUpManager.addPopUp(popUpInterDisplay, this, true);
    But will use it at least 30 times. For example:
                   private function inter_1b(evt:MouseEvent):void {
                    var popUpInterDisplay:interactionexporter;
                    popUpInterDisplay = new interactionexporter();
                    popUpInterDisplay.source = "lessons/lessonone/interactions/inter1b.swf";
                    PopUpManager.addPopUp(popUpInterDisplay, this, true);
               private function inter_1c(evt:MouseEvent):void {
                     var popUpInterDisplay:interactionexporter;
                     popUpInterDisplay = new interactionexporter();
                     popUpInterDisplay.source = "lessons/lessonone/interactions/inter1c.swf";
                     PopUpManager.addPopUp(popUpInterDisplay, this, true);
        ETC......
    Any ideas as to make this more efficient?
    Thanks

    This can be written more efficient indeed. How are these functions called, by Buttons or by an item in a datagrid?
    In case it are buttons, you can store the name of the swf in their id properties:
    private function inter(evt:MouseEvent):void
          var popUpInterDisplay:interactionexporter = new interactionexporter();
          popUpInterDisplay.source = "lessons/lessonone/interactions/" + evt.target.id + ".swf";
          PopUpManager.addPopUp(popUpInterDisplay, this, true);
    In case of a datagrid, you can use a property of the selectedItem:
    private function inter(evt:MouseEvent):void
           var popUpInterDisplay:interactionexporter = new interactionexporter();
           popUpInterDisplay.source = "lessons/lessonone/interactions/" + evt.currentTarget.selectedItem.propName + ".swf";
           PopUpManager.addPopUp(popUpInterDisplay, this, true);
    Dany

  • Pointers: more efficient method(s), styles for making unconventional UI's

    i currently use mages on my custom panels to give the customized look i want for my apps. But i just can shake the feeling that there are more efficient ways to do it. i just need pointers to some materials (books, articles, documentation, etc) for some technology i can use.
    thanks!

    i currently use mages on my custom panels to give the customized look i want for my apps. But i just can shake the feeling that there are more efficient ways to do it. i just need pointers to some materials (books, articles, documentation, etc) for some technology i can use.
    thanks!

  • Linking from one PDF to another: Is there a more efficient way?

    Some background first:
    We make a large catalog (400pages) in Indesign and it's updated every year. We are a wholesale distributor and our pricing changes so we also make a price list with price ref # that corresponded with #s printed in the main catalogue.  Last year we also made this catalog interactive so that a pdf of it could be browsed using links and bookmarks. This is not too difficult using Indesign and making any adjustments in the exported PDF. Here is the part that becomes tedious and is especially so this year:
    We also set up links in the main catalog that go to the price list pdf - opening the page with the item's price ref # and prices... Here's my biggest issue - I have not found any way to do this except making links one at a time in Acrobat Pro (and setting various specifications like focus and action and which page (in the price list) to open) Last year this wasn't too bad because we used only one price list. It still took some time to go through and set up 400-500 links individually.
    This year we've simplified our linking a little by putting only one link per page but that is still 400 links. And this year I have 6 different price lists (price tiers...) to link to the main catalogue pdf. (That's in the neighborhood of 1200-1500 double clicking the link(button) to open Button Properties, click Actions tab, click Add..."Go to page view" , set link to other pdf page, click edit, change Open in to "New Window" and set Zoom.  This isn't a big deal if you only have a few Next, Previous, Home kind of buttons....but it's huge when you have hundreds of links. Surely there's a better way?
    Is there anyway in Acrobat or Indesign to more efficiently create and edit hundreds of links from one pdf to another?
    If anything is unclear and my question doesn't make sense please ask. I will do my best to help you answer my questions.
    Thanks

    George, I looked at the article talking about the fdf files and it sounds interesting. I've gathered that I could manipulate the pdf links by making an fdf file and importing that into the PDF, correct?
    Now, I wondered - can I export an fdf from the current pdf and then change what is in there and import it back into the pdf.  I've tried this (Forms>More Form Options>Manage Form Data>Export Data) and then opened the fdf in a text editor but I see nothing related to the documents links... I assume this is because the links are 'form' data to begin with - but is there away to export something with link data like that described in the article link you provided?
    Thanks

  • I need a more efficient method of transferin​g data from RT in a FP2010 to the host.

    I am currently using LV6.1.
    My host program is currently using Datasocket to read and write data to and from a Field Point 2010 system. My controls and indicators are defined as datasockets. In FP I have an RT loop talking to a communication loop using RT-FIFO's. The communication loop is using Publish to send and receive via the Datasocket indicators and controls in the host program. I am running out of bandwidth in getting data to and from the host and there is not very much data. The RT program includes 2 PID's and 2 filters. There are 10 floats going to the Host and 10 floats coming back from the Host. The desired Time Critical Loop time is 20ms. The actual loop time is about 14ms. Data is moving back and forth between Host and FP several times a second without regularity(not a problem). If I add a couple more floats each direction, the communications goes to once every several seconds(too slow).
    Is there a more efficient method of transfering data back and forth between the Host and the FP system?
    Will LV8 provide faster communications between the host and the FP system? I may have the option of moving up.
    Thanks,
    Chris

    Chris, 
    Sounds like you might be maxing out the CPU on the Fieldpoint.
    Datasocket is considered a pretty slow method of moving data between hosts and targets as it has quite a bit of overhead assosciated with it.  There are several things you could do. One, instead of using a datasocket for each float you want to transfer (which I assume you are doing), try using an array of floats and use just one datasocket transfer for the whole array.  This is often quite a bit faster than calling a publish VI for many different variables.
    Also, as Xu mentioned, using a raw TCP connection would be the fastest way to move data.  I would recommend taking a look at the TCP examples that ship with LabVIEW to see how to effectively use these. 
    LabVIEW 8 introduced the shared variable, which when network enabled, makes data transfer very simple and is quite a bit faster than a comparable datasocket transfer.  While faster than datasocket, they are still slower than just flat out using a raw TCP connection, but they are much more flexible.  Also, the shared variables can fucntion in the RT fifo capacity and clean up your diagram quite a bit (while maintaining the RT fifo functionality).
    Hope this helps.
    --Paul Mandeltort
    Automotive and Industrial Communications Product Marketing

  • Make Code More Efficient

    I got this code to play some audio clips and it works alright. The only issue is that when I call the play method it lags the rest of my game pretty badly. Is there anything in the play method you guys think could be moved to the constructor to make it more efficient?
    package main;
    import java.io.*;
    import javax.sound.sampled.*;
    public class Sound
         private AudioFormat format;
        private byte[] samples;
        private String name;
         public Sound(String filename)
              name=filename;
              try
                AudioInputStream stream =AudioSystem.getAudioInputStream(new File("sounds/"+filename));
                format = stream.getFormat();
                samples = getSamples(stream);
            }catch (Exception e){System.out.println(e);}
         public byte[] getSamples()
            return samples;
        private byte[] getSamples(AudioInputStream audioStream)
            int length=(int)(audioStream.getFrameLength()*format.getFrameSize());
            byte[] samples = new byte[length];
            DataInputStream is = new DataInputStream(audioStream);
            try
                is.readFully(samples);
            }catch (Exception e){System.out.println(e);}
            return samples;
        public void play()
             InputStream stream =new ByteArrayInputStream(getSamples());
            int bufferSize = format.getFrameSize()*Math.round(format.getSampleRate() / 10);
            byte[] buffer = new byte[bufferSize];
            SourceDataLine line;
            try
                DataLine.Info info=new DataLine.Info(SourceDataLine.class, format);
                line=(SourceDataLine)AudioSystem.getLine(info);
                line.open(format, bufferSize);
            }catch (Exception e){System.out.println(e);return;}
            line.start();
            try
                int numBytesRead = 0;
                while (numBytesRead != -1)
                    numBytesRead =
                        stream.read(buffer, 0, buffer.length);
                    if (numBytesRead != -1)
                       line.write(buffer, 0, numBytesRead);
            }catch (Exception e){System.out.println(e);}
            line.drain();
            line.close();
        public String getName()
             return name;
    }

    I don't know much about the guts of flex, but I assume it's
    based on Java's design etc.
    Storing event.target.selectedItem in an objet should not be
    anymore efficient than calling event.target.selectedItem. The objet
    will simply be a pointer of sorts to event.target.selectedItem. At
    no point in the event.target.selectedItem call are you doing a
    search or something, so storing the result will not result in any
    big savings.
    Now, if you were doing something like
    array.findItem(something) 4 times, then yes, it would be to your
    advantage to store the data.
    Keep in mind that storing event.target.selectedItem in an
    object will probably break bindings....that may or may not be a
    problem. Objet doesn't support binding. There is a subclass of
    Object that does, but I forget which.
    Just a suggestion based on my knowledge of how data is stored
    in an object oriented language...this may not be the case in
    flex.

  • Disapearing Apple - Unknown Device - Making Sounds

    Hi all -
    So here is the deal. I have an 15G iPod with Dock Connector -- the one before the turnie wheel. I am now trying to install this iPod on my computer for the first time. I plug the iPod into the adaptor - adaptor into a working outlet and the apple appears then disappears -- I have pluged and unpluged -- I have tried different outlets -- there is no consistancey except that the apple SOMETIMES appears -- but mainly its blank. One time I got a battery bar with a ! triangle -- but that was just once.
    SECOND issue -- I have yet to configure this iPod because when I connect it to the USB port -- I get the USB Device Not Recognized. So I went to the Device Manager -- it's there but as an Unknown Device. The computer does not recognize the device ANYWHERE but in the Device Manager as an Unknown Device. Oh! And when I did the trouble shoot thing on the error message -- it said "No Drivers are installed for this device."
    Is there a driver I am missing? How do I get my iPod to charge and to be recognized?

    Oh! Oh! One more bit of information -- the iPod is getting warm when plugged in AND its making sounds.
    Thanks for any help!!!

  • Implicit Join or Explicit Join...which is more efficient???

    Which is more efficient?
    An IMPLICIT JOIN
    SELECT TableA.ColumnA1,
    TableB.ColumnB2
    FROM TableA,
    TableB
    WHERE TableA.ColumnA1 = TableB.ColumnB1
    Or....An EXPLICIT JOIN
    SELECT TableA.ColumnA1,
    TableB.ColumnB2
    FROM TableA
    INNER JOIN TableB
    ON TableA.ColumnA1 = TableB.ColumnB1
    I have to write a pretty extensive query and there will be many parts and I just want to try and make sure it is efficient as possible. Can I EXPLAIN this in SQL Navigator as well to find out???
    Thanks in advance for your review and hopeful for a reply.
    PSULionRP

    Alex Nuijten wrote:
    The Partition Outer Join is very handy, but it's an Oracle-ism - Not ANSI ...Ooh, "New thing learnt today" - check.
    but then again who cares? ;)Oracle roolz! *{;-D                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • A more efficient way to assure that a string value contains only numbers?

    Hi ,
    I'm using Oracle 9.2.0.6.
    I was curious to know if there was any way I could write a more efficient query to determine if a string value contains only numbers.
    Here's my current query. This SQL is from a sub query in a Join clause.
    select distinct cta.CUSTOMER_TRX_ID, to_number(cta.SALES_ORDER) SALES_ORDER
                from ra_customer_trx_lines_all cta
                where length(cta.SALES_ORDER) = 6
                and cta.SALES_ORDER is not null
                and substr(cta.SALES_ORDER,1,1) in('1','2','3','4','5','6','7','8','9','0')
                and substr(cta.SALES_ORDER,2,1) in('1','2','3','4','5','6','7','8','9','0')
                and substr(cta.SALES_ORDER,3,1) in('1','2','3','4','5','6','7','8','9','0')
                and substr(cta.SALES_ORDER,4,1) in('1','2','3','4','5','6','7','8','9','0')
                and substr(cta.SALES_ORDER,5,1) in('1','2','3','4','5','6','7','8','9','0')
                and substr(cta.SALES_ORDER,6,1) in('1','2','3','4','5','6','7','8','9','0')This is a string where I'm finding A-Z-a-z characters and '/' and '-' characters in all 6 positions, plus there are values that are longer than 6 characters. That's what the length(cta.SALES_ORDER) = 6 is for. Also, of course. some cells are NULL.
    So the question is, is there a more efficient way to screen out only the values in this field that are 6 character numbers or is what I have the best I can do?
    Thanks,

    I appreciate all of your very helpfull workarounds. The cost is a little better in all cases than my original where clause.
    To address the discussion that's popped up about design from this question, I can say a few things that should clear , at least, my situation up.
    First of all this custom quoting , purchase order , and sales order entry system WAS written by a bunch a of 'bad' coders who didn't document their work and then left. We don't even have an ER diagram
    The whole project that I'm only a small part of is literally trying to put Humpty Dumpty together again and then move it from a bad custom solution into Oracle Applications.
    We're rebuilding, documenting, and doing ETL. This is one of your prototypical projects from hell.
    It's a huge database project so we're taking small bites as a time. Hopefully, somewhere right before Armageddon hits, this thing will be complete.
    But until then,..., well,..., you know the drill.
    Thanks Again.

  • My iphone 4s is no longer making sound when i have an incoming call or message after installing ios7.... any help?

    My iphone 4s is no longer making sound when i have an incoming call or message after installing ios7.... any help?
    It still vibrates but no calling sounds or message sounds. It's not on mute and the speakers are working... I can hear music etc.
    Oh yeah no keypad noises either.

    Same thing has happened to me. I have tried every trick that's been posted here. I just ran out of options. Galaxy phone is starting to look better by the minute.

  • More-efficient keyboard

    Anyone have a way to get a better onscreen keyboard going than the QWERTY one that is stock on the iPhone? I love the FITALY (fitaly.com) keyboard on my old Palm, but that company says Apple won't let them do a system keyboard. One would like to think that a Dvorak or other non-18th century keyboard could be available among the international keyboards, but I don't find one.
    And yes, I've already tried the alternatives, e.g., TikiNotes, which takes me three times as long to type on than the Qwerty.
    If not, this would be a great suggestion for a new feature for Apple to incorporate.

    Just to let everybody know I am now 28 years old. I first learned how to type in typing class in junior high. I was using the Qwerty layout. The only nice thing I can say about the Qwerty layout is that it's available at any computer you want to use without any configuration.
    Then I looked online for a better way to type and more efficient. That's when I learned about Dvorak keyboard layout. This was about four years ago. I stuck with it for about two years. I felt my right hand was doing a lot more typing than my left hand. It felt too lopsided for me. But that's just my opinion. I went on the hunt for something better than Dvorak and I found the glorious Colemak keyboard layout.
    I have been typing with it ever since. My hands are a lot more comfortable and I can type faster now. It took me a month to actually get comfortable with the keyboard layout. If you actually go to this Java applet on Colemak's website.
    www.colemak.com/Compare
    You can just copy and paste a body of text and click on Calculate it will analyze the typing and compare the three different keyboard layouts. I just hope it becomes an ANSI standard like Dvorak has. I hope that happens in the future.
    I just want everybody to know there is a third option out there and its great. If ever Colemak goes away I will be going back to Dvorak. I will never learn the Qwerty keyboard layout ever again.
    Just wanted to give my two cents worth.

  • I just updated my iPhone 5 and Siri sounds more like a robot and I don't know what's wrong. My iPad Siri and my moms iPhone Siri sound like real people. Why doesn't my phone Siri sound like it should???

    Siri sounds more robotic on my iphone for the iOS 7 update.....  Help????

    Hello smartbud,
    The following article provides steps for changing the way Siri sounds.
    Can I change how Siri sounds?
    New female and male voices will be available initially in U.S. English, French, and German. You can change the gender by going to Settings > General > Siri > Voice Gender. Your iOS device initially uses a compact voice for Siri. iOS will automatically download and install a more natural-sounding voice when you first connect to power and a Wi-Fi network.
    iOS: About Siri
    http://support.apple.com/kb/HT4992
    Cheers,
    Allen

  • Camera Making Sound After Denim Update on Lumia 10...

    Camera of My Lumia 1020 Making Sound While taking Picture and Video After Installing Denim Update
    Have Sample Video Contains that Sound 
    Help Me
    Thank You

    Welcome to our community, heartlyjoshi. Sure! send us the video. Is for the Lumia Camera app or the Microsoft camera app (native built-in camera app)? BTW, is there any difference if you press and hold both the volume down and the power keys for 10-15 seconds? Does it happen regardless of the camera settings that you have set? We'll wait for your reply. 

  • My Ipod touch 2nd generation stopped making sound

    I have had my ipod for many years so I know it doesn't fit under this topic but none of them did... All of a sudden last night my ipod touch 2G just stopped making sound for music or notifications even with headphones. I restored it from itunes but no help, I reset from Ipod touch but no help, then I went to google & was able to get the sound back only with headphones. Can someone please tell me how I can get my sound back! My ipod is my life, I think I might die without it! jk lol

    It is not clear from your question if the restore was from backup or what. Have you tried restoring it to factory defaults/new iPod via iTUnes. Not from backup.

Maybe you are looking for

  • Save As - Settings and Filename Incrementer

    Hello All, I'm on CS5/CS6, i use a panel which i created in configurator. I have it run actions, menu items etc. All works great. Problem: I'm sick and tired of saving each open active image as JPG and incrementing the filename by 1.  I'm hoping some

  • Index for group by

    Oracle 10g: Does having index help when doing query by "group by"? For eg: select aa, count(*) from B group by aa

  • File sharing reports too many users connected

    SPECS: Mac Mini Core 2 Duo 2 GHz, 2G RAM, Mac OS X 10.6.4. Other users in office also running similar hardware and Mac OS X 10.6.4. CLARIFICATION: This Mini is used as a file server in a small law office (4 other workstations). It is running Mac OS X

  • Does the new iPhone 4s read text messages back to you?

    I had watch a video where the new iPhone 4s will read text message back to you. If that is true, how do you set the phone up to do this?

  • Printing problems with CS3 in Photoshop

    I have Photoshop CS3.  Just got a new HP Photosmart 7520 not good prints results so far. Need help printing asap. Need to know how to set the printer dialog box to give me best prints.  Appreciative of help ASAP  as I have a big job I need to complet