can't play 2 audioclips at same time?

AudioClip music=getAudioClip(getCodeBase(), “Music/song.midi”);
AudioClip sound=getAudioClip(getCodeBase(), “Sounds/sound.wav”);

sound.play(); //works, used when I press enter

music.play(); //works

but when I play them together, only music.play() gives me any sound. When I press enter, nothing happens most of the time and every so often sound.play() plays maybe half of the sound file. Any ideas?

Seems I’m having the same trouble. I’m guessing that the, quite limited, built-in AudioClip interface only allows one sound to be playing at a time. Time to go learn javax.sound. Anyone have any info on that, btw?

Ahh, well I found a few examples and hacked away at it until I came up with this. I recommend you replace your AudioClip system with it (or a variation on it). Enjoy! ;D


import java.io.*;
import java.net.URL;
import java.util.*;
import javax.sound.sampled.*;

public class SoundSystem
{
      private javax.sound.sampled.Line.Info lineInfo;
      private Vector afs;
      private Vector sizes;
      private Vector infos;
      private Vector audios;
      private int num = 0;

      private HashMap map;

      public SoundSystem()
      {
            afs = new Vector();
            sizes = new Vector();
            infos = new Vector();
            audios = new Vector();
            map = new HashMap();
      }

      public void addClip(String s)
      {
            try{
                  URL url = getClass().getResource(s);
                  //InputStream inputstream = url.openStream();
                  AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(loadStream(url.openStream()));
                  AudioFormat af = audioInputStream.getFormat();
                  int size = (int) (af.getFrameSize() * audioInputStream.getFrameLength());
                  byte[] audio = new byte[size];
                  DataLine.Info info = new DataLine.Info(Clip.class, af, size);
                  audioInputStream.read(audio, 0, size);

                  afs.add(af);
                  sizes.add(new Integer(size));
                  infos.add(info);
                  audios.add(audio);

                  map.put(s, (Object)new Integer(num));

                  num++;
            } catch(UnsupportedAudioFileException e) {
                  return;
            } catch(IOException e) {
                  return;
            }
      }

      public void addAllClips(final String ext) // EX: ".wav"
      {
            File dir = new File(".");
          FilenameFilter filter = new FilenameFilter() {
              public boolean accept(File dir, String name) {
                  return name.endsWith(ext);
              }
          };
          String[] children = dir.list(filter);

          if (children != null)
          {
              for (int i = 0; i < children.length; i++)
              {
                  addClip(children[i]);
              }
          }
      }

      private ByteArrayInputStream loadStream(InputStream inputstream) throws IOException
      {
            ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
            byte data[] = new byte[1024];
            for(int i = inputstream.read(data); i != -1; i = inputstream.read(data))
            bytearrayoutputstream.write(data, 0, i);

            inputstream.close();
            bytearrayoutputstream.close();
            data = bytearrayoutputstream.toByteArray();
            return new ByteArrayInputStream(data);
      }

      public void playSound(int x) throws UnsupportedAudioFileException, LineUnavailableException
      {
            if(x > num)
            {
                  System.out.println("playSound: sample nr["+x+"] is not available");
            }
            else
            {
                  Clip clip = (Clip) AudioSystem.getLine((DataLine.Info)infos.elementAt(x));
                  clip.open((AudioFormat)afs.elementAt(x), (byte[])audios.elementAt(x), 0, ((Integer)sizes.elementAt(x)).intValue());
                  clip.start();
            }
      }

      public void loopSound(int x) throws UnsupportedAudioFileException, LineUnavailableException
      {
            if(x > num)
            {
                  System.out.println("loopSound: sample nr["+x+"] is not available");
            }
            else
            {
                  Clip clip = (Clip) AudioSystem.getLine((DataLine.Info)infos.elementAt(x));
                  clip.open((AudioFormat)afs.elementAt(x), (byte[])audios.elementAt(x), 0, ((Integer)sizes.elementAt(x)).intValue());
                  clip.start();
                  clip.loop(Clip.LOOP_CONTINUOUSLY);
            }
      }

      public void stopSound(int x) throws UnsupportedAudioFileException, LineUnavailableException
      {
            if(x > num)
            {
                  System.out.println("stopSound: sample nr["+x+"] is not available");
            }
            else
            {
                  Clip clip = (Clip) AudioSystem.getLine((DataLine.Info)infos.elementAt(x));
                  clip.open((AudioFormat)afs.elementAt(x), (byte[])audios.elementAt(x), 0, ((Integer)sizes.elementAt(x)).intValue());
                  clip.stop();
            }
      }

