views:

86

answers:

4

Hi all, I have two questions - (1) How to play small sound clips, e.g. saucer flying, bullets shooting, things getting hit with bullets, etc. Very short, but real-time, sounds. I like the old arcade sounds, so they need not be largess .wav's. I want to run these in as little code as possible. Which leads to my second question... (2) Does anyone know where to find these sound clips.

A little note, I've seen some of the answers here, and they seem incomplete. If you have a straight, generic code, that's great! I know very little about sounds as I don't normally get this far in my game writing.

Thanks for any and all information - I do appreciate it!

+1  A: 

I don't know about the API part, but for the sounds try www.sounddogs.com

Michael Rodrigues
Thanks Michael, but these are not free. (only for evaluation purposes).
Scott Foulk
+1  A: 

Using javax.sound, it's possible to have simple sound effect.

See Produce special sound effect


EDIT: Using a Thread (or not)

import javax.sound.sampled.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class AppWithSound2 extends JFrame implements ActionListener {
  JButton b1;
  JButton b2;

  private static final long serialVersionUID = 1L;

  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        AppWithSound2 app = new AppWithSound2();
        app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        app.startApp();
      }
    });
  }

  public AppWithSound2() {
    initGUI();
  }

  private void startApp() {
    setVisible(true);
  }

  private void initGUI() {
    setLayout(new FlowLayout());
    setSize(300, 200);
    b1 = new JButton("Sound with no thread");
    b2 = new JButton("Sound with thread");
    b1.addActionListener(this);
    b2.addActionListener(this);
    add(b1);
    add(b2);
  }

  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == b1) {
      LaserSound.laser();
    }
    if (e.getSource() == b2) {
      new LaserSound().start();
    }
  }
}

class LaserSound extends Thread {

  public void run() {
    LaserSound.laser();
  }

  public static void laser() {
    int repeat = 10;
    try {
      AudioFormat af = new AudioFormat(8000f, // sampleRate
          8, // sampleSizeInBits
          1, // channels
          true, // signed
          false); // bigEndian
      SourceDataLine sdl;
      sdl = AudioSystem.getSourceDataLine(af);
      sdl.open(af);
      sdl.start();

      byte[] buf = new byte[1];
      int step;

      for (int j = 0; j < repeat; j++) {
        step = 10;
        for (int i = 0; i < 2000; i++) {
          buf[0] = ((i % step > 0) ? 32 : (byte) 0);

          if (i % 250 == 0)
            step += 2;
          sdl.write(buf, 0, 1);
        }
        Thread.sleep(200);
      }
      sdl.drain();
      sdl.stop();
      sdl.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
RealHowTo
Wow - this looks like something I really need. I have not actually run the code, but it is creating it's own sounds and it's in an application, not an applet...
Scott Foulk
Well, unfortunately the sounds seem to stop the action whenever called. I gotta say I really love that old time arcade sound, simple as it is, I'm very nostalgic...I'd love to get it into my game...
Scott Foulk
I believe that you need to produce the sound in its own Thread.
RealHowTo
Hmmm. Okay - I will try. Thanks again...
Scott Foulk
Okay, but embarrassingly I ask - how do I do that (I did try, btw)? I got slowed down on each click still, then all hell broke loose because I apparently do not know how to do threads.
Scott Foulk
See my edit for an example with or without thread
RealHowTo
Thanks for this - I am now playing with the sounds to figure out what is going on, and I've been able to expand the bang iinto more of an explosion, for multiple use.I tested it pretty well and it works great!I will be visiting your site too since I see that you are in the know on Java Sound. Thanks again. The awesome 'old-time' arcade sounds are great!
Scott Foulk
Also, btw, I am now better educated on Java Threads thanks to you. See you on your website!
Scott Foulk
A: 

Clip interface is the easiest way to play small sounds in your app. Here is an example. If you want to play anything other than wav, use MP3SPI or VorbisSPI from JavaZOOM.

tulskiy
Thanks tulskiy, but I'm looking for Java applications.
Scott Foulk
@Scott Foulk: this is java!
tulskiy
Well Tulskiy, you are right - sorry I saw applet and assumed it was for applets only. I inserted the code you linked to after my code below (see below) did not work. It seemed to work for a second, but the sounds only came out every 2nd or third time the call was made. Shortly thereafter, it stops completely.It's like a fricking nightmare to get the Java sounds to work, at least more than once...
Scott Foulk
@Scott Foulk: Are you creating the Clip on every call or just call `start()` or `loop()` on an existing Clip? I wrote a full-featured audio player in java, I know it's hard. But it was designed for playing simple sounds, so your problem should be easy to fix.
tulskiy
I only start() the clip and then end it, but the sounds work only a couple of times. It's a game and I need to run clips on demand (e.g. bullet sounds), and sometimes one after the other (fast). I'd like to run background music or sounds, but just to get a clip working properly hasn't happened. My ideal would be to create a clip once, then run it as needed. I could use the loop() too if it will work.Your help is greatly appreciated tulskiy.
Scott Foulk
A: 

Okay guys - here's what i came up with while I was waiting. I thought I had set the Stack Overflow settings to email me when my question was answered, so I thought I received no answers yet. Thus, I continued on by myself. Here's what I found that worked.

(1) Create the instance by using this:

private PlaySounds lasershot = new PlaySounds("snd/lasershot.wav");
private PlaySounds test = new PlaySounds("snd/cash_register.au");

(2) And create the file PlaySounds.java (or whatever you like) import java.io.; import javax.media.;

public class PlaySounds { private Player player; private File file;

   // Create a player for each of the sound files
   public PlaySounds(String filename)
   {
       file = new File(filename);
       createPlayer();
   }

   private void createPlayer()
   {
       if ( file == null )
           return;

       try 
       {
           // create a new player and add listener
           player = Manager.createPlayer( file.toURI().toURL() );
           //player.addController( (Controller) new EventHandler(player, null, null, null) );
          // player.start();  // start player
       }
       catch ( Exception e )
       {
       }
   }

    public void playSound()
    {
        // start player
        player.start();
        // Clear player
        player = null;  
        // Re-create player
        createPlayer();
    }

} // End of file PlaySounds.java


(3) To use, insert these where you want the sounds:

 lasershot.playSound();
 test.playSound();

This was the shortest / sweetest I found. Very easy to use, and plays both .au AND .wav files.

I do appreciate all your help guys.

Scott Foulk
Okay - <egg on my face> This did not work. </egg on my face>After shooting my bullets for about a minute or three, the application runs out of memory. It appears to work very well, and just as I wanted it to. So back to square one.
Scott Foulk
Okay - the best one was what I put above, except for the memory issue. The sounds played on demand and there as no lag in the visuals. Can anyone tell me how to get this stuff working. I'm getting very frustrated...
Scott Foulk