Tải bản đầy đủ - 0 (trang)
Hack 73. Play a Sound with QuickTime for Java

Hack 73. Play a Sound with QuickTime for Java

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

importquicktime.std.*;

importquicktime.std.clocks.*;

importquicktime.std.movies.*;

importquicktime.*;

importquicktime.io.*;

importquicktime.app.time.*;

publicclassQTJSoundextendsObject{









FilesoundFile;

JDialogplayingDialog;

Moviemovie;















publicstaticvoidmain(String[]args){



JFileChooserchooser=newJFileChooser();



chooser.showOpenDialog(null);



Filef=chooser.getSelectedFile();



try{























}





QTJSounds=newQTJSound(f);

}catch(Exceptione){



e.printStackTrace();

}





publicQTJSound(Filef)





throwsQTException{





soundFile=f;





//prepareadialogtodisplaywhileplaying

JOptionPanepane=newJOptionPane("Playing"+f.getN





















playingDialog=pane.createDialog(null,"QTJS





playingDialog.pack();

















//getandplaysound

QTSession.open();

QTFileqtf=newQTFile(f);























OpenMovieFileomf=OpenMovieFile.asRead(qtf);



movie=Movie.fromFile(omf);



MyDemoClosercloser=newMyDemoCloser(movie);



TaskAllMovies.addMovieAndStart();



movie.start();



playingDialog.setVisible(true);

}

classMyDemoCloserextendsExtremesCallBack{







publicMyDemoCloser(Moviem)throwsQTExceptio









StdQTConstants.triggerAtStop);

callMeWhen();





}

publicvoidexecute(){







playingDialog.setVisible(false);







System.out.println("dialogclosed");







//note:thiscanhangonWindows-con







//usingQTSession.exitMovies()instead







QTSession.close();







System.out.println("closedQTSession")







System.exit(0);





}



}

}



Someofthiscodelooksveryun-Java-likeandthere'sareason:

QTJisanobject-orientedwrapperaroundastraight-CAPI.

WheneverIseetheCversionsofthingsIdoinQTJ,I'm

gratefultheygotitasOOastheydid.Nevertheless,thereare

differences:whereaJavadeveloperwouldexpecttodealwith

listeners,QTJmakesyouwrangleCallBackobjects,whichhave

toreregisterthemselveseverytimethey'recalledorelse

they'reforgotten.Andthenumberofimportsforasmallclassis

quiteatypicalQTJishighlygranularinitsclassorganization.



Takealookattheconstructor.Afterdoingthefile-selection

dialog,itcallsQTSession.open().Thisisacallthatinitializes

QuickTimeresourcesandmustbemadebeforeanyotherQTJ

call,oranexceptionwillbethrown.You'llberesponsiblefor

shuttingdownQuickTimelater,ofcourse.

Thebasicthingyouwanttodoistousethefiletocreatea

Movie.Don'tworry,thisisn'tturningintoavideohack;

QuickTimeusesthetermmovieforanyplayableordisplayable

thingitworkswith:audio,video,audioandvideo,Flash,static

images,etc.TocreatetheMovie,youneedanOpenMovieFile,which

yougetbymakingaQTFilefromjava.io.Fileandthenusingthe

staticasRead()togetanOpenMovieFile.

Thedemosetsupacallbackbycreatinganinstanceofthe

innerclassMyDemoCloser,callsthecryptic

TaskAllMovies.addMovieAndStart()(moreonthatlater),andfinally

startstheaudiowithMovie.start().IfthesourceisaURL,ora

fileonreallyslowmedia,itmighthelptocallMovie.prePreroll()

andMovie.preroll()beforestarting,toletQuickTimepre-allocate

neededsystemresourcesandreadinsomedata.

Settingupacallbacktocloseeverythingdownrequiresuseof

anExTRemesCallBack,whichisanobjectthatgetscalledwhen

eitherthebeginningorendofthemovieisreached.Its

constructortakesthemovie'stimebase(whichisanobject

representingthemovie'stime-keepingsystem)andaflagto

indicatewhatconditionsthecallbackshouldbecalledin.The

flagisanint,butitreallycontainsbitvaluesthatcanbeORed

together.Forexample,ifthemediacouldplayinbothdirections

andyouwantedtobenotifiedwhenitreachedthebeginningof

themovietoo,you'dpassStdQTConstants.triggerAtStop|

StdQTConstants.triggerAtStart.

Next,youhavetousecallMeWhen()toregisterthecallback.This

signsyouupforonecallbackifyou'recalledandarestill

interestedinfutureevents,youhavetoreregisterwithanother

callMeWhen().



Whenthesoundfinishes,thecallbackcallsexecute().Thisis

whenyoushuteverythingdown,asintheotherhacks.Notice

thatyouclosedownQuick-Timewith QTSession.close(),the

obviouscounterparttoQTSession.open().Therearesomeissues

abouthowwellitworksonWindows:itsometimeshangsfor

me,andyoumaywanttousethesaferQTSession.exitMovies(),

whichonlyclosesdownsomeofQTJ,buttherestseemstoget

takencareofbyQTJitself,asI'veneverhadaproblem.

AndonemorebitofarcaneQTJlore:thecodemakesacallto

TaskAllMovies.addMovieAndStart().Thishelpsdealwiththefactthat

movieshavetoexplicitlybegivenCPUtime,withcallstoa

task()method,inordertowork.TaskAllMoviesisaconvenience

Threadthatcanperiodicallymakethistaskingcallforallyour

movies.Ifyou'vereadChris'bookonQTJ,youwouldthinkthat

thisisn'tnecessary,ashavingtheAWTeventdispatchthread

usuallyprovidestaskingcalls.Theproblemisthatthedialog

boxthat'sshowingwhiletheaudioplaysismodal;thus,it

blockstheeventloop,whichinturnblocksthetaskingyou

usuallygetforfreewithAWT.So,youhavetosetitupyourself.



QTJisfullofweirdgotchaslikethis.Whatdoyouexpectwhenit's

largelyaportfromC?



10.5.2.CompilingQuickTimeCode

Yep,thishackhasspecialcompileinstructions.First,youhave

tobesurethatyourmachineevenhasQuickTimeforJavaonit.

It'sinstalledbydefaultwithMacOSX,sothisisonlyanissue

forWindows-baseddevelopers.OnWindows,ifyoudon'thave

QuickTimeatall,getitfromhttp://www.apple.com/quicktime/

anddoacustominstall:QuickTimeforJavawillbeoneofthe



non-defaultoptionalpieces,andyoujustneedtocheckmarkit

toincludeitinyourinstall.IfyoudohaveQuickTime,runthe

QuickTimeUpdaterfromyourStartmenuoryourtraytodoa

"custom"update,whichwillshowthesamelistofoptional

piecesasthemaininstaller.

TheinstallorupdatewillputQTJava.zipintothelib/extofany

Javahomefoldersitfinds.Itshouldalsoputacopyin

C:\windows\system32andaddasystem-wideenvironment

variableQTJAVApointingtooneofthesefiles,withthepathin

quotes(whichmayormaynotbegoodforyou,dependingon

whatelseyoudowithenvironmentvariables).

Here'sthefunpartaboutcompiling:youmustexplicitlypoint

yourcompiletimeclasspathtooneoftheseQTJava.zipfilesfor

javac(orjikes,orwhatever)tofindtheQTJclasses.Ifyoudon't,

you'llgetabunchofcompiletimeerrorslike:

QTJSound.java:4:packagequicktime.stddoesnotexist

importquicktime.std.*;

^

QTJSound.java:5:packagequicktime.std.clocksdoesnotexist

importquicktime.std.clocks.*;

^

QTJSound.java:6:packagequicktime.std.moviesdoesnotexist

importquicktime.std.movies.*;



So,assumingyouwanttoworkwithacopyofJavainstalledin

ProgramFiles\Java\j2re1.4.2_06(whichismycurrentpath…

yoursmayvary),youcompilethisdemowiththefollowing

command:



C:\>javac



-classpath"c:\ProgramFiles\Java\j2re1.4.2_06\lib\ext\



QTJSound.java



ThisshouldbetypedasonelineI'veword-wrappedtoaccommodatethe

book'smargins.



YoucansubstituteanyotherpathtoaQTJava.zipfileforthe

classpathifyoufinditmoreconvenient,orjustwriteanAnt

buildfiletoautomateeverythingforyou.

OnMacOSX,thelocationofQTJava.zipisneveramystery