      public void Play(String s)
      {
            try{
                  Object obj = map.get(s);
                  if(obj == null)
                        return;
                  int x = ((Integer)obj).intValue();
                  playSound(x);
            } catch(UnsupportedAudioFileException e) {
                  return;
            } catch(LineUnavailableException e) {
                  return;
            }
      }

      public void Loop(String s)
      {
            try{
                  Object obj = map.get(s);
                  if(obj == null)
                        return;
                  int x = ((Integer)obj).intValue();
                  loopSound(x);
            } catch(UnsupportedAudioFileException e) {
                  return;
            } catch(LineUnavailableException e) {
                  return;
            }
      }

      public void Stop(String s)
      {
            try{
                  Object obj = map.get(s);
                  if(obj == null)
                        return;
                  int x = ((Integer)obj).intValue();
                  stopSound(x);
            } catch(UnsupportedAudioFileException e) {
                  return;
            } catch(LineUnavailableException e) {
                  return;
            }
      }
}

EDIT: Added ‘addAllClips’.

I modified example code a bit. Its quite easy to create a audiowrapper class to give better interface for clips.


import java.io.*;
import java.net.URL;
import java.util.*;
import javax.sound.sampled.*;

/**
 * Play .wav audio files
 */
public class AudioWrapper  {
      private AudioFormat af;
      private int size;
      private DataLine.Info info;
      private byte[] data;
      // int size = data.length;
      private Clip clip;

      public AudioWrapper() { }

      public void play() throws UnsupportedAudioFileException, LineUnavailableException {
         if (clip != null)
            stop();
         clip = (Clip)AudioSystem.getLine(info);
         clip.open(af, data, 0, data.length);
         clip.start();

         // clip.start();
         // clip.loop(Clip.LOOP_CONTINUOUSLY);
      }

      public void stop() throws UnsupportedAudioFileException, LineUnavailableException {
         if (clip != null)
           clip.stop();
         clip = null;         
      }

   public void load(String fileName) throws Exception {
      // dispose previous clip if was loaded
      try { if (clip != null) clip.stop(); } catch (Exception ex) { }
      this.af  = null;
      this.info = null;
      this.data = null;
      this.clip = null;

      // We read all bytes to ByteInputStream first then use it 
      // as a source stream. We probably could stream directly
      // from files but then must use FIS opened for longer time.
      // TODO: change to URL-stream to support file+jar+web sources (see previous example)
      FileInputStream fis = new FileInputStream(fileName);
      InputStream is = loadStream(fis);
      AudioInputStream ais = AudioSystem.getAudioInputStream(is);
      fis.close();

      this.af   = ais.getFormat();
      int size = (int)(this.af.getFrameSize() * ais.getFrameLength());
      this.info = new DataLine.Info(Clip.class, this.af, size);
      this.data = new byte[size];
      ais.read(this.data, 0, this.data.length);
   }

   // load inputstream to ByteArrayInputStream
   private ByteArrayInputStream loadStream(InputStream is) throws IOException {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      byte data[] = new byte[1024];
      for(int i = is.read(data); i != -1; i = is.read(data))
         baos.write(data, 0, i);
      baos.close();
      return new ByteArrayInputStream(baos.toByteArray());
  }
}

Hello. I used the above code like bottom code.
But, I cannot hear 2 sounds at the same time. I can hear 005.wav but I cannot hear 006.wav.
give me some advice, please


public class AudioWrapperTest extends JFrame {
    public AudioWrapperTest() {
        AudioWrapper aw1 = new AudioWrapper();
        AudioWrapper aw2 = new AudioWrapper();
        
        try {
            aw1.load("005.wav");
            aw2.load("009.wav");
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        try {
            aw1.play();
            aw2.play();
        } catch (UnsupportedAudioFileException e1) {
            e1.printStackTrace();
        } catch (LineUnavailableException e1) {
            e1.printStackTrace();
        }
    }

    public static void main(String[] args) {
        AudioWrapperTest frame = new AudioWrapperTest();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

Hi … I am quite new here… but maybe you can try using Threads?

Threads maybe slower in performance but better in quality… I THINK

:-\

I’m also a n00b… but using Threads … sounds awfull. Maybe one thread for all sounds but creating a thread per audio file for playing? That’s surely not the way it is done.

If you’re still having problems, see my tutorial: http://www.cowgodgames.com/articles/jgptutorial/ch01.5.php. I never finished my tutorial, but I did post stuff about music and sound.

The tutorial’s code (1.19 MB) is at http://www.cowgodgames.com/downloads/javatutorial.zip.

You make a sound manager and thread pool.

http://rapidshare.de/files/22475672/Sound.zip.html

In your main manager class you create a new sound manager with an audio format similar to

AudioFormat(44100, 16, 2, true, false)

(Stereo)

then just do

sound boop = soundManager.getSound(pathToBoop);
soundManager.play(boop);