问题描述
亲们,我想要一个java程序写的调用windows自带的音乐播放器播放map3等格式的音乐,如果有可能的话swing做的播放器也可以,我在网上找了很多例子和代码,有的是乱码,有的不能实现,,现在头都炸了,,希望高手快快出来,帮帮我~!
解决方案
解决方案二:
要搞这方面。奉劝你先学学Win32API.
解决方案三:
解决方案四:
引用1楼dr8737010的回复:
要搞这方面。奉劝你先学学Win32API.
Win32API是什么?我只是需要一段如何调用本地播放器播放音乐的代码就可以,能实现就行
解决方案五:
引用2楼ticmy的回复:
http://code.google.com/p/yoyoplayer/
这个。。我下载了一个,怎么全是jar?
解决方案六:
我听歌用的播放器就是自己用javaswing写的。我在百度网盘http://pan.baidu.com/share/link?shareid=110575&uk=2165635302放了一份,楼主可以先看下。我这个需要32位的java虚拟机,不支持64位java虚拟机。
解决方案七:
引用5楼akemi_homura的回复:
我听歌用的播放器就是自己用javaswing写的。我在百度网盘http://pan.baidu.com/share/link?shareid=110575&uk=2165635302放了一份,楼主可以先看下。我这个需要32位的java虚拟机,不支持64位java虚拟机。
需要告诉楼主的是,我按照自己的需求来写的能放几种格式的音乐,当做只能放MP3吧可以放放MPG等格式的视频。好吧。功能简单的我都想把回帖删了。。不说了。
解决方案八:
importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.IOException;importsun.audio.AudioStream;importsun.audio.ContinuousAudioDataStream;/***Copyright(C),2006-2010,ChengDuinfo.Co.,Ltd.*FileName:Music.java*此类为音乐类,用于播放各种音乐**@authorls*@Date2010-4-1*@version1.00*/publicclassGameMusicextendsThread{publicfinalstaticStringWELCOME="music/dancer.wav";publicfinalstaticStringEV="music/evillaugh.wav";publicfinalstaticStringFLOOP="music/floop.wav";publicfinalstaticStringSIREN="music/siren.wav";publicfinalstaticStringREADY="music/readysetplant.wav";publicfinalstaticStringSET="music/grassstep.wav";publicfinalstaticStringFIRE="music/firepea.wav";publicfinalstaticStringKERN="music/kernelpult.wav";publicfinalstaticStringSHOVER="music/gravebutton.wav";publicfinalstaticStringPUFF="music/puff.wav";publicfinalstaticStringEXPLOSION="music/explosion.wav";publicfinalstaticStringEND="music/scream.wav";privatestaticAudioStreamplay_music;privatestaticContinuousAudioDataStreammusicStream;/***Method:MusicDesctiptoin:构造方法**@parammusicFile*音乐文件路径*@paramtime*音乐播放时间*/publicGameMusic(StringmusicFile){}/***播放单音音频*@parammusicFile单音音频文件路径*/publicstaticvoidplaySingleMusic(StringmusicFile){FileInputStreamfin=null;try{fin=newFileInputStream(musicFile);//创建文件读入流play_music=newsun.audio.AudioStream(fin);//创建音频流sun.audio.AudioPlayer.player.start(play_music);//播放音乐}catch(Exceptione){System.out.println(e);}}/***循环播放音频*@parammusicFile*/publicstaticvoidplayLoopMusic(StringmusicFile){stopLoopMusic();try{FileInputStreammusicInputStream=newFileInputStream(musicFile);sun.audio.AudioStreamplay_Loopmusic=newsun.audio.AudioStream(musicInputStream);musicStream=newContinuousAudioDataStream(play_Loopmusic.getData());sun.audio.AudioPlayer.player.start(musicStream);}catch(FileNotFoundExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}/***停止播放循环音频*/publicstaticvoidstopLoopMusic(){if(musicStream!=null){sun.audio.AudioPlayer.player.stop(musicStream);try{musicStream.close();}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}}/***停止播放单音音频**/publicstaticvoidstopSingleMusic(){sun.audio.AudioPlayer.player.stop(play_music);}//publicstaticvoidmain(String[]args){//GameMusic.playSingleMusic("music/zombaquarium_die.wav");//}}代码直接贴给你,以前做swing的植物大战僵尸用的
解决方案九:
引用7楼li164589371的回复:
importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.IOException;importsun.audio.AudioStream;importsun.audio.ContinuousAudioDataStream;/***Copyright……
为嘛把代码弄过去会报错?还要建立类?
解决方案十:
引用6楼akemi_homura的回复:
引用5楼akemi_homura的回复:我听歌用的播放器就是自己用javaswing写的。我在百度网盘http://pan.baidu.com/share/link?shareid=110575&uk=2165635302放了一份,楼主可以先看下。我这个需要32位的java虚拟机,不支持64位java虚拟机。需要告诉楼主的是,我按照自己的需求来写……
下载了,一个可执行文件,可是路径弄上去没反应哇?
解决方案十一:
引用8楼Faneney的回复:
引用7楼li164589371的回复:importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.IOException;importsun.audio.AudioStream;importsun.audio.ContinuousAud……
报错是要把构建路劲改一下,你用的是jre要改成jdk
解决方案十二:
importsun.audio.AudioStream;importsun.audio.ContinuousAudioDataStream;这个是在jdk里面的
解决方案十三:
找jdk目录lib目录下面有个rt.jar加进去就行了
解决方案十四:
引用4楼Faneney的回复:
引用2楼ticmy的回复:http://code.google.com/p/yoyoplayer/这个。。我下载了一个,怎么全是jar?
在dos下输入java-jar目下的的YOYOPlayer.jar
解决方案十五:
好像只能播放wav格式的音频
解决方案:
引用9楼Faneney的回复:
引用6楼akemi_homura的回复:引用5楼akemi_homura的回复:我听歌用的播放器就是自己用javaswing写的。我在百度网盘http://pan.baidu.com/share/link?shareid=110575&uk=2165635302放了一份,楼主可以先看下。我这个需要32位的java虚拟机,不支持64……
那个路径是你MP3音乐所在的路径。
解决方案:
比方我的音乐在D:/music文件夹下这样设置就行了
解决方案:
引用16楼akemi_homura的回复:
比方我的音乐在D:/music文件夹下这样设置就行了
然后程序会扫描该文件夹,能够播放的音乐格式的文件会被加载并播放。
解决方案:
这个代码能播MP3publicclassMP3Player{publicvoidtestPlay(Stringfilename){try{Filefile=newFile(filename);AudioInputStreamin=AudioSystem.getAudioInputStream(file);AudioInputStreamdin=null;AudioFormatbaseFormat=in.getFormat();AudioFileFormatbaseFileFormat=AudioSystem.getAudioFileFormat(file);System.out.println(baseFileFormat);System.out.println(baseFileFormat.properties());AudioFormatdecodedFormat=newAudioFormat(AudioFormat.Encoding.PCM_SIGNED,baseFormat.getSampleRate(),16,baseFormat.getChannels(),baseFormat.getChannels()*2,baseFormat.getSampleRate(),false);din=AudioSystem.getAudioInputStream(decodedFormat,in);//Playnow.rawplay(decodedFormat,din);in.close();}catch(Exceptione){}}privatevoidrawplay(AudioFormattargetFormat,AudioInputStreamdin)throwsIOException,LineUnavailableException{byte[]data=newbyte[4096];SourceDataLineline=getLine(targetFormat);if(line!=null){//Startline.start();intnBytesRead=0;intnBytesWritten=0;while(nBytesRead!=-1){nBytesRead=din.read(data,0,data.length);if(nBytesRead!=-1)nBytesWritten=line.write(data,0,nBytesRead);}//Stopline.drain();line.stop();line.close();din.close();}}privateSourceDataLinegetLine(AudioFormataudioFormat)throwsLineUnavailableException{SourceDataLineres=null;DataLine.Infoinfo=newDataLine.Info(SourceDataLine.class,audioFormat);res=(SourceDataLine)AudioSystem.getLine(info);res.open(audioFormat);returnres;}publicstaticStringtoHexString(byte[]b){if(b==null)returnnull;StringBuildersb=newStringBuilder();for(bytex:b){Stringtt=Integer.toHexString(x&0xff);sb.append(tt).append("00".substring(tt.length()));}returnsb.toString();}publicstaticbyte[]md5(Stringstr){MessageDigestmd;byteb[]=null;try{md=MessageDigest.getInstance("MD5");md.update(str.getBytes());b=md.digest();}catch(NoSuchAlgorithmExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}returnb;}/***@paramargs*/publicstaticvoidmain(String[]args){MP3Playerplayer=newMP3Player();player.testPlay("e:/temp/1111.mp3");}}
解决方案:
大神们学习了
解决方案:
天啊,我都晕了~!亲们,晚上的时候我再试试,今天应该能结贴~
解决方案:
不能播放MP3格式的啊
解决方案:
引用18楼hbwhwang的回复:
这个代码能播MP3publicclassMP3Player{publicvoidtestPlay(Stringfilename){try{Filefile=newFile(filename);AudioInputStreamin=AudioSystem.getAudioInputStream(file);AudioInputStreamdin=null;AudioFormatbaseFormat=in.getFormat();AudioFileFormatbaseFileFormat=AudioSystem.getAudioFileFormat(file);System.out.println(baseFileFormat);System.out.println(baseFileFormat.properties());AudioFormatdecodedFormat=newAudioFormat(AudioFormat.Encoding.PCM_SIGNED,baseFormat.getSampleRate(),16,baseFormat.getChannels(),baseFormat.getChannels()*2,baseFormat.getSampleRate(),false);din=AudioSystem.getAudioInputStream(decodedFormat,in);//Playnow.rawplay(decodedFormat,din);in.close();}catch(Exceptione){}}privatevoidrawplay(AudioFormattargetFormat,AudioInputStreamdin)throwsIOException,LineUnavailableException{byte[]data=newbyte[4096];SourceDataLineline=getLine(targetFormat);if(line!=null){//Startline.start();intnBytesRead=0;intnBytesWritten=0;while(nBytesRead!=-1){nBytesRead=din.read(data,0,data.length);if(nBytesRead!=-1)nBytesWritten=line.write(data,0,nBytesRead);}//Stopline.drain();line.stop();line.close();din.close();}}privateSourceDataLinegetLine(AudioFormataudioFormat)throwsLineUnavailableException{SourceDataLineres=null;DataLine.Infoinfo=newDataLine.Info(SourceDataLine.class,audioFormat);res=(SourceDataLine)AudioSystem.getLine(info);res.open(audioFormat);returnres;}publicstaticStringtoHexString(byte[]b){if(b==null)returnnull;StringBuildersb=newStringBuilder();for(bytex:b){Stringtt=Integer.toHexString(x&0xff);sb.append(tt).append("00".substring(tt.length()));}returnsb.toString();}publicstaticbyte[]md5(Stringstr){MessageDigestmd;byteb[]=null;try{md=MessageDigest.getInstance("MD5");md.update(str.getBytes());b=md.digest();}catch(NoSuchAlgorithmExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}returnb;}/***@paramargs*/publicstaticvoidmain(String[]args){MP3Playerplayer=newMP3Player();player.testPlay("e:/temp/1111.mp3");}}
需要导入的包呢???能给我吗?
解决方案:
publicclassEmbeddedMediaPlayerextendsApplication{privatestaticfinalStringMEDIA_URL="http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv";@Overridepublicvoidstart(StageprimaryStage){primaryStage.setTitle("EmbeddedMediaPlayer");Grouproot=newGroup();Scenescene=newScene(root,540,253);Mediamedia=newMedia(MEDIA_URL);MediaPlayermediaPlayer=newMediaPlayer(media);mediaPlayer.setAutoPlay(true);MediaControlmediaControl=newMediaControl(mediaPlayer);scene.setRoot(mediaControl);primaryStage.setScene(scene);primaryStage.show();}publicstaticvoidmain(String[]args){launch(args);}}
publicclassMediaControlextendsBorderPane{privateMediaPlayermp;privateMediaViewmediaView;privatefinalbooleanrepeat=false;privatebooleanatEndOfMedia=false;privateDurationduration;privateSlidertimeSlider;privateLabelplayTime;privateSlidervolumeSlider;privateHBoxmediaBar;publicMediaControl(finalMediaPlayermp){this.mp=mp;setStyle("-fx-background-color:#bfc2c7;");mediaView=newMediaView(mp);PanemvPane=newPane(){};mvPane.getChildren().add(mediaView);mvPane.setStyle("-fx-background-color:black;");setCenter(mvPane);mediaBar=newHBox();mediaBar.setAlignment(Pos.CENTER);mediaBar.setPadding(newInsets(5,10,5,10));BorderPane.setAlignment(mediaBar,Pos.CENTER);finalButtonplayButton=newButton(">");playButton.setOnAction(newEventHandler<ActionEvent>(){publicvoidhandle(ActionEvente){Statusstatus=mp.getStatus();if(status==Status.UNKNOWN||status==Status.HALTED){//don'tdoanythinginthesestatesSystem.out.println("Playerisinabadorunknownstate,can'tplay.");return;}if(atEndOfMedia){//rewindthemovieifwe'resittingattheendatEndOfMedia=false;mp.seek(mp.getStartTime());playButton.setText("||");}elseif(status==Status.PAUSED||status==Status.READY||status==Status.STOPPED){mp.play();}else{mp.pause();}}});mp.currentTimeProperty().addListener(newInvalidationListener(){publicvoidinvalidated(Observableov){updateValues();}});mp.setOnPlaying(newRunnable(){publicvoidrun(){System.out.println("onPlaying");playButton.setText("||");}});mp.setOnPaused(newRunnable(){publicvoidrun(){System.out.println("onPaused");playButton.setText(">");}});mp.setOnReady(newRunnable(){publicvoidrun(){System.out.println("onReady");duration=mp.getMedia().getDuration();updateValues();}});mp.setCycleCount(repeat?MediaPlayer.INDEFINITE:1);mp.setOnEndOfMedia(newRunnable(){publicvoidrun(){System.out.println("onEndOfMedia");if(!repeat){playButton.setText(">");atEndOfMedia=true;}}});mediaBar.getChildren().add(playButton);//AddspacerLabelspacer=newLabel("");mediaBar.getChildren().add(spacer);//AddTimelabelLabeltimeLabel=newLabel("Time:");mediaBar.getChildren().add(timeLabel);//AddtimeslidertimeSlider=newSlider();HBox.setHgrow(timeSlider,Priority.ALWAYS);timeSlider.setMinWidth(50);timeSlider.setMaxWidth(Double.MAX_VALUE);timeSlider.valueProperty().addListener(newInvalidationListener(){publicvoidinvalidated(Observableov){if(timeSlider.isValueChanging()){/**multiplydurationbypercentagecalculatedbyslider*position*/mp.seek(duration.multiply(timeSlider.getValue()/100.0));if(atEndOfMedia){/**ifmediahasarriveditsendbeforetheseeking,*adjusttheplaybuttoncontent*/atEndOfMedia=false;playButton.setText("||");}}}});mediaBar.getChildren().add(timeSlider);//AddPlaylabelplayTime=newLabel();playTime.setPrefWidth(130);playTime.setMinWidth(50);mediaBar.getChildren().add(playTime);//AddthevolumelabelLabelvolumeLabel=newLabel("Vol:");mediaBar.getChildren().add(volumeLabel);//AddVolumeslidervolumeSlider=newSlider();volumeSlider.setPrefWidth(70);volumeSlider.setMaxWidth(Region.USE_PREF_SIZE);volumeSlider.setMinWidth(30);volumeSlider.valueProperty().addListener(newInvalidationListener(){publicvoidinvalidated(Observableov){if(volumeSlider.isValueChanging()){mp.setVolume(volumeSlider.getValue()/100.0);}}});mediaBar.getChildren().add(volumeSlider);setBottom(mediaBar);}protectedvoidupdateValues(){if(playTime!=null&&timeSlider!=null&&volumeSlider!=null){Platform.runLater(newRunnable(){publicvoidrun(){DurationcurrentTime=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));}}});}}privatestaticStringformatTime(Durationelapsed,Durationduration){intintElapsed=(int)Math.floor(elapsed.toSeconds());intelapsedHours=intElapsed/(60*60);if(elapsedHours>0){intElapsed-=elapsedHours*60*60;}intelapsedMinutes=intElapsed/60;intelapsedSeconds=intElapsed-elapsedHours*60*60-elapsedMinutes*60;if(duration.greaterThan(Duration.ZERO)){intintDuration=(int)Math.floor(duration.toSeconds());intdurationHours=intDuration/(60*60);if(durationHours>0){intDuration-=durationHours*60*60;}intdurationMinutes=intDuration/60;intdurationSeconds=intDuration-durationHours*60*60-durationMinutes*60;if(durationHours>0){returnString.format("%d:%02d:%02d/%d:%02d:%02d",elapsedHours,elapsedMinutes,elapsedSeconds,durationHours,durationMinutes,durationSeconds);}else{returnString.format("%02d:%02d/%02d:%02d",elapsedMinutes,elapsedSeconds,durationMinutes,durationSeconds);}}else{if(elapsedHours>0){returnString.format("%d:%02d:%02d",elapsedHours,elapsedMinutes,elapsedSeconds);}else{returnString.format("%02d:%02d",elapsedMinutes,elapsedSeconds);}}}}