`
任我随风
  • 浏览: 14297 次
  • 性别: Icon_minigender_1
  • 来自: 重庆
社区版块
存档分类
最新评论

打开音乐文件

阅读更多


import java.io.File;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
public class OpenMusic extends Thread {
 
 private String _fileName;
 
 public OpenMusic(String fileName) {
  _fileName=fileName;
 }
 
 public synchronized void run() {
  AudioInputStream m_audioInputStream = null;
  SourceDataLine m_line = null;
  AudioFormat audioFormat = null;
  try {
   File file = new File(_fileName);
   m_audioInputStream = AudioSystem.getAudioInputStream(file);
   audioFormat = m_audioInputStream.getFormat();

   if (audioFormat.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
    AudioFormat newFormat = new AudioFormat(
      AudioFormat.Encoding.PCM_SIGNED,
      audioFormat.getSampleRate(), 16,
      audioFormat.getChannels(),
      audioFormat.getChannels() * 2,
      audioFormat.getSampleRate(), false);
    System.out.println("Converting audio format to " + newFormat);
    AudioInputStream newStream = AudioSystem.getAudioInputStream(
      newFormat, m_audioInputStream);
    audioFormat = newFormat;
    m_audioInputStream = newStream;
   }

   DataLine.Info info = new DataLine.Info(SourceDataLine.class,
     audioFormat);
   m_line = (SourceDataLine) AudioSystem.getLine(info);
   m_line.open(audioFormat, m_line.getBufferSize());
   m_line.start();

   int bufferSize = (int) audioFormat.getSampleRate()
     * audioFormat.getFrameSize();
   byte[] buffer = new byte[bufferSize];

   int bytesRead = 0;
   while (bytesRead >= 0) {
    bytesRead = m_audioInputStream.read(buffer, 0, buffer.length);
    if (bytesRead >= 0) {
     m_line.write(buffer, 0, bytesRead);
    }
   }
   m_line.drain();
   m_line.close();

  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 
public static void main(String[] args){

//调用打开音乐的方法,在这之前要加载打开音乐的3个驱动程序(附件)。
 new OpenMusic("C:\\Users\\Administrator\\Desktop\\四个女生-心愿.mp3").start();

 }
 


}

 

  • lib.rar (203.7 KB)
  • 下载次数: 16
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics