1. 程式人生 > >Java播放聲音的幾種方式

Java播放聲音的幾種方式

課程設計用的方法

import Java.applet.AudioClip;

import java.io.*;

import java.applet.Applet;

import java.awt.Frame;

import java.NET.MalformedURLException;

import java.Net.URL;

publicclass Music extends Frame{

    publicstatic String imagePath=System.getProperty("user.dir")+"/Music/";

    public Music(){

    try {

            URL cb;

            //File f = new File(imagePath+"mario.midi");

            //File f = new File(imagePath+"1000.ogg");

            File f = new File(imagePath+"失敗音效.wav");

            //File f = new File("d:\\鈴聲.mp3");

            cb = f.toURL();

            AudioClip aau;

            aau = Applet.newAudioClip

(cb);

            aau.play();//迴圈播放 aau.play() 單曲 aau.stop()停止播放

            //aau.loop();

        } catch (MalformedURLException e) {

            e.printStackTrace();

        }

    }

    publicstaticvoid main(String args[]) {

    new Music();

    }

}

因為最近在研究java的語音聊天問題,所以剛剛好寫了幾個,給你三個播放的方法,分為三個類,建議採用第二或第三個:
package org.bling.music; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import sun.audio.AudioPlayer; 
public class MusicTest2 { 
private InputStream inputStream = null; 
private String file = "./intel.wav"; 
public MusicTest2(){ 
} 
public void play() throws IOException{ 
inputStream = new FileInputStream(new File(file)); 
AudioPlayer.player.start(inputStream); 
} 
public static void main(String[] args) { 
try { 
new MusicTest2().play(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
} 
---------------------------------------------------------------- 
package org.bling.music; 
import java.io.File; 
import java.io.IOException; 
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 MusicTest { 
private AudioFormat audioFormat = null; 
private SourceDataLine sourceDataLine = null; 
private DataLine.Info dataLine_info = null; 
private String file = "./intel.wav"; 
private AudioInputStream audioInputStream = null; 
public MusicTest() throws LineUnavailableException, UnsupportedAudioFileException, IOException{ 
audioInputStream = AudioSystem.getAudioInputStream(new File(file)); 
audioFormat = audioInputStream.getFormat(); 
dataLine_info = new DataLine.Info(SourceDataLine.class,audioFormat); 
sourceDataLine = (SourceDataLine)AudioSystem.getLine(dataLine_info); 
} 
public void play() throws IOException, LineUnavailableException{ 
byte[] b = new byte[1024]; 
int len = 0; 
sourceDataLine.open(audioFormat, 1024); 
sourceDataLine.start(); 
while ((len = audioInputStream.read(b)) > 0){ 
sourceDataLine.write(b, 0, len); 
} 
audioInputStream.close(); 
sourceDataLine.drain(); 
sourceDataLine.close(); 
} 
public static void main(String[] args) { 
try { 
new MusicTest().play(); 
} catch (IOException e) { 
e.printStackTrace(); 
} catch (LineUnavailableException e) { 
e.printStackTrace(); 
} catch (UnsupportedAudioFileException e) { 
e.printStackTrace(); 
} 
} 
} 
----------------------------------------------------------------- 
package org.bling.music; 
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 PlayTest { 
/** 
* @param args 
*/ 
public static void main(String[] args) { 
try { 
AudioInputStream ais = AudioSystem.getAudioInputStream(new File("intel.wav"));// 獲得音訊輸入流
AudioFormat baseFormat = ais.getFormat();// 指定聲音流中特定資料安排
System.out.println("baseFormat="+baseFormat); 
DataLine.Info info = new DataLine.Info(SourceDataLine.class,baseFormat); 
System.out.println("info="+info); 
SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); 
// 從混頻器獲得源資料行
System.out.println("line="+line); 
line.open(baseFormat);// 開啟具有指定格式的行,這樣可使行獲得所有所需的系統資源並變得可操作。
line.start();// 允許資料行執行資料 I/O 
int BUFFER_SIZE = 4000 * 4; 
int intBytes = 0; 
byte[] audioData = new byte[BUFFER_SIZE]; 
while (intBytes != -1) { 
intBytes = ais.read(audioData, 0, BUFFER_SIZE);// 從音訊流讀取指定的最大數量的資料位元組,並將其放入給定的位元組陣列中。
if (intBytes >= 0) { 
int outBytes = line.write(audioData, 0, intBytes);// 通過此源資料行將音訊資料寫入混頻器。
} 
} 
} catch (Exception e) { 
} 
} 
}

java播放wav的基礎程式碼

2007-02-09 15:09

import javax.sound.sampled.*;
import java.io.*;
public class TestMusic{
 
 private AudioFormat format;
    private byte[] samples;
 
 public static void main(String args[])throws Exception{
  TestMusic sound =new TestMusic("1.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();

    }


}

java 播放midi,wav,mp3

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import java.io.IOException;
import java.io.File;

public class BasicPlayer {

  private AudioInputStream stream = null;
  private AudioFormat format = null;
  private Clip clip = null;
  private SourceDataLine m_line;

  public void play(File fileName,int itemStatus)
  {
    try {
        // From file
        stream = AudioSystem.getAudioInputStream(fileName);

        // At present, ALAW and ULAW encodings must be converted
        // to PCM_SIGNED before it can be played
        format = stream.getFormat();
        if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
            format = new AudioFormat(
              AudioFormat.Encoding.PCM_SIGNED,
              format.getSampleRate(),
              16,
              format.getChannels(),
              format.getChannels() * 2,
              format.getSampleRate(),
               false);        // big endian
            stream = AudioSystem.getAudioInputStream(format, stream);
        }

        // Create the clip
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, stream.getFormat(), AudioSystem.NOT_SPECIFIED);
        m_line = (SourceDataLine) AudioSystem.getLine(info);
        m_line.open(stream.getFormat(),m_line.getBufferSize());
        m_line.start();

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

  public double getDuration()
  {
    return m_line.getBufferSize() /
        (m_line.getFormat().getFrameSize() * m_line.getFormat().getFrameRate());
  }

  public double getDecision()
  {
    return m_line.getMicrosecondPosition()/1000.0;
  }
}

java 視訊與音訊播放器支援wav mp3 視訊支援mpg

package book.mutimedia.vedio.jmf;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FileDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.media.ControllerClosedEvent;
import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.EndOfMediaEvent;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.PrefetchCompleteEvent;
import javax.media.RealizeCompleteEvent;
import javax.media.Time;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
/**
* 用Java的JMF實現一個媒體播放器,可以播放音訊和視訊
*/
public class JMFMediaPlayer extends JFrame implements ActionListener,
   ControllerListener, ItemListener {
// JMF的播放器
Player player;
// 播放器的視訊元件和控制組件
Component vedioComponent; 
Component controlComponent;

// 標示是否是第一次開啟播放器
boolean first = true;
// 標示是否需要迴圈
boolean loop = false;
// 檔案當前目錄
String currentDirectory;

// 構造方法
public JMFMediaPlayer(String title) {
   super(title);
   addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e){
     // 使用者點選視窗系統選單的關閉按鈕
     // 呼叫dispose以執行windowClosed
     dispose();
    }
    public void windowClosed(WindowEvent e){
     if (player != null){
      // 關閉JMF播放器物件
      player.close();
     }
     System.exit(0);
    }
   });
   // 建立播放器的選單
   JMenu fileMenu = new JMenu("檔案");
   JMenuItem openMemuItem = new JMenuItem("開啟");
   openMemuItem.addActionListener(this);
   fileMenu.add(openMemuItem);
   // 新增一個分割條
   fileMenu.addSeparator();
   // 建立一個複選框選單項
   JCheckBoxMenuItem loopMenuItem = new JCheckBoxMenuItem("迴圈", false);
   loopMenuItem.addItemListener(this);
   fileMenu.add(loopMenuItem);
   fileMenu.addSeparator();
   JMenuItem exitMemuItem = new JMenuItem("退出");
   exitMemuItem.addActionListener(this);
   fileMenu.add(exitMemuItem);
  
   JMenuBar menuBar = new JMenuBar();
   menuBar.add(fileMenu);
   this.setJMenuBar(menuBar);
   this.setSize(200, 200);
  
   try {
    // 設定介面的外觀,為系統外觀
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    SwingUtilities.updateComponentTreeUI(this);
   } catch (Exception e) {
    e.printStackTrace();
   }
   this.setVisible(true);
}

/**
* 實現了ActionListener介面,處理元件的活動事件
*/
public void actionPerformed(ActionEvent e) {
   if (e.getActionCommand().equals("退出")) {
    // 呼叫dispose以便執行windowClosed
    dispose();
    return;
   }
   FileDialog fileDialog = new FileDialog(this, "開啟媒體檔案", FileDialog.LOAD);
   fileDialog.setDirectory(currentDirectory);
   fileDialog.setVisible(true);
   // 如果使用者放棄選擇檔案,則返回
   if (fileDialog.getFile() == null){
    return;
   }
   currentDirectory = fileDialog.getDirectory();
   if (player != null){
    // 關閉已經存在JMF播放器物件
    player.close();
   }
   try {
    // 建立一個開啟選擇檔案的播放器
    player = Manager.createPlayer(new MediaLocator("file:"
      + fileDialog.getDirectory() + fileDialog.getFile()));
   } catch (java.io.IOException e2) {
    System.out.println(e2);
    return;
   } catch (NoPlayerException e2) {
    System.out.println("不能找到播放器.");
    return;
   }
   if (player == null) {
    System.out.println("無法建立播放器.");
    return;
   }
   first = false;
   this.setTitle(fileDialog.getFile());
   // 播放器的控制事件處理
   player.addControllerListener(this);
   // 預讀檔案內容
   player.prefetch();
}
/**
* 實現ControllerListener介面的方法,處理播放器的控制事件
*/
public void controllerUpdate(ControllerEvent e) {
   // 呼叫player.close()時ControllerClosedEvent事件出現。
   // 如果存在視覺部件,則該部件應該拆除(為一致起見,
   // 我們對控制面板部件也執行同樣的操作)
   if (e instanceof ControllerClosedEvent) {
    if (vedioComponent != null) {
     this.getContentPane().remove(vedioComponent);
     this.vedioComponent = null;
    }
    if (controlComponent != null) {
     this.getContentPane().remove(controlComponent);
     this.controlComponent = null;
    }
    return;
   }
   // 如果是媒體檔案到達尾部事件
   if (e instanceof EndOfMediaEvent) {
    if (loop) {
     // 如果允許迴圈,則重新開始播放
     player.setMediaTime(new Time(0));
     player.start();
    }
    return;
   }
   // 如果是播放器預讀事件
   if (e instanceof PrefetchCompleteEvent) {
    // 啟動播放器
    player.start();
    return;
   }
   // 如果是檔案開啟完全事件,則顯示視訊元件和控制器元件
   if (e instanceof RealizeCompleteEvent) {
    vedioComponent = player.getVisualComponent();
    if (vedioComponent != null){
     this.getContentPane().add(vedioComponent);
  
    }
    controlComponent = player.getControlPanelComponent();
    if (controlComponent != null){
     this.getContentPane().add(controlComponent, BorderLayout.SOUTH);
    }
    this.pack();
   }
}

// 處理“迴圈”複選框選單項的點選事件
public void itemStateChanged(ItemEvent e) {
   loop = !loop;
}

public static void main(String[] args){
   new JMFMediaPlayer("JMF媒體播放器");
}
}

需要下載jmf 的庫檔案   包括customizer.jar   jmf.jar mediaplayer.jar multiplayer.jar 共4個jar 包