Java播放声音的几种方式

来源:互联网 发布:淘宝男装潮店 编辑:程序博客网 时间:2024/05/22 07:53

转自:http://blog.csdn.net/kalision/article/details/7898786

————————————————————————————————————————————

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 包

0 0
原创粉丝点击