「音频播放器java」音频播放器官方下载
本篇文章给大家谈谈音频播放器java,以及音频播放器官方下载对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。
本文目录一览:
如何用Java来编写一个音乐播放器
首先要在环境电脑中安装下JMF环境,才能引入javax.sound.sampled.*这个包,一下是用过的代码
package TheMusic;
import java.io.*;
import javax.sound.sampled.*;
public class Music {
public static void main(String[] args) {
// TODO Auto-generated method stub
//修改你的音乐文件路径就OK了
AePlayWave apw=new AePlayWave("突然好想你.wav");
apw.start();
}
}
在程序中实例化这个类,启动线程,实例化的时候参照Test修改路径就OK播放声音的类
Java代码
public 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[512];
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();
}
}
}
java写mp3播放器
--------------不支持MP3---------------------
public AudioClip loadSound(String filename) { // 返回一个AudioClip对象
URL url = null; // 因为newAudioClip()的参数为URL型
try {
url = new URL("file:" + filename); // 指定文件,“file:"不能少
} catch (MalformedURLException e) {
}
return JApplet.newAudioClip(url); // 通过newAudioClip(
// )方法装载声音,此方法为JDK后添加的方法,太老的JDK里可能没有
}
AudioClip s1 = loadSound("声音//TableStopGetPrice.wav");
s1.play();
------------------支持mp3--------------------------
见附件
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javazoom.jl.decoder.Bitstream;
import javazoom.jl.decoder.BitstreamException;
import javazoom.jl.decoder.Decoder;
import javazoom.jl.decoder.Header;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.decoder.SampleBuffer;
import javazoom.jl.player.AudioDevice;
import javazoom.jl.player.FactoryRegistry;
/**
* The codePlayer/code class implements a simple player for playback of an
* MPEG audio stream.
*
* @author Mat McGowan
* @since 0.0.8
*/
public class Player
{
/**
* The current frame number.
*/
private int frame = 0;
/**
* The MPEG audio bitstream.
*/
// javac blank final bug.
/* final */private Bitstream bitstream;
/**
* The MPEG audio decoder.
*/
/* final */private Decoder decoder;
/**
* The AudioDevice the audio samples are written to.
*/
private AudioDevice audio;
/**
* Has the player been closed?
*/
private boolean closed = false;
/**
* Has the player played back all frames from the stream?
*/
private boolean complete = false;
private int lastPosition = 0;
/**
* Creates a new codePlayer/code instance.
*/
public Player ( InputStream stream ) throws JavaLayerException
{
this (stream, null);
}
public Player ( InputStream stream, AudioDevice device ) throws JavaLayerException
{
bitstream = new Bitstream (stream);
decoder = new Decoder ();
if (device != null)
{
audio = device;
}
else
{
FactoryRegistry r = FactoryRegistry.systemRegistry ();
audio = r.createAudioDevice ();
}
audio.open (decoder);
}
public void play () throws JavaLayerException
{
play (Integer.MAX_VALUE);
}
/**
* Plays a number of MPEG audio frames.
*
* @param frames
* The number of frames to play.
* @return true if the last frame was played, or false if there are more
* frames.
*/
public boolean play ( int frames ) throws JavaLayerException
{
boolean ret = true;
while (frames-- 0 ret)
{
ret = decodeFrame ();
}
if (!ret)
{
// last frame, ensure all data flushed to the audio device.
AudioDevice out = audio;
if (out != null)
{
out.flush ();
synchronized (this)
{
complete = ( !closed );
close ();
}
}
}
return ret;
}
/**
* Cloases this player. Any audio currently playing is stopped immediately.
*/
public synchronized void close ()
{
AudioDevice out = audio;
if (out != null)
{
closed = true;
audio = null;
// this may fail, so ensure object state is set up before
// calling this method.
out.close ();
lastPosition = out.getPosition ();
try
{
bitstream.close ();
}
catch (BitstreamException ex)
{}
}
}
/**
* Returns the completed status of this player.
*
* @return true if all available MPEG audio frames have been decoded, or
* false otherwise.
*/
public synchronized boolean isComplete ()
{
return complete;
}
/**
* Retrieves the position in milliseconds of the current audio sample being
* played. This method delegates to the code
* AudioDevice/code that is used by this player to sound the decoded audio
* samples.
*/
public int getPosition ()
{
int position = lastPosition;
AudioDevice out = audio;
if (out != null)
{
position = out.getPosition ();
}
return position;
}
/**
* Decodes a single frame.
*
* @return true if there are no more frames to decode, false otherwise.
*/
protected boolean decodeFrame () throws JavaLayerException
{
try
{
AudioDevice out = audio;
if (out == null)
return false;
Header h = bitstream.readFrame ();
if (h == null)
return false;
// sample buffer set when decoder constructed
SampleBuffer output = (SampleBuffer) decoder.decodeFrame (h, bitstream);
synchronized (this)
{
out = audio;
if (out != null)
{
out.write (output.getBuffer (), 0, output.getBufferLength ());
}
}
bitstream.closeFrame ();
}
catch (RuntimeException ex)
{
throw new JavaLayerException ("Exception decoding audio frame", ex);
}
/*
* catch (IOException ex) {
* System.out.println("exception decoding audio frame: "+ex); return
* false; } catch (BitstreamException bitex) {
* System.out.println("exception decoding audio frame: "+bitex); return
* false; } catch (DecoderException decex) {
* System.out.println("exception decoding audio frame: "+decex); return
* false; }
*/
return true;
}
public static void main ( String[] args )
{
try
{
Player player = new Player (new FileInputStream (new File ("D:\\Youdagames\\JLayer1.0.1\\abc.mp3")));
player.play ();
}
catch (FileNotFoundException e)
{
e.printStackTrace ();
}
catch (JavaLayerException e)
{
e.printStackTrace ();
}
}
}
如何用java做一个音乐播放器?
首先下载播放mp3的包,比如mp3spi1.9.4.jar。在工程中添加这个包。
播放器演示代码如下
package com.test.audio;
import java.io.File;
import java.awt.BorderLayout;
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.List;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.MenuShortcut;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
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 MusicPlayer extends Frame {
/**
*
*/
private static final long serialVersionUID = -2605658046194599045L;
boolean isStop = true;// 控制播放线程
boolean hasStop = true;// 播放线程状态
String filepath;// 播放文件目录
String filename;// 播放文件名称
AudioInputStream audioInputStream;// 文件流
AudioFormat audioFormat;// 文件格式
SourceDataLine sourceDataLine;// 输出设备
List list;// 文件列表
Label labelfilepath;//播放目录显示标签
Label labelfilename;//播放文件显示标签
public MusicPlayer() {
// 设置窗体属性
setLayout(new BorderLayout());
setTitle("MP3 Music Player");
setSize(350, 370);
// 建立菜单栏
MenuBar menubar = new MenuBar();
Menu menufile = new Menu("File");
MenuItem menuopen = new MenuItem("Open", new MenuShortcut(KeyEvent.VK_O));
menufile.add(menuopen);
menufile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
open();
}
});
menubar.add(menufile);
setMenuBar(menubar);
// 文件列表
list = new List(10);
list.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// 双击时处理
if (e.getClickCount() == 2) {
// 播放选中的文件
filename = list.getSelectedItem();
play();
}
}
});
add(list, "Center");
// 信息显示
Panel panel = new Panel(new GridLayout(2, 1));
labelfilepath = new Label("Dir:");
labelfilename = new Label("File:");
panel.add(labelfilepath);
panel.add(labelfilename);
add(panel, "North");
// 注册窗体关闭事件
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setVisible(true);
}
// 打开
private void open() {
FileDialog dialog = new FileDialog(this, "Open", 0);
dialog.setVisible(true);
filepath = dialog.getDirectory();
if (filepath != null) {
labelfilepath.setText("Dir:" + filepath);
// 显示文件列表
list.removeAll();
File filedir = new File(filepath);
File[] filelist = filedir.listFiles();
for (File file : filelist) {
String filename = file.getName().toLowerCase();
if (filename.endsWith(".mp3") || filename.endsWith(".wav")) {
list.add(filename);
}
}
}
}
// 播放
private void play() {
try {
isStop = true;// 停止播放线程
// 等待播放线程停止
System.out.print("Start:" + filename);
while (!hasStop) {
System.out.print(".");
try {
Thread.sleep(10);
} catch (Exception e) {
}
}
System.out.println("");
File file = new File(filepath + filename);
labelfilename.setText("Playing:" + filename);
// 取得文件输入流
audioInputStream = AudioSystem.getAudioInputStream(file);
audioFormat = audioInputStream.getFormat();
// 转换mp3文件编码
if (audioFormat.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
audioFormat.getSampleRate(), 16, audioFormat
.getChannels(), audioFormat.getChannels() * 2,
audioFormat.getSampleRate(), false);
audioInputStream = AudioSystem.getAudioInputStream(audioFormat,
audioInputStream);
}
// 打开输出设备
DataLine.Info dataLineInfo = new DataLine.Info(
SourceDataLine.class, audioFormat,
AudioSystem.NOT_SPECIFIED);
sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
sourceDataLine.open(audioFormat);
sourceDataLine.start();
// 创建独立线程进行播放
isStop = false;
Thread playThread = new Thread(new PlayThread());
playThread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
class PlayThread extends Thread {
byte tempBuffer[] = new byte[320];
public void run() {
try {
int cnt;
hasStop = false;
// 读取数据到缓存数据
while ((cnt = audioInputStream.read(tempBuffer, 0,
tempBuffer.length)) != -1) {
if (isStop)
break;
if (cnt 0) {
// 写入缓存数据
sourceDataLine.write(tempBuffer, 0, cnt);
}
}
// Block等待临时数据被输出为空
sourceDataLine.drain();
sourceDataLine.close();
hasStop = true;
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
}
public static void main(String args[]) {
new MusicPlayer();
}
}
关于音频播放器java和音频播放器官方下载的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。
发布于:2022-11-23,除非注明,否则均为
原创文章,转载请注明出处。