Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble playing wav in Java

I'm trying to play a

PCM_UNSIGNED 11025.0 Hz, 8 bit, mono, 1 bytes/frame

file as described here (1) and here(2).

The first approach works, but I don't want to depend on sun.* stuff. The second results in just some leading frames being played, that sounds more like a click. Can't be an IO issue as I'm playing from a ByteArrayInputStream.

Plz share your ideas on why might this happen. TIA.

like image 592
yanchenko Avatar asked Feb 23 '09 14:02

yanchenko


People also ask

Can you play sounds in Java?

The Java Sound APIs are designed to play sounds smoothly and continuously, even very long sounds. As part of this tutorial, we'll play an audio file using Clip and SourceDataLine Sound APIs provided by Java. We'll also play different audio format files.

Can Windows 10 play WAV files?

On Windows, the Windows Media Player is capable of playing WAV files. On MacOS, iTunes or QuickTime can play WAV files. On Linux, your basic ALSA system can play these files.

What is AudioSystem in Java?

The AudioSystem class acts as the entry point to the sampled-audio system resources. This class lets you query and access the mixers that are installed on the system. AudioSystem includes a number of methods for converting audio data between different formats, and for translating between audio files and streams.


1 Answers

I'm not sure why the second approach you linked to starts another thread; I believe the audio will be played in its own thread anyway. Is the problem that your application finishes before the clip has finished playing?

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.LineEvent.Type;

private static void playClip(File clipFile) throws IOException, 
  UnsupportedAudioFileException, LineUnavailableException, InterruptedException {
  class AudioListener implements LineListener {
    private boolean done = false;
    @Override public synchronized void update(LineEvent event) {
      Type eventType = event.getType();
      if (eventType == Type.STOP || eventType == Type.CLOSE) {
        done = true;
        notifyAll();
      }
    }
    public synchronized void waitUntilDone() throws InterruptedException {
      while (!done) { wait(); }
    }
  }
  AudioListener listener = new AudioListener();
  AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(clipFile);
  try {
    Clip clip = AudioSystem.getClip();
    clip.addLineListener(listener);
    clip.open(audioInputStream);
    try {
      clip.start();
      listener.waitUntilDone();
    } finally {
      clip.close();
    }
  } finally {
    audioInputStream.close();
  }
}
like image 107
JaredMcAteer Avatar answered Oct 20 '22 18:10

JaredMcAteer