用 Java Sound API 播放 PCM 音频

用 Java Sound API 播放 PCM 音频 Playing PCM Audio with Java Sound API
  多媒体应用程序,比如因特网电话,需要实时播放音频,于是就要处理内存中的音频数据。本文将演示如何播放 PCM(脉冲编码调制)音频。     Multimedia application, such as an Internet phone, requires playing sound in real time. Thus we are going to deal with in-memery audio data. This article will show how to play PCM (Pulse Code Modulation) audio.
  假设有一个字节数组 audioBuffer 用来保存将要播放的音频块。做以下的初始化:     Suppose there is a byte array audioBuffer which holds a chunck of audio data to be played. Do the following initializations:
  1. AudioFormat af = new AudioFormat(
  2.         sampleRate, sampleSizeInBits, channels, signed, bigEndian);
  3. SourceDataLine.Info info = new DataLine.Info(
  4.         SourceDataLine.class, af, bufferSize);
  5. SourceDataLine sdl = (SourceDataLine) AudioSystem.getLine(info);
  6. sdl.open(af);
  7. sdl.start();
  接着只要不停地用 sdl 向混频器写入字节:     Then just continously write bytes to mixer with sdl:
  1. int offset = 0;
  2. while (offset < audioData.length) {
  3.     offset += sdl.write(audioData, offset, bufferSize);
  4. }
  因为 audioBuffer 被不断填充和播放,所以最好把上述代码放入线程。播放结束后像这样来停止 sdl     Since audioBuffer is filled and played on and on, it's best to put the above code in a thread. When the playing is over, stop sdl like this:
  1. sdl.drain();
  2. sdl.stop();

你可能感兴趣的:(用 Java Sound API 播放 PCM 音频)