求java播放音乐mp3等格式的代码
亲们,我想要一个java程序写的调用windows自带的音乐播放器播放map3等格式的音乐,如果有可能的话swing做的播放器也可以,我在网上找了很多例子和代码,有的是乱码,有的不能实现,,现在头都炸了,,希望高手快快出来,帮帮我~! --------------------编程问答-------------------- 要搞这方面。奉劝你先学学Win32 API. --------------------编程问答-------------------- http://code.google.com/p/yoyoplayer/ --------------------编程问答-------------------- Win32 API 是什么?我只是需要一段如何调用本地播放器播放音乐的代码就可以,能实现就行 --------------------编程问答-------------------- 这个。。我下载了一个,怎么全是jar? --------------------编程问答-------------------- 我听歌用的播放器就是自己用java swing写的。我在百度网盘http://pan.baidu.com/share/link?shareid=110575&uk=2165635302放了一份,楼主可以先看下。我这个需要32位的java虚拟机,不支持64位java虚拟机。 --------------------编程问答-------------------- 需要告诉楼主的是,我按照自己的需求来写的 能放几种格式的音乐,当做只能放MP3吧 可以放放MPG等格式的视频。好吧。功能简单的我都想把回帖删了。。不说了。 --------------------编程问答--------------------import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import sun.audio.AudioStream;
import sun.audio.ContinuousAudioDataStream;
/**
* Copyright (C), 2006-2010, ChengDu info. Co., Ltd.
* FileName: Music.java
* 此类为音乐类,用于播放各种音乐
*
* @author ls
* @Date 2010-4-1
* @version 1.00
*/
public class GameMusic extends Thread {
public final static String WELCOME = "music/dancer.wav";
public final static String EV = "music/evillaugh.wav";
public final static String FLOOP = "music/floop.wav";
public final static String SIREN = "music/siren.wav";
public final static String READY = "music/readysetplant.wav";
public final static String SET = "music/grassstep.wav";
public final static String FIRE = "music/firepea.wav";
public final static String KERN= "music/kernelpult.wav";
public final static String SHOVER = "music/gravebutton.wav";
public final static String PUFF = "music/puff.wav";
public final static String EXPLOSION = "music/explosion.wav";
public final static String END= "music/scream.wav";
private static AudioStream play_music;
private static ContinuousAudioDataStream musicStream;
/**
* Method: Music Desctiptoin: 构造方法
*
* @param musicFile
* 音乐文件路径
* @param time
* 音乐播放时间
*/
public GameMusic(String musicFile) {}
/**
* 播放单音音频
* @param musicFile 单音音频文件路径
*/
public static void playSingleMusic(String musicFile) {
FileInputStream fin = null;
try {
fin = new FileInputStream(musicFile);//创建文件读入流
play_music = new sun.audio.AudioStream(fin);//创建音频流
sun.audio.AudioPlayer.player.start(play_music);// 播放音乐
} catch (Exception e) {
System.out.println(e);
}
}
/**
* 循环播放音频
* @param musicFile
*/
public static void playLoopMusic(String musicFile){
stopLoopMusic();
try {
FileInputStream musicInputStream = new FileInputStream(musicFile);
sun.audio.AudioStream play_Loopmusic = new sun.audio.AudioStream(musicInputStream);
musicStream = new ContinuousAudioDataStream(play_Loopmusic.getData());
sun.audio.AudioPlayer.player.start(musicStream);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 停止播放循环音频
*/
public static void stopLoopMusic() {
if(musicStream != null){
sun.audio.AudioPlayer.player.stop(musicStream);
try {
musicStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 停止播放单音音频
*
*/
public static void stopSingleMusic() {
sun.audio.AudioPlayer.player.stop(play_music);
}
// public static void main(String[] args) {
// GameMusic.playSingleMusic("music/zombaquarium_die.wav");
// }
}
代码直接贴给你,以前做swing的植物大战僵尸用的
--------------------编程问答-------------------- 为嘛把代码弄过去会报错?还要建立类? --------------------编程问答-------------------- 下载了,一个可执行文件,可是路径弄上去没反应哇? --------------------编程问答--------------------
报错是要把构建路劲改一下,你用的是jre要改成jdk --------------------编程问答-------------------- import sun.audio.AudioStream;
import sun.audio.ContinuousAudioDataStream;
这个是在jdk里面的 --------------------编程问答-------------------- 找jdk目录lib目录下面有个rt.jar加进去就行了
--------------------编程问答--------------------
在dos下输入 java -jar 目下的的YOYOPlayer.jar --------------------编程问答-------------------- 好像只能播放wav格式的音频 --------------------编程问答-------------------- 那个路径是你MP3音乐所在的路径。 --------------------编程问答-------------------- 比方我的音乐在D:/music文件夹下 这样设置就行了 --------------------编程问答-------------------- 然后程序会扫描该文件夹,能够播放的音乐格式的文件会被加载并播放。 --------------------编程问答-------------------- 这个代码能播MP3
--------------------编程问答-------------------- 大神们 学习了 --------------------编程问答-------------------- 天啊,我都晕了~!亲们,晚上的时候我再试试,今天应该能结贴~ --------------------编程问答-------------------- 不能播放MP3格式的啊 --------------------编程问答-------------------- 需要导入的包呢???能给我吗? --------------------编程问答--------------------
public class MP3Player {
public void testPlay(String filename)
{
try {
File file = new File(filename);
AudioInputStream in= AudioSystem.getAudioInputStream(file);
AudioInputStream din = null;
AudioFormat baseFormat = in.getFormat();
AudioFileFormat baseFileFormat = AudioSystem.getAudioFileFormat(file);
System.out.println(baseFileFormat);
System.out.println(baseFileFormat.properties());
AudioFormat decodedFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(),
16,
baseFormat.getChannels(),
baseFormat.getChannels() * 2,
baseFormat.getSampleRate(),
false);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
// Play now.
rawplay(decodedFormat, din);
in.close();
} catch (Exception e){
}
}
private void rawplay(AudioFormat targetFormat, AudioInputStream din) throws IOException,LineUnavailableException
{
byte[] data = new byte[4096];
SourceDataLine line = getLine(targetFormat);
if (line != null)
{
// Start
line.start();
int nBytesRead = 0;
int nBytesWritten = 0;
while (nBytesRead != -1)
{
nBytesRead = din.read(data, 0, data.length);
if (nBytesRead != -1)
nBytesWritten = line.write(data, 0, nBytesRead);
}
// Stop
line.drain();
line.stop();
line.close();
din.close();
}
}
private SourceDataLine getLine(AudioFormat audioFormat) throws LineUnavailableException {
SourceDataLine res = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
res = (SourceDataLine) AudioSystem.getLine(info);
res.open(audioFormat);
return res;
}
public static String toHexString(byte[] b){
if (b==null)
return null;
StringBuilder sb=new StringBuilder();
for (byte x:b){
String tt=Integer.toHexString(x&0xff);
sb.append(tt).append("00".substring(tt.length()));
}
return sb.toString();
}
public static byte[] md5(String str){
MessageDigest md;
byte b[]=null;
try {
md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
b = md.digest();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return b;
}
/**
* @param args
*/
public static void main(String[] args) {
MP3Player player=new MP3Player();
player.testPlay("e:/temp/1111.mp3");
}
}
public class EmbeddedMediaPlayer extends Application {
private static final String MEDIA_URL = "http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv";
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Embedded Media Player");
Group root = new Group();
Scene scene = new Scene(root, 540, 253);
Media media = new Media(MEDIA_URL);
MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.setAutoPlay(true);
MediaControl mediaControl = new MediaControl(mediaPlayer);
scene.setRoot(mediaControl);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
public class MediaControl extends BorderPane {
private MediaPlayer mp;
private MediaView mediaView;
private final boolean repeat = false;
private boolean atEndOfMedia = false;
private Duration duration;
private Slider timeSlider;
private Label playTime;
private Slider volumeSlider;
private HBox mediaBar;
public MediaControl(final MediaPlayer mp) {
this.mp = mp;
setStyle("-fx-background-color: #bfc2c7;");
mediaView = new MediaView(mp);
Pane mvPane = new Pane() {
};
mvPane.getChildren().add(mediaView);
mvPane.setStyle("-fx-background-color: black;");
setCenter(mvPane);
mediaBar = new HBox();
mediaBar.setAlignment(Pos.CENTER);
mediaBar.setPadding(new Insets(5, 10, 5, 10));
BorderPane.setAlignment(mediaBar, Pos.CENTER);
final Button playButton = new Button(">");
playButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
Status status = mp.getStatus();
if (status == Status.UNKNOWN || status == Status.HALTED) {
// don't do anything in these states
System.out
.println("Player is in a bad or unknown state, can't play.");
return;
}
if (atEndOfMedia) {
// rewind the movie if we're sitting at the end
atEndOfMedia = false;
mp.seek(mp.getStartTime());
playButton.setText("||");
} else if (status == Status.PAUSED || status == Status.READY
|| status == Status.STOPPED) {
mp.play();
} else {
mp.pause();
}
}
});
mp.currentTimeProperty().addListener(new InvalidationListener() {
public void invalidated(Observable ov) {
updateValues();
}
});
mp.setOnPlaying(new Runnable() {
public void run() {
System.out.println("onPlaying");
playButton.setText("||");
}
});
mp.setOnPaused(new Runnable() {
public void run() {
System.out.println("onPaused");
playButton.setText(">");
}
});
mp.setOnReady(new Runnable() {
public void run() {
System.out.println("onReady");
duration = mp.getMedia().getDuration();
updateValues();
}
});
mp.setCycleCount(repeat ? MediaPlayer.INDEFINITE : 1);
mp.setOnEndOfMedia(new Runnable() {
public void run() {
System.out.println("onEndOfMedia");
if (!repeat) {
playButton.setText(">");
atEndOfMedia = true;
}
}
});
mediaBar.getChildren().add(playButton);
// Add spacer
Label spacer = new Label(" ");
mediaBar.getChildren().add(spacer);
// Add Time label
Label timeLabel = new Label("Time: ");
mediaBar.getChildren().add(timeLabel);
// Add time slider
timeSlider = new Slider();
HBox.setHgrow(timeSlider, Priority.ALWAYS);
timeSlider.setMinWidth(50);
timeSlider.setMaxWidth(Double.MAX_VALUE);
timeSlider.valueProperty().addListener(new InvalidationListener() {
public void invalidated(Observable ov) {
if (timeSlider.isValueChanging()) {
/*
* multiply duration by percentage calculated by slider
* position
*/
mp.seek(duration.multiply(timeSlider.getValue() / 100.0));
if (atEndOfMedia) {
/*
* if media has arrived its end before the seeking,
* adjust the play button content
*/
atEndOfMedia = false;
playButton.setText("||");
}
}
}
});
mediaBar.getChildren().add(timeSlider);
// Add Play label
playTime = new Label();
playTime.setPrefWidth(130);
playTime.setMinWidth(50);
mediaBar.getChildren().add(playTime);
// Add the volume label
Label volumeLabel = new Label("Vol: ");
mediaBar.getChildren().add(volumeLabel);
// Add Volume slider
volumeSlider = new Slider();
volumeSlider.setPrefWidth(70);
volumeSlider.setMaxWidth(Region.USE_PREF_SIZE);
volumeSlider.setMinWidth(30);
volumeSlider.valueProperty().addListener(new InvalidationListener() {
public void invalidated(Observable ov) {
if (volumeSlider.isValueChanging()) {
mp.setVolume(volumeSlider.getValue() / 100.0);
}
}
});
mediaBar.getChildren().add(volumeSlider);
setBottom(mediaBar);
}
protected void updateValues() {
if (playTime != null && timeSlider != null && volumeSlider != null) {
Platform.runLater(new Runnable() {
public void run() {
Duration currentTime = mp.getCurrentTime();
playTime.setText(formatTime(currentTime, duration));
timeSlider.setDisable(duration.isUnknown());
if (!timeSlider.isDisabled()
&& duration.greaterThan(Duration.ZERO)
&& !timeSlider.isValueChanging()) {
timeSlider.setValue(currentTime.divide(
duration.toMillis()).toMillis() * 100.0);
}
if (!volumeSlider.isValueChanging()) {
volumeSlider.setValue((int) Math.round(mp.getVolume() * 100));
}
}
});
}
}
private static String formatTime(Duration elapsed, Duration duration) {
int intElapsed = (int) Math.floor(elapsed.toSeconds());
int elapsedHours = intElapsed / (60 * 60);
if (elapsedHours > 0) {
intElapsed -= elapsedHours * 60 * 60;
}
int elapsedMinutes = intElapsed / 60;
int elapsedSeconds = intElapsed - elapsedHours * 60 * 60
- elapsedMinutes * 60;
if (duration.greaterThan(Duration.ZERO)) {
int intDuration = (int) Math.floor(duration.toSeconds());
int durationHours = intDuration / (60 * 60);
if (durationHours > 0) {
intDuration -= durationHours * 60 * 60;
}
int durationMinutes = intDuration / 60;
int durationSeconds = intDuration - durationHours * 60 * 60
- durationMinutes * 60;
if (durationHours > 0) {
return String.format("%d:%02d:%02d/%d:%02d:%02d", elapsedHours,
elapsedMinutes, elapsedSeconds, durationHours,
durationMinutes, durationSeconds);
} else {
return String.format("%02d:%02d/%02d:%02d", elapsedMinutes,
elapsedSeconds, durationMinutes, durationSeconds);
}
} else {
if (elapsedHours > 0) {
return String.format("%d:%02d:%02d", elapsedHours,
elapsedMinutes, elapsedSeconds);
} else {
return String.format("%02d:%02d", elapsedMinutes,
elapsedSeconds);
}
}
}
}
补充:Java , Java SE