Java 怎么播放采样音频流

2019年7月29日20:08:15Java 怎么播放采样音频流已关闭评论 947 1555字阅读5分11秒

1.简介

Java 怎么播放采样音频流?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Main {

  public void main(String[] argv) {
    try {
      AudioInputStream stream = AudioSystem.getAudioInputStream(new File("audiofile"));

      stream = AudioSystem.getAudioInputStream(new URL("http:

      AudioFormat format = stream.getFormat();
      if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
        format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
            format.getSampleRate(), format.getSampleSizeInBits() * 2,
            format.getChannels(), format.getFrameSize() * 2,
            format.getFrameRate(), true); 
        stream = AudioSystem.getAudioInputStream(format, stream);
      }

      SourceDataLine.Info info = new DataLine.Info(SourceDataLine.class,
          stream.getFormat(),
          ((int) stream.getFrameLength() * format.getFrameSize()));
      SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
      line.open(stream.getFormat());
      line.start();

      int numRead = 0;
      byte[] buf = new byte[line.getBufferSize()];
      while ((numRead = stream.read(buf, 0, buf.length)) >= 0) {
        int offset = 0;
        while (offset < numRead) {
          offset += line.write(buf, offset, numRead - offset);
        }
      }
      line.drain();
      line.stop();
    } catch (MalformedURLException e) {
    } catch (IOException e) {
    } catch (LineUnavailableException e) {
    } catch (UnsupportedAudioFileException e) {
    }
  }
}

 
继续阅读
编程十万个怎么办