Tải bản đầy đủ - 0 (trang)
Hack 71. Play a Sound with JavaSound

Hack 71. Play a Sound with JavaSound

Tải bản đầy đủ - 0trang











FilesoundFile;

JDialogplayingDialog;

Clipclip;

























publicstaticvoidmain(String[]args){



JFileChooserchooser=newJFileChooser();



chooser.showOpenDialog(null);



Filef=chooser.getSelectedFile();



try{





CoreJavaSounds=newCoreJavaSound(f)



}catch(Exceptione){





e.printStackTrace();



}

}























publicCoreJavaSound(Filef)



throwsLineUnavailableException,IOException,







UnsupportedAudioFileException{



soundFile=f;



//prepareadialogtodisplaywhileplaying



JOptionPanepane=newJOptionPane("Playing"

















playingDialog=pane.createDialog(null,"Appli



playingDialog.pack();





























//getandplaysound



Line.Infolinfo=newLine.Info(Clip.class);



Lineline=AudioSystem.getLine(linfo);



clip=(Clip)line;



clip.addLineListener(this);



AudioInputStreamais=AudioSystem.getAudioInpu



clip.open(ais);



clip.start();

}

//LineListener

publicvoidupdate(LineEventle){







LineEvent.Typetype=le.getType();





if(type==LineEvent.Type.OPEN){







System.out.println("OPEN");





}elseif(type==LineEvent.Type.CLOSE){







System.out.println("CLOSE");







System.exit(0);

}elseif(type==LineEvent.Type.START){







System.out.println("START");







playingDialog.setVisible(true);





}elseif(type==LineEvent.Type.STOP){







System.out.println("STOP");





}



}

}



TheJavaSoundAPIforworkingwithsampledsoundsisan

elaborateperhapsevenbaroquesetofabstractionsaboutthe

variouspartsofasoundsystem.Thepointofentryisan

AudioSystem,whosevariousstaticmethodsletyougetatthe

differentsoundresources.TheseincludeLines,whichareaudio

feeds(inputoroutput);Mixers,whichcombinelines;

AudioInputStreams,whichrepresentincomingaudiodata;and

formatconversions.Linehasasub-interfacecalledDataLine,

whichhasasub-interfacecalledClip,whichrepresentsaline

thatcanbeloadedintomemoryandplayedimmediately,

insteadofstreamingoutfromitssource.Ifyourdataissmall

enoughtofitinmemorywhilebeingplayed,thisisa

particularlyconvenientclasstoworkwith.



Ifyouraudioisnotsmallenoughtofitinmemory,checkouthowto

playJavaSoundfilesofanylength[Hack#76]laterinthischapter.



ToplayaudioinJavaSound,youneedtosetupaDataLineand

callitsstart()method.Easiersaidthandone,thoughthisisthe

baroquepart.

ThereareacoupleofwaystogetaLine.Inthemostbasiccase,

youjustindicatethatyouwantalinethatcanworkwithagiven

class.BecausethisexampleworkswithClips,itasksfora

Line.InfoobjectsuitableforusewithClips.Thenyoupassthat

infoobjecttotheAudioSystemtogetaLine,whichcanbecasttoa

Clipsincethat'swhatyouaskedforinthefirstplace.

Beforesettingupthemediadata,thisexamplesetsupa

LineListener,whichwillprovideeventswhenthemediais

opened,startsplaying,stopsplaying,andisclosed.

OK,you'vegotaClip,sohere'showtogetsomeaudiodatainto

it.YoucreateanAudioInputStreamfromthestatic

getAudioInputStream()method,thenpassittoClip'sopen()method.

Thismakestheclipoperational:itprefetchesanyneeded

systemresourcesandentersa"readytoplay"state.Now,you

canjustplaytheaudiowiththestart()method,inheritedfrom

DataLine.

TheexamplesetsupaLineListenerontheClipandlooksatthe

typeofreceivedeventsforfourvaluesdefinedinthe

LineEvent.Typeclass:OPEN,CLOSE,START,andSTOP.Alloftheseare

loggedtostandardout,andthenanappropriateactionistaken:

STARTmakesthedialogvisible,STOPhidesthedialogandcloses

theclip(thisiscalledwhenyouOKthedialog),andCLOSEexits

theapplication(andiscalledasasideeffectofclip.close()in

thehandlingofSTOP).

Therearealotmoreclassesinthepackage,andyoucanwrite

reallyconfusingcodewiththemandIhaven'tevenmentioned

MIDI.Butforthestatedgoalofplayingasmallaudiofilewitha

minimumoffuss,that'showyoudoitwithJavaSound.



10.3.2.ListenUp

Whenyourunthedemoprogram,itbringsuparegular

JFileChooser.Youneedtopickasoundfilefromoneof

JavaSound'ssupportedfileformats…ofwhichthereareonly

three:WAV,AIFF,andAU(notMP3,WMA,orOgg).Youknew

therehadtobeacatch,right?Moreover,bydefault,JavaSoundonlyplaysuncompressedsoundfiles,soifthedatain

thefileisinALAW,ULAW,MACE,etc.,itwon'tplay.

IfJavaSoundcanreadit,itwillstartplayingthechosenfile

immediately.ThedemoalsoshowsadialoglikeFigure10-3,

showingthenameofthechosenaudiofile.



Figure10-3.Dialogshowingcurrentsoundfile



ClickingtheOKbuttonclearsthedialogandunblockstheAWT

sothatwhentheclipfinishesplaying,theSTOPeventcan

removethedialogfromthescreenandclosetheclip,which

exitsthedemo.

WorkingwiththeAudioSystemandhavingtopassaround

descriptionobjectsisalittlestrange,especiallywith

JavaSound'shabitofusingpublicinnerclassesasdescriptor

objects,butthankstotheClipclass,itdoesofferapretty

reasonablewaytoplaysmallaudioclipsfromyourprogram.

ThedownsidetoJavaSoundisthesmallnumberofsupported



formats.Java-Sound,atleastoutofthebox,isn'twellsuitedto

handlehavingrandomsoundformatsthrownatit.That'snota

problemifyou'resupplyingyourownsoundsforyour

applicationjuststickwithAIFForWAV.Butitdoesmake

JavaSoundlessthanusefulinamediabrowserorsomeother

applicationthatisgoingtohavetodealwithrandomformats

encounteredontheNetortheuser'slocalstorage.Ofcourse,

that'spartoftheideaofthespisub-package:Sunprovidesthe

framework,andthirdpartiesmaketheirformatsavailableto

Javabyimplementingspiinterfaces.



Hack72.PlayaSoundwithJavaMedia

Framework



UsetheJavaMediaFrameworkforbetterperformance

andsupportformoreaudioformats.

JavaMediaFramework(JMF)isSun'sattempttobringabroadly

focusedmultimediaframeworktoJava,supportingaudio,video,

andothertimebasedmediatypes.TheideaistoprovideJava

desktopapplicationswiththesefeaturesacrossoperating

systems.LikeJavaSound,it'smeanttobeextendedsothatSun

orthirdpartiescouldaddsupportfornewfileformatsorcodecs

(thecompression/decompressionencodingschemesusedinside

thosefiles).

JMFoffersanotherwaytoprovidesoundfromanapplication.

TheadvantagesofdoingsoarethatJMFmayprovideaccessto

manymoresoundfilesthanJavaSoundwillalone,andthatJMF

issomewhateasiertocodethanJavaSound,particularlyfor

simpletasks.ThedisadvantagesarethatJMFcapabilitiesvary

wildlybyplatform,andthattheenduserwillhavetoinstallJMF

separately,whichwillbedifficultorsimplynotallowedforsome

users.



10.4.1.InstallingJMF

DownloadandinstallJMFfromitshomepageat

http://java.sun.com/products/java-media/jmf/index.jspand

youshouldbereadytogonorebootrequired.Theinstallers

shouldhaveputeverythingintothecorrectpathandsetup

yourenvironment.IfyouhavetroublegettingJMFprogramsto



run,orifyouusedtheall-Javaversionthatdoesn'thavea

specialinstaller,youcantryaddingthefollowingenvironment

variable:





JMFHOME="C:\ProgramFiles\JMF2.1.1"



Next,addthetwoJMFJavalibrariestoyourclasspath:







CLASSPATH="$JMFHOME\lib\jmf.jar;$JMFHOME\lib\sound.jar;

PATH="$JMFHOME\lib;$PATH"



10.4.2.TheCode

ThedemoinExample10-4isbasicallyaportoftheCoreJavaSound

demousedinplayingaudiowithJavaSound[Hack#71],

exceptthattheeventhandlinghasbeensimplifiedtoa"quit

whendone"implementation.JMF'splaybackmetaphorinvolves

Players,whichsimplyplaymedia,andProcessors,whichmaytake

actiononthemedia,suchasaddingeffectsortranscodingto

otherformats.Thisallowsthesimplestufftostaysimple:to

playafile,youwireituptoaPlayer,telleverythingtoget

initialized("realized"inJMFparlance),andcallstart().Notice

thatwhiletheotherimportsareomittedasusual,thislisting

showstheimportjavax.media.*thatwillbringintheJMFclasses

usedhere.



Example10-4.PlayingaudiowithJavaMedia

Framework

importjavax.media.*;



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Hack 71. Play a Sound with JavaSound

Tải bản đầy đủ ngay(0 tr)

×