通过Java调用音频文件 不需要播放器

package com.test;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

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 TestMusic {

 
 
 
 private AudioFormat format;
  private byte[] samples;
 
 public static void main(String args[])throws Exception{
  TestMusic sound =new TestMusic("D:\\Program Files\\KuGou2012\\login.wav");
  InputStream stream =new ByteArrayInputStream(sound.getSamples());
  // play the sound
  sound.play(stream);
  // exit
  System.exit(0);
  }
 
 public TestMusic(String filename) {
  try {
  // open the audio input stream
  AudioInputStream stream =AudioSystem.getAudioInputStream(new File(filename));
  format = stream.getFormat();
  // get the audio samples
  samples = getSamples(stream);
  }
  catch (UnsupportedAudioFileException ex) {
  ex.printStackTrace();
  }
  catch (IOException ex) {
  ex.printStackTrace();
  }
  }
 
 public byte[] getSamples() {
  return samples;
  }
 
 private byte[] getSamples(AudioInputStream audioStream) {
  // get the number of bytes to read
  int length = (int)(audioStream.getFrameLength() * format.getFrameSize());
  // read the entire stream
  byte[] samples = new byte[length];
  DataInputStream is = new DataInputStream(audioStream);
  try {
  is.readFully(samples);
  }
  catch (IOException ex) {
  ex.printStackTrace();
  }
  // return the samples
  return samples;
  }
 
 public void play(InputStream source) {
  // use a short, 100ms (1/10th sec) buffer for real-time
  // change to the sound stream
  int bufferSize = format.getFrameSize() *
  Math.round(format.getSampleRate() / 10);
  byte[] buffer = new byte[bufferSize];
  // create a line to play to
  SourceDataLine line;
  try {
  DataLine.Info info =
  new DataLine.Info(SourceDataLine.class, format);
  line = (SourceDataLine)AudioSystem.getLine(info);
  line.open(format, bufferSize);
  }
  catch (LineUnavailableException ex) {
  ex.printStackTrace();
  return;
  }
  // start the line
  line.start();
  // copy data to the line
  try {
  int numBytesRead = 0;
  while (numBytesRead != -1) {
  numBytesRead =
  source.read(buffer, 0, buffer.length);
  if (numBytesRead != -1) {
  line.write(buffer, 0, numBytesRead);
  }
  }
  }
  catch (IOException ex) {
  ex.printStackTrace();
  }
  // wait until all data is played, then close the line
  line.drain();
  line.close();
  }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值