java如何播放wav文件

Python024

java如何播放wav文件,第1张

建议使用jmf(java media framwork),这样就能播放mp3等众多格式音乐了;去sun官网下一个jmf,安装好后,把

jmf.jar包引入便可使用,给出例zi代码:使用方法:构造函数中传入文件路径名即可,播放、暂停、继续、停止等功能均已实现。

/*************************************************

* Subclass: MusicPlay

*************************************************/

public class MusicPlay implements Runnable {

private Time zeroTime = new Time(0)

private Player player

private boolean isloop = false

/*************************************************

* Function: MusicPlay Description: constructor, load the music file and

* get ready for play Called By: MultiMedia()

*************************************************/

// 实例化各个参数 filename 为文件名,可为绝对路径

public MusicPlay(String filename) {

File file = new File(filename)

try {

player = Manager.createRealizedPlayer(file.toURI().toURL())

player.addControllerListener(new ControllListener())

} catch (NoPlayerException e) {

e.printStackTrace()

} catch (CannotRealizeException e) {

e.printStackTrace()

} catch (MalformedURLException e) {

e.printStackTrace()

} catch (IOException e) {

e.printStackTrace()

}

}

/*************************************************

* Function: isRunning Description: test if this music is playing Called

* By:

*************************************************/

public boolean isRunning() {

return player.getState() == Player.Started

}

/*************************************************

* Function: play Description: play the music for once Called By:

* resumeAll()

*************************************************/

// 只播放一次

public void play() {

if (!turnOff)

player.start()

}

/*************************************************

* Function: replay Description: replay the music Called By: musics that

* will be played many times will invoke this methed

*************************************************/

// 再播放一次

public void replay() {

if (turnOff)

return

if (player.getState() == Controller.Prefetched)

player.setMediaTime(zeroTime)

player.start()

}

/*************************************************

* Function: stop Description: stop this music Called By: stopAll() of

* upper class,suspendAll() of upper

* class,BackroundForMenuPanel,GameOverPanel

*************************************************/

public void stop() {

player.stop()

}

/*************************************************

* Function: close Description: dispose the music Called By: closeAll()

* of super class

*************************************************/

public void close() {

player.stop()

player.close()

}

/*************************************************

* Function: loop Description: make the music played repetitiously

* Called By: music that will repetitious play

*************************************************/

// 循环播放

public void loop() {

if (turnOff)

return

isloop = true

player.prefetch()

replay()

}

/*************************************************

* Function: run Description: trig this music Called By: Override method

*************************************************/

@Override

public void run() {

loop()

}

/*************************************************

* Subclass: ControllListener Description: listener for playing and

* implement playing repetitiously

*************************************************/

// 通过对播放进度的监听,实现循环播放

private class ControllListener implements ControllerListener {

public void controllerUpdate(ControllerEvent e) {

if (e instanceof EndOfMediaEvent) {

if (isloop) {

player.setMediaTime(new Time(0))

player.start()

}

}

}

}

}

/**

* 播放音乐

*

* @param mp3Path

* @param repeat

*/

public static void playSound(final String mp3Path, final int repeat) {

new Thread(new Runnable() {

@Override

public void run() {

if (mp3Path.endsWith("mp3")) {

// TODO Auto-generated method stub

MP3Player mp3 = new MP3Player(mp3Path)

int ccc = 0

while (ccc <repeat) {

try {

Thread.sleep(1000)

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace()

}

ccc++

mp3.play()

}

} else {

try {

// .wav 文件放在java project 下面

//System.getProperty("user.dir") + File.separator+ "ring.wav"

System.out.println(mp3Path)

FileInputStream fileau = new FileInputStream(

mp3Path)

AudioStream as = new AudioStream(fileau)

int ccc = 0

while (ccc <repeat) {

try {

Thread.sleep(1000)

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace()

}

ccc++

AudioPlayer.player.start(as)

}

} catch (Exception e) {

e.printStackTrace()

}

}

}

}).start()

}

sun audio jar下载 需要自己下载

import java.awt.BorderLayout

import java.awt.Color

import java.awt.FlowLayout

import java.awt.Font

import java.awt.Graphics

import java.awt.event.*

import java.io.*

import javax.sound.sampled.*

import javax.swing.JFileChooser

import javax.swing.JFrame

import javax.swing.JMenu

import javax.swing.JMenuBar

