1

LAST EDIT - TWO SIMPLE ANSWERS NEEDED.

1) I was able to get the code working with a URL (it's the code from one of the responses below). But my song is in a wav file. When I try to do File url = new File("---");, it doesn't work.

Instead, in the stack trace (thanks for that tip!), it says

"Failed to allocate clip data: Requested buffer too large"

The song I'm trying to play is techno, about 3 minutes long.

How do I work around the clip data size issue?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Marky Mark
  • 33
  • 1
  • 7
  • Also, does it matter in this case if the file is WAV or MP3? – Marky Mark Sep 24 '10 at 10:48
  • Replace the output in all the catches with the stack trace, which is a lot more informative and useful than printing "F*CK". If using a WAV instead of an MP3, there should be no need to add the mp3plugin.jar to the run-time class-path. J2SE supports most WAVs 'out of the box'. – Andrew Thompson Sep 24 '10 at 11:20
  • Aaah.. I was waiting for that. My experiments revealed that Clip was limited to one entire second of stereo, 16 bit, 44.1 KHz sound. That is why I developed BigClip. See http://pscode.org/javadoc/org/pscode/xui/sound/bigclip/BigClip.html. Note that BigClip has a bug in looping that I have not had time to track down. If you can find where I went wrong, please provide a fix. ;) – Andrew Thompson Sep 25 '10 at 05:24

2 Answers2

2

Look at the classes of the Java Sound API for sampled sound. Particularly the Clip interface and the AudioSystem class.

Java Sound uses the SPI to add support for extra formats to the defaults built in to the J2SE. You can add the JMF based mp3plugin.jar to provide support for MP3s to JavaSound.


For playing WAVs in a loop, see this small example..
import java.net.URL;
import javax.sound.sampled.*;

public class LoopSound {

  public static void main(String[] args) throws Exception {
    URL url = new URL(
      "http://pscode.org/media/leftright.wav");
    Clip clip = AudioSystem.getClip();
    AudioInputStream ais = AudioSystem.
      getAudioInputStream( url );
    clip.open(ais);
    clip.loop(5);
    javax.swing.JOptionPane.showMessageDialog(null, "Close to exit!");
  }
} 
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
0

Check out this tutorial, it shows how to implement your own read-feed-play loop and avoid memory errors:

http://codeidol.com/java/swing/Audio/Play-Non-Trivial-Audio/

urish
  • 8,943
  • 8
  • 54
  • 75