Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (539)
Games in Android Showcase (132)
games submitted by our members
Games in WIP (603)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  can't play 2 audioclips at same time?  (Read 3891 times)
0 Members and 1 Guest are viewing this topic.
Offline lefnire

Senior Newbie




Java games rock!


« Posted 2005-04-04 02:13:51 »

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?
Offline Vage

Senior Newbie




learning++;


« Reply #1 - Posted 2005-04-22 02:12:39 »

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?

Personally, you could strap me into a mech cockpit with 47 virtual HUD displays, two complex hand controls and foot pedals and I'd be grinning like the gamer freak I am.
Offline Vage

Senior Newbie




learning++;


« Reply #2 - Posted 2005-04-22 02:54:37 »

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!  Grin

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
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'.

Personally, you could strap me into a mech cockpit with 47 virtual HUD displays, two complex hand controls and foot pedals and I'd be grinning like the gamer freak I am.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline whome

Junior Devvie




Carte Noir Java


« Reply #3 - Posted 2005-07-12 06:40:11 »

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

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
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());
  }
}
Offline mori

Innocent Bystander




Java games rock!


« Reply #4 - Posted 2005-08-15 07:48:04 »

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

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
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);
    }
}
Offline ENC

Junior Devvie





« Reply #5 - Posted 2006-03-21 01:40:47 »

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

Threads maybe slower in performance but better in quality... *I THINK*

 Undecided
Offline Kova

Senior Devvie





« Reply #6 - Posted 2006-05-07 10:20:06 »

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.
Offline fletchergames

Senior Devvie





« Reply #7 - Posted 2006-05-08 01:56:35 »

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.
Offline Coinerson

Junior Devvie




Introducing the world's cutest zombie, Timmy


« Reply #8 - Posted 2006-06-07 19:37:12 »

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

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

then just do
1  
2  
sound boop = soundManager.getSound(pathToBoop);
soundManager.play(boop);


Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

rwatson462 (30 views)
2014-12-15 09:26:44

Mr.CodeIt (23 views)
2014-12-14 19:50:38

BurntPizza (49 views)
2014-12-09 22:41:13

BurntPizza (83 views)
2014-12-08 04:46:31

JscottyBieshaar (44 views)
2014-12-05 12:39:02

SHC (58 views)
2014-12-03 16:27:13

CopyableCougar4 (56 views)
2014-11-29 21:32:03

toopeicgaming1999 (122 views)
2014-11-26 15:22:04

toopeicgaming1999 (112 views)
2014-11-26 15:20:36

toopeicgaming1999 (32 views)
2014-11-26 15:20:08
Resources for WIP games
by kpars
2014-12-18 10:26:14

Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!