Play more than one sound

I want to write a program that can play more tha one music file(wav).
I have used threat and mixer(javax.sound.sample.*) but Ican't do this.
Help me please !!!!!!
And show me some code example about mixer if can
Thank you very much !!!!!!!!

Here is a simple solution for playing more than one sound at the time. It uses two classes where the first is a thread that plays a sound, and the second is a "container" that loads and stores your sounds.
SoundThread.java
import javax.sound.sampled.*;
public class SoundThread extends Thread
    private Clip soundClip = null;
    private int soundIndex = 0;
    private int loopCount = 0;
    private boolean donePlaying = false;
     * Constructor
     * @param acClip Clip The sound clip.
     * @param index int The index of the sound (so that the correct thread can be found when a sound should be stopped.)
    public SoundThread( Clip clip, int index )
        soundIndex = index;
        soundClip = clip;
        soundClip.stop();
        soundClip.flush();
        soundClip.setFramePosition( 0 );
        soundClip.setLoopPoints(0, -1);
        setPriority(Thread.MIN_PRIORITY);
      * Tell the thread to play the sound once and start playback.
     public void playSound()
         loopCount = 0;
         start();
     * Tell the thread to loop the sound and start playing.
    public void loopSound()
        loopCount = Clip.LOOP_CONTINUOUSLY;
        start();
     * Stop playing the sound in this thread.
    public void stopSound()
        soundClip.stop();
        soundClip.flush();
        soundClip.setFramePosition( 0 );
        donePlaying = true;
     * Get the index of this particular sound clip.
     * @return int The index.
    public int getSoundIndex()
        return soundIndex;
     * Has the sound finished playing?
     * @return boolean True iff it's done.
    public boolean isDonePlaying()
        return donePlaying;
     * Play the sound in the thread.
    public void run()
        soundClip.loop( loopCount );
        donePlaying = true;
