Question

I tried to get to work with the javax.sound.sampled-package.

I tried implementing my own version of TargetDataLine (for test purposes at this point). To my very dismay, however, when I was done and tried to "play" it, neither one of it's methods were invoked (nor any exceptions raised), but instead, the program froze.

The code segment in question looks like this:

try {
  // create stream.
  AssembledDataLine line = new AssembledDataLine();
  AudioInputStream stream = new AudioInputStream(line);

  // create content.
  int size = 65536;
  byte[] array = new byte[size];
  byte inc = 1;
  byte pos = (byte) 0;
  for (int i = 0; i < size; ++i) {
    array[i] = (pos += inc);
    if (pos == 127) {
      inc = -1;
    } else if (pos == -128) {
      inc = 1;
    }
  }
  line.writeArray(array);

  // play.
  System.out.println("starting to play.");
  Clip clip = AudioSystem.getClip();
  clip.loop(Clip.LOOP_CONTINUOUSLY);
  System.out.println("got clip");
  clip.open(stream);
  System.out.println("opened");
  clip.start();
  Thread.sleep(5000);
  System.out.println("started");
  clip.close();
  System.out.println("end.");
} catch (Exception e) {
  e.printStackTrace();
  System.out.println("error");
}

The above mentioned code will never reach the "opened" statement, or throw an exception. I tried inserting a printout into every single method implemented in AssembledDataLine, but neither of them is ever invoked (with the exception of writeArray, which is called before opening the stream).

So at this point i think the Clip.open(stream) method freezes up even before reaching the point of gaining input from the stream.

I tried to open a file the same way and it worked, so I figure this is related to the way I instantiate the AudioInputStream.

Was it helpful?

Solution

The answer was, that the Clip, whilst not directly invoking a method of AssembledDataLine, will ask the wrapping AudioInputStream which format is being used. Therein was my mistake. I had swapped the values for FRAME_RATE and FRAME_SIZE when creating the audio-format. This meant the audio-format was invalid and thus the clip would freeze on allocating enough memory to actually play the input data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top