becausethesysteminstallerputsitin

/System/Library/Java/Extensions.QTJava.zip.So,youcompile

with:

[aeris:HacksBook/Media/52]cadamson%javac-classpath



/System/Library/Java/Extensions/QTJava.zip



QTJSound.java



Ineithercase,you'llprobablyberelievedtoknowthatyou

don'thavetospecifytheclasspathwhenrunningaQTJ

application.



10.5.3.RunningtheCode

LiketheJMFport[Hack#72],QTJSoundlooksandfeelsmoreor

lessthesameastheoriginalCoreJavaSound[Hack#71].The

bigdifferenceisinthesupportedsoundfileformats.QuickTime

willopennotjustuncompressedWAVsandAIFFs,but

compresseddatainthoseformats,alongwithMP3s,AACs,

3GPPmobileaudiofiles,iTunesMusicStorefiles,audiotracksof



variousaudio/videoformatslikeQuickTimemovies(.mov),

MPEG-4,evenaudioCDtracks(butonlyontheMac).

That'sobviouslythebigwinwithQuickTimeforJava:youget

supportforalotmoreformats.Thepriceyoupayisthatyour

codeonlyrunsontwooperatingsystemsandthatitcanbe

difficulttowrite.Theidealwouldbeiftheobviouspointsof

extensibilityinJavaSoundandJMFhadbeenexploited,sothat

moreformatswouldbeavailablewhenusingthoseAPIs.Witha

notableexception[Hack#74],thathasn'thappenedyet.



Bytheway,tolearnmoreaboutQuickTimeforJava,checkout

QuickTimeforJava:ADeveloper'sNotebook(O'Reilly).



Hack74.AddMP3SupporttoJMF



MP3sareeverywhere,andbyinstallingaplug-inyoucan

usethemwithJavaMediaFramework,too.

Itusedtobesaidthateveryprogramwillcontinuetogrowuntil

itincludesanemailreader.Todaywecouldsaythesamefor

MP3players.Theyareeverywhere,andanyprogramthathas

plug-inswilleventuallybegivenamusicplayer.PlayingMP3sin

Javausedtobequiteanordeal,involvingasuiteoftoolkitsand

codecsfromdifferentsources.Fortunately,it'saloteasierto

playanMP3filethesedays,andthishackshowshow.

JMFcameoutin1998,supportingplaybackofanumberof

audioandvideoformats,butnotMP3.Supportforthispopular

formatarrivedwithJMF2.0in1999.Unfortunately,in2002,

SunremovedMP3supportfromJMFbecauseoflicensing

problems.Finally,inNovemberof2004,Sunreleasedafully

licensedMP3plug-inforpublicdownloadontheirwebsite.With

thisplug-in,youcanplayanyMP3filewithonlyfourlinesof

code.



10.6.1.AddaPlug-IntoJMF

First,installJavaMediaFramework[Hack#72].ToaddMP3

support,downloadtheplug-infrom

http://java.sun.com/products/javamedia/jmf/mp3/download.html.Thedownloadpageoffersan

.exeinstallerforWindowsandaZIPforotherplatforms.Inboth

cases,thereisanmp3plugin.jarfilethattheinstalldocssay

youneedtoplaceintheext/libdirectoryofanyJREyouwantto

providetheplug-into.WiththeJARinyourclasspath,you



installtheplug-inwiththefollowingcommand:





javacom.sun.media.codec.audio.mp3.JavaDecoder



OnMacOSX,theproperwaytoaddJARfilestotheclasspathistoput

themin/Library/Java/Extensions,insteadofusingtheactualext/lib

directory,whichishardtofindandwillbewipedoutbysystem

installersandupdatesanyways.



10.6.2.SimplicityIsNice

Example10-6isthecodeforprettymuchthesimplestMP3

playingprogramyoucancreate.Youwillneedtoimport

javax.media.*inadditiontotheusualjava.ioclasses.



Example10-6.AverybasicMP3player

importjavax.media.*;

publicclassMP3Player{













}



publicstaticvoidmain(String[]args)throwsException



Filefile=newFile("test.mp3");



MediaLocatormrl=newMediaLocator(file.toURL(



Playerplayer=Manager.createPlayer(mrl);



player.start();

}



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

Hack 73. Play a Sound with QuickTime for Java

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

×