import javax.swing.JMenuItem

import javax.swing.border.Border

public class testmusic {

// static String s1="E:\\nine muses - no playboy - 韩国.wav"

// static String s2="E:\\蔡妍 - my love.wav"

// static String s3="E:\\钢琴与嗨曲的完美结合 性感女声慢摇 经典中的经典.wav"

public static void main(String[] args){

test t = new test()

Thread s = new Thread(t)

s.start()

}

}

class AePlayWave extends Thread{

private String filename

public AePlayWave(String wavfile){

filename = wavfile

}

public void run(){

File soundFile = new File(filename)

AudioInputStream audioInputStream=null

try{

audioInputStream = AudioSystem.getAudioInputStream

(soundFile)

}catch(Exception e1){

e1.printStackTrace()

return

}

AudioFormat format = audioInputStream.getFormat()

SourceDataLine auline = null

DataLine.Info info = new DataLine.Info(SourceDataLine.class,format)

try{

auline=(SourceDataLine)AudioSystem.getLine(info)

auline.open(format)

}catch(Exception e){

e.printStackTrace()

return

}

auline.start()

int nBytesRead=0

byte[] abData = new byte[1024]

try{

while(nBytesRead!=-1){

nBytesRead=audioInputStream.read

(abData,0,abData.length)

if(nBytesRead>=0)

auline.write(abData,0,nBytesRead)

}

}catch(IOException e){

e.printStackTrace()

return

}finally{

auline.drain()

auline.close()

}

}

}

//import java.io.File

//import javax.sound.sampled.AudioFormat

//import javax.sound.sampled.AudioInputStream

//import javax.sound.sampled.AudioSystem

//import javax.sound.sampled.Clip

//import javax.sound.sampled.DataLine

//try{

//File file = new File("D:\\music\\i - m - back.mp3")

//AudioInputStream stream = AudioSystem.getAudioInputStream(file)

//AudioFormat format = stream.getFormat()

//DataLine.Info info = new DataLine.Info(Clip.class,format)

//Clip clip = (Clip)AudioSystem.getLine(info)

//clip.open(stream)

//clip.start()

//}catch(Exception e){

//e.printStackTrace()

//}

class test extends JFrame implements Runnable,ActionListener{

int x=30,y=40

JMenuBar jmb= null

JMenu jm = null

JMenuItem jmi,jmi1,jmi2=null

test(){

super("JAVA写的最原始的WAV格式音乐播放器")

setSize(500,500)

jmb=new JMenuBar()

jm = new JMenu("文件")

jmi = new JMenuItem("播放")

jmi1= new JMenuItem("打开")

jmi2=new JMenuItem("退出")

this.setLayout(new BorderLayout())

this.add(jmb,BorderLayout.NORTH)

jmb.add(jm)

jm.add(jmi)

jm.add(jmi1)

jm.add(jmi2)

jmi1.addActionListener(this)

jmi2.addActionListener(this)

jmi1.setActionCommand("open")

jmi2.setActionCommand("exit")

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

setVisible(true)

setResizable(false)

this.getContentPane().setBackground(Color.black)

}

@Override

public void run() {

// TODO Auto-generated method stub

while(true){

try{

Thread.sleep(1000)

x+=10

y+=10

repaint()

if(x==500){

x=30

}

if(y==500){

y=40

}

}catch(Exception e){

e.printStackTrace()

}

}

}

public void paint(Graphics g){

super.paint(g)

g.setColor(Color.red)

g.fillOval(x,y,40,40)

g.fill3DRect(y+60,x+60,60,60,true)

g.setColor(Color.yellow)

g.setFont(new Font("华文彩云",Font.BOLD,20))

g.drawString("点击菜单条的打开选中你电脑里面的WAV格式音乐", 20, 300)

g.drawString("点击退出即可退出",20,330)

g.drawString("别的按钮没有注册监听,无效。。。。",20,350)

}

@Override

public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub

if(e.getActionCommand().equals("open")){

JFileChooser jf = new JFileChooser()

jf.showOpenDialog(null)

String s1=(jf.getSelectedFile().getAbsoluteFile()).toString()

//System.out.println(s1)

AePlayWave a = new AePlayWave(s1)

a.start()

}

if(e.getActionCommand().equals("exit")){

System.exit(0)

}

}

}

仅支持WAV格式 点击打开按钮播放