SoundPlayer.java
import javax.sound.sampled.*;
import java.net.URL;
import java.util.LinkedList;
import java.util.Vector;
public class SoundPlayer
    private Vector<Clip> clipList = null;
    private LinkedList<SoundThread> playerList = null;
     * Constructor
     * Initializes the list of sounds being played and the list of sound clips.
    public SoundPlayer()
        playerList = new LinkedList<SoundThread>();
        clipList = new Vector<Clip>();
     * Add a sound to the list of sounds in the player.
     * @param fileName String The file name (including sub-directories) to the sound.
     * @return int The index of the sound in the list, -1 if it could not be added.
     * @throws UnsupportedAudioFileException The format of the file is unrecognized.
     * @throws LineUnavailableException No output found.
     * @throws IOException Most likely the file could not be found.
    public int setSound( String fileName ) throws Exception
        Clip theClip = getClip(getURL(fileName));
        if ( clipList.add(theClip) == false )
            theClip.flush();
            theClip.close();
            return -1;
        return clipList.indexOf(theClip);
     * Get a reference to a specific sound.
     * @param soundIndex int The internal index of the sound.
     * @return Clip A reference to the sound.
    public Clip getSound( int soundIndex )
        return clipList.elementAt(soundIndex);
     * Play a sound.
     * @param soundIndex int The internal index of the sound to be played.
    public void play( int soundIndex )
        SoundThread player = new SoundThread(getSound(soundIndex), soundIndex);
        playerList.add(player);
        player.playSound();
     * Stop playing all sounds.
    public void stop()
        while ( playerList.isEmpty() == false )
            SoundThread player = playerList.removeFirst();
            player.stopSound();
            player = null;
     * Stop playing a specific looping sound.
     * @param soundIndex int The internal index of the sound to be stopped.
    public void stop( int soundIndex )
        // Create a temporary list for sounds that are playing and should continue to play.
        LinkedList<SoundThread> tempList = new LinkedList<SoundThread>();
        while ( playerList.isEmpty() == false )
            SoundThread player = playerList.removeFirst();
            // This is the sound clip that should be stopped.
            if ( player.getSoundIndex() == soundIndex )
                player.stopSound();
            // Remove any threads that are done playing.
            if ( player.isDonePlaying() )
                player = null;
            // Add all other threads to the temporary list.
            else
                tempList.add(player);
        // Update the player list to the new list.
        playerList = tempList;
     * Loop a sound.
     * @param soundIndex int The internal index of the sound to be played.
    public void loop( int soundIndex )
        SoundThread player = new SoundThread(getSound(soundIndex), soundIndex);
        playerList.add(player);
        player.loopSound();
     * Get an URL to a file inside the current jar archive.
     * @param fileName String The file name, including subdierctory information if applicable.
     * @return URL An URL to the file.
    public URL getURL( String fileName )
        return this.getClass().getClassLoader().getResource(fileName);
     * Load a sound clip from an URL.
     * @param urlResource URL An URL to the sound file.
     * @return Clip A reference to the sound.
    public Clip getClip( URL urlResource ) throws Exception
        Clip theSound = null;
        try
            // Open a stream to the sound.
            AudioInputStream ais = AudioSystem.getAudioInputStream( urlResource );
            // Get the format of the sound clip.
            AudioFormat af = ais.getFormat();
            // Create a line for the sound clip.
            DataLine.Info dli = new DataLine.Info( Clip.class, af, AudioSystem.NOT_SPECIFIED );
            // If the format of the clip is not supported directly then try to transcode it to PCM.
            if ( !AudioSystem.isLineSupported( dli ) )
                // Create a new PCM audio format for the clip.
                AudioFormat pcm = new AudioFormat( af.getSampleRate(), 16, af.getChannels(), true, false );
                // Open a stream to the sound using the new format.
                ais = AudioSystem.getAudioInputStream( pcm, ais );
                // Read the format of the clip.
                af = ais.getFormat();
                // Create a new line for the sound clip.
                dli = new DataLine.Info( Clip.class, af );
            // Create the clip, open it, and read its entire contents.
            theSound = ( Clip )AudioSystem.getLine( dli );
            theSound.open( ais );
            theSound.drain();
        catch( Exception ex )
            throw new Exception(urlResource.toString() + "\n" + ex.getMessage());
        // Return a reference to the sound clip.
        return theSound;
      * Destructor
      * Release memory used by loaded sounds.
     public void dispose()
         stop();
         for ( int i = 0; i < clipList.size(); i++ )
             Clip c = clipList.elementAt(i);
             c.stop();
             c.flush();
             c.close();
         clipList = null;
}Here is an example of how to use these classes:
    public static final void main( String[] args )
        try
            SoundPlayer sp = new SoundPlayer();
            int clip1 = sp.setSound("clip1.wav");
            int clip2 = sp.setSound("mySounds/clip2.aiff");
            int clip3 = sp.setSound("clip3.au");
            sp.loop( clip1 );
            Thread.sleep( 5000 );
            sp.play( clip2 );
            Thread.sleep( 1000 );
            sp.play( clip3 );
            Thread.sleep( 4000 );
            sp.stop( clip1 );
            sp.dispose();
        catch( Exception ex )
            ex.printStackTrace();
...The main weakness of this solution is that if you've got two or more instances of the same sound looping and want only one of them to stop, then, sorry, they're all stopped. There are probably more weak points but these two classes have worked well for my purposes so far.
Hope this solves at least part of your problem.
Hjalti
PS. I have assembled these two classes from code snippets and examples found here and there on the Web so I'm in no way claiming to be the original author of all of this code. Unfortunately I haven't registered where it all came from so I'm unable to give credit where credit is due.

Similar Messages

  • OSS doesn't play more than 1 sound at the same time [SOLVED]

    Hello,
    I use OSS to replace ALSA, it used to work properly here. Today I noticed that I can't play more than one sound at the same time, something which I used to be able to do.
    Also, ossxmix doesn't operate properly (I can't control the volume of a specific program).
    Looks like a permissions issue, because /dev/dsp and /dev/oss are created as root and other users get Permission Denied.
    Any ideas how to fix it? My sound card is an AC'97 onboard.
    Thanks!
    EDIT: Solved by pacman -R oss, rm -rf /usr/lib/oss then pacman -S oss. Seems to have worked.
    Last edited by Renan Birck (2009-01-02 23:06:35)

    Hello Angela,
    Have you tried resetting the iPod yet to see if that makes a difference?  To do this, press and hold both the Select (Center) and Menu buttons together long enough for the Apple logo to appear.
    If that doesn't work, a restore of the iPod via iTunes may be in order.
    B-rock

  • HT1459 After updating ITunes, it, ITunes started loosing my music files and stopped playing more than one song at a time.What now?

    After updating ITunes, it, ITunes started loosing my music files and stopped playing more than one song at a time also there would be duplicate songs in the same folders.What now?

    Sound like something messed up somehow. Maybe you can consider reinstalling the drivers again? @28.86.2.0

  • Play more than one auido files

    Is it possible, in j2me, to play more than one auido files at the same time?
    I want to play an audio file as my background music and player some other files as sound effect.

    http://developer.sonyericsson.com/site/global/techsupport/tipstrickscode/java/p_using_simultaneous_sounds.jsp

  • Projector that plays more than one movie

    How can I make one projector play more than one movie? If the movies are protected, can the projector still play them? How can I link them? Thanks for your help.

    Hi Norman,
    I’ll elaborate on Sean’s reply.
    As Sean mentioned you can use:
    _movie.go("markerName", "MovieName")
    To jump to the marker named ‘Markername’ in a movie called ‘MovieName’.
    I tend to still use the verbose syntax
    go to "markerName" of movie "MovieName"
    If you had:
    go to movie "MovieName"
    you’d jump to the start of the movie (frame 1)
    you could use:
    go to movie "MovieName.dir"
    but the '.dir' is not needed and if you create a protected DXR or DCR, the statement (without the movie extension) would work.
    Now, if you want to avoid writing a unique behavior for every link you’re creating, I’ve got a tutorial that describes how to do it at:
    http://www.deansdirectortutorials.com/Lingo/paramDialog.htm
    The above uses property variables and a parameter dialog box. It does require some understanding of programming (not too much though).
    If you have D11.5, in the Library Palette, in the ‘Controls’, category, there is a ‘Jump to Movie Button’ behavior. This behavior can be dragged and dropped onto a sprite and then you can type in the marker name and movie name in a parameter dialog box to set the link for the sprite. I say D11.5 because while earlier versions of Director have this behavior, there is a small error (easily fixed) that makes the marker jumping part non-functional. Anyway, my behavior in my tut site does the same thing.
    Dean
    Director Lecturer / Consultant / Director Enthusiast
    http://www.deansdirectortutorials.com/
    http://www.multimediacreative.com.au

  • Play more than one song at a time

    The apple tv won't play more than one song on my playlist. And why can't there be playlists under "Music" and well as "Computer"?

    WLFehrs wrote:
    This has been a condition since day one.  The "working" icon just keeps going and it doesn't move on to the next song.  I've tried using the random play option as well to no avail.
    Is this when trying to stream content from iTunes using the Computers icons and Music submenu? I assume  the same happens when you try to play from the internet using the main Music icon too?  Is it only on Shuffle or when playing an album?
    What about movie rentals from itunes Store  - will they play ok?
    WLFehrs wrote:
    Connectivity isn't a problem, my home network has the latest tech and the Apple TV is within 15 feet anyway. 
    While that seems logical don't entirely discount it - issues like this are incredibly frustrating to pin down to which component on the network is causing the problem  - your old AppleTV worked (with Windows 8?) so this makes the newer model the more likely culprit I would agree.
    Whenever there are issues like this, if you have not done so:
    1 - Unpower AppleTV, router and restart along with the computer.
    2 - If connecting via wifi and it is feasible to test with ethernet do so to exclude wifi as the problem somewhere in the chain.
    3 - If streaming from iTunes check the computer is not going to sleep - power saving with hard drives spinning down could potentially cause a 'timeout' issue for access and worth temporarily disabling to test.
    4 - Temporarily disable any security software (firewall/port blocking) on the computer or check if it is detecting AppleTV repeated connections as an unknown intrusion threat.
    5 - Reset AppleTV and set it up again from the Settings menu.
    6 - Restore AppleTV using iTunes and a microUSB to USB connection:
    Apple TV (2nd and 3rd generation): Restoring your Apple TV
    7 - Assuming under warranty, take it to an Apple store and see if you can get a replacement.  It may be faulty.
    As I said these issues can be very tricky to pin down and it can be a process of elimination.
    I had issues last year with connection problems - I thought it was an itunes update as there were threads elsewhere about multiple connections being established.  One day I restarted my router and the problem was fixed.  A few years ago my AppleTV1s were hanging after extended use - it was the Netgear router overheating ( aknown fault with that particular model).
    AC

  • ITunes will no longer play more than one song in a row

    I upgraded my iTunes and it seemed to be working fine. But all of a sudden I cannot get my libraray or any playlist ti play more than one song at a time automatically. It just stops after each song. Any ideas?
    Thanks
      Windows XP  

    But all of a sudden I cannot get my libraray or any playlist ti play more than one song at a time automatically. It just stops after each song.
    head into your itunes main library window. are all the little boxes to the left of your tracks unchecked?
    is so, hold down Ctrl and click on one of those boxes to recheck all the songs. (this may take a little time.)
    do you get continuous play once all the songs are rechecked?

  • Applet Videoplayer, able to play more than one movie

    Hallo,
    I am looking for a sample applet that works as a video player.
    I have tested the sample code provided by JMF, but there is no
    example that allows to replace the current movie with a new movie.
    In other words, I am looking for a applet program, which allows me
    to give in new movie adresses and so to reload the player with a
    new film.
    Thanks in advance
    mk

    I do not know if I am using a flvplayback component. I am using "import video" - using the URL. I am using a skin provided in flash. Is that a flvplayback component?
    I am not using flv if that matters (using h.264 - f4v I believe it is called).
    Where do I put this code you have provided? I find this the most confusing part of Flash - I never know where to insert provided code.
    Does it go in the original swf file (if so - where?), or does it go in the main swf (where all the swfs would play one after the other) - and if so, where exactly?
    I don't really get how I load more than one swf in a main file to begin with either...... as I said - when I try - I get a loop of two frames - like an animation - it's not playing the full videos (with page setup), and then moving onto the next one. This is where I get lost - and tutorials are not being very helpful (as they deal strictly with video - often not continuous play, but user controlled, OR, they provide code with no directions where to actually put things).
    Do I import the swf into the master swf? Or just use code to tell it where the files are??
    Feel free to use small words and speak slowly. I haven't used this program before, and it seems very different from building a website with, say CSS for example (something I DO know how to do). I appreciate specific directions (or tutorials that provide the specific directions that address this question....)
    BTW - and overall ty for your continued assistance. If I had more time, I would pick up a book and work through things slowly - but I need to get at least a few things working to hand in the art piece for school - doesn't need to be finished, but needs to at least demonstrate a few of the website's overall features. I fully intend to do more detailed learning later to finish the piece outside of class.

  • IPad - with movie clips - how can I play more than one at a time?

    iPad2.  I post short movie clips via iTunes to the Photo catagory.  I can play each of these clips by selecting the clip and pressing the start arrow, only the selected clip will play.  How can I select a group of movie clips and have them play with only one selection.  Like a "slide show" but for movie clips???

    More than one contacts at a time

  • External MIDI device, can't get more than one sound, Logic Express 9 & Korg N364

    Hi, I just beginning to use Logic. I trying to get Logic Express 9 to work with and use my Korg N364 keyboard/workstation as an external MIDI device. I can only get one sound at a time even though I create multiple tracks and assign different programs (or patches) to them.
      Each time I do the following: I add a new external MIDI track, change the Channel to new number, put a check in the Program box ( as well as the Volume & Pan), and choose a instrument or patch from the Program drop down menu. What happens, though, it changes the sound to that instrument alright, but ALL THE PREVIOUS EXTERNAL MIDI TRACKS HAVE THE SAME SOUND NOW. I've followed the tutorials I found on the web and it seems like I'm doing everything correct in Logic. I hooked up the MIDI cables, added a new device and connected virtual cables in the MIDI studio window of my Mac OS, and have added the proper Korg multi instrument in the environment window of Logic and "un-slashed" the 16 channels. I get the sounds from the Korg no problem, it's just that I can only assign one sound and no more to the external MIDI tracks. Is there something in my Korg I need to do? Or am I missing something in Logic?

    It's not Logic, it's how you have the Korg setup.
    I'm not familiar with that model but it is a workstation so I'm pretty sure you can set it to a "Multi" mode.
    Right now you are running it in single patch mode.
    In single patch mode only one sound is available on a single MIDI channel, your Korg probably has a Multi or Combi mode, this is where multiple sounds can be played, each sound has to have it's own MIDI channel.
    You will need to set this up on the Korg first.

  • XFi Can't Handle more than one sound at a time?!?

    I bought an XFi Elite Pro and it was working great. Now, however, it will only handle one sound at a time. For example, if I'm playing a song in iTunes and windows makes a sound, the itunes song cuts out, the windows sound plays, then itunes abruptly cuts back in. Same thing in games. If I'm playing Warcraft the sound will cut out if Windows makes some kind of a sound.
    How do I get my card back to being able to play multiple sounds/music simultaneously? I'm running Vista Ultimate on a Quad Core system with 4 gigs of RAM.

    Sound like something messed up somehow. Maybe you can consider reinstalling the drivers again? @28.86.2.0

  • Audio issue on ipad - won't play more than on sound at a time.

    I have a module with some background music, voice overs and various sound efx.
    On the ipad only one sound will play at a time. So if there is background music it disappears when the voice over comes in and if there's a sound effect on top of voice over there is a disruption to the voice over.
    It seems to work fine on desktop, laptop and even android devices.
    Is this a known issue? Anybody have a solution or workaround?
    The only thing I can think of is having all the audio pre-mixed.
    any help would be appreciated.
    thanks
    morgan

    Hi there,
    Avoid overlapping audio in the project. If at all you need overlapping audio, read the article Adobe Captivate audio for iPad.
    If you use overlapping audio, then please check this article from the help file on 'best practices for creating projects for I-pads':
    http://helpx.adobe.com/content/help/en/captivate/using/publish-projects-html5-files.html
    Thanks.

  • How do I get iTunes to play more than one song at a time on my PC?

    I have selected all in a playlist, then click the play button. It plays only the first song in the playlist. How do I get it to play all of those selected?

    My iTunes is doing the same thing: when I select a playlist and hit "play," if shuffle is turned on, iTunes plays only one song and then stops. If shuffle is turned off, it plays just fine (one song after another, in order).
    Select the songs, right click - get info.
    Select the Options tab and Uncheck *Skip when shuffling*.
    Also, when I hit shuffle, it doesn't rearrange the songs in the playlist like it's supposed to.
    If you are sorting on any column besides the very first on before the track name, the songs will stay displayed in that same sort order.
    When you play the playlist, the list will jump around and be shuffled.
    If you are sorting on the very first column, the list will be displayed in the shuffled order and play in that order.

  • Why won't my iTunes 11 play more than one song at a time?

    Songs appear in "Up Next", but at the end of the song being played they disappear and nothing gets played next. This makes iTunes useless as a music player. Please help.

    My iTunes is doing the same thing: when I select a playlist and hit "play," if shuffle is turned on, iTunes plays only one song and then stops. If shuffle is turned off, it plays just fine (one song after another, in order).
    Select the songs, right click - get info.
    Select the Options tab and Uncheck *Skip when shuffling*.
    Also, when I hit shuffle, it doesn't rearrange the songs in the playlist like it's supposed to.
    If you are sorting on any column besides the very first on before the track name, the songs will stay displayed in that same sort order.
    When you play the playlist, the list will jump around and be shuffled.
    If you are sorting on the very first column, the list will be displayed in the shuffled order and play in that order.

  • Play more than one genre at a time?

    Is there a way to play 2 or more genres at a time to avoid shuffling all genres?
    for example i want to be in the mood for pop and r&b with no classic or jazz in the mix!

    Yes, put them into an *On-The-Go Playlist.*
    (For anyone who doesn't know how to do this) scroll to the genre list and when you highlight the first of your chosen genres, press-and-hold the centre (select) button until the display flashes. Now scroll to the other genre and press-an-hold this one. Hey presto, both genres are now in the *On-The-Go Playlist.* As well as playing the list, you can save it or delete it when you've finished with it.
    Phil

Maybe you are looking for

  • F150 Dunning notice not generated

    hi, Scenario: My client has created Employees as Vendors and when loan has been sanctioned to the employees. After some time when he is generating the dunning notice in F150, the transaction data is not picked for dunning and no dunning notice is gen

  • How can i insert more than one record a time in a JSP page?

    Hi experts, I'm working with JDeveloper version 3.2 application server 9i. I want to insert more than 1 record using a jsp page and then perform a commit at the end. do you can help me with this problem/challenge? Thank you, Regards, Mario

  • Cannot connect to Cisco WiFi...?  Anyone else?

    I cannot for the life of my connect to my office Cisco 1252 Lightweight AP. I have tested with virtually every setting, including a basic broadcasted SSID of "test" with no security. I always get a "cannot connect to the wireless network" error messa

  • How to reactivate the welcome screen of indesign?

    how to reactivate the welcome screen of indesign?

  • HFM Disaster Recovery

    We have realtime copying happening from the PROD server disk array to the PREPROD server disk array for the Database servers, the FDM server and the Essbase servers.  Now my question is, can the PREPROD server mentioned above which is getting the dat