Tải bản đầy đủ - 0 (trang)
Chapter 9. The Mac OS X Speech Framework

Chapter 9. The Mac OS X Speech Framework

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

ApplehasmadeJava-basedframeworksforbothtext-to-speech

andvoicerecognitionavailableasfreelydownloadablepackages

fromtheAppleDeveloperConnection(ADC).Thenativesupport

isalreadyincludedinMacOSX,butthedownloadable

frameworksincludetherequiredJavabindingsand

documentationtomakethemusefulprogrammatically.You'll

needtoregisterwiththeADCtodownloadthetoolkit;free

registrationisavailableathttp://www.apple.com/developer/.



Currently,theSpeechFrameworkreliesonApple'sJDirect

implementation(asdescribedinChapter5).SinceJDirectisn'tincluded

intheMacOSXJDK1.4implementation,itmaybesometimebefore

animplementationoftheSpeechFrameworkismadeavailableforJDK

1.4-basedapplications.Visithttp://developer.apple.com/java/forthe

latestinformation.Inthemeantime,you'llhavetoconsiderspeecha

JDK1.3-onlyfeature.



Beforedivingintothecode,considerthisadvicebeforeusing

speechinyourapplications:

Youcan'trequirespeechinputforyourapplicationunless

youarewillingtoconstraintheuseofyourapplication.I

wrotemostofthischapterinacoffeeshop.Text-to-speech

workedwellwithmyheadphones,butIwasn'tboldenough

totalktomyiBookinpublic.IfI'mhesitant,yourusers

mightbe,too.

It'seasierand(arguably)moreusefultoaddtext-to-speech

toyourapplicationthantoaddspeechrecognition.Also,

justbecauseyouaddone,itdoesn'tmeanthatyoumust

addboth.I'dsuggestaddingtext-to-speechcapabilitiesfirst

andspeechrecognitionsecond.

Whenusingtext-to-speech,includeaneasywayforthe

usertostopthesystemfromspeaking.Ifyouuseatalking

alertdialog,turnoffthesoundiftheuserclicksthemouse



anywhere,notjustonabutton.Includeanoptionthatturns

speechoffandoneasilyandgloballyinyourapplication.If

you'reworkingonagame,pausethespeechenginewhen

youpausetherestofthegame.

Don'tforgetthatthehardwareandenvironmentcanaffect

theutilityofbothtechnologies.Also,non-nativeEnglish

speakerscansometimesfindspeakingsystemsdifficultto

useorunderstand.



15.3SOAP

TheSimpleObjectAccessProtocol(SOAP)isamorecomplex

RPCmechanismthanXML-RPC,butbothshareacommonbasis

(anunderlyingprotocolbasedonXMLandHTTP)and

conceptualmodel.SOAPaddsmanyfeaturestoRPC,including

explicitsupportforasynchronousmessagedeliveryviathe

SimpleMailTransportProtocol(SMTP),thebasisfordeliveryof

Internetemail.

TheuseofSOAPversusXML-RPCdependslargelyonthe

eventualtargetuseofyourapplicationandwhoorwhatyou're

communicatingwith.Generally,thesimplicityofXML-RPChas

ledtowidespreadadoption,whereastheoverallsophistication

andcapabilitiesofSOAPhaveledtobroaderadoptioninthe

enterprise(nottomentiontheexplicitendorsementofSOAPby

entitiessuchasMicrosoftandIBM).

ThischapterlooksatApacheAxis1.0,anopensource

implementationoftheSOAP1.1specificationprovidingboth

serverandclientcapabilities.



15.3.1ObtainingAxis

YoucandownloadApacheAxis1.0from

http://xml.apache.org/axis/.ThedownloadusedhereisRelease

1.0fromhttp://xml.apache.org/axis/releases.html.



15.3.2Installation

Therestofthischapterassumesthatyouareworkingwith

JBoss,installedasdescribedinChapter14.



TheprocessofinstallingAxisunderTomcatissimilartoinstallation

underJBoss.Forcompleteinstructions,referto



http://cvs.apache.org/viewcvs.cgi/~checkout~/xmlaxis/java/docs/install.html.



SOAPrequiresaservlet(or,sometimes,severalservlets)to

receiverequests,andthenrespondtothoserequests,viaHTTP.

Usingaservletletsyouavoiddealingwithnetworksockets

manually,whichisalwaysahassle.

AxiscomesprepackagedwithaWARdirectory,readytoinstall

inawebcontainerorapplicationserver.



IfyoudecidetoinstallAxismanuallyoronanothersystemlater,the

corelibrariesareinthefollowingJARfiles:

axis-1_0/lib/axis.jar

axis-1_0/lib/jaxrpc.jar

axis-1_0/lib/saaj.jar

axis-1_0/lib/commons-logging.jar

axis-1_0/lib/commons-dicovery.jar

axis-1_0/lib/wsdl4j.jar



WhileyoucansetupAxistoexposeanyJavaclassasaweb

service,oneofitsbestfeaturesisitsabilitytoexposeJavaWeb

Servicefileswithlittle(orno)developerintervention.



15.3.2.1WhatisJWS?

AJavaWebService(JWS)fileisanordinaryJavasourcefile

withadifferentextension(.jws),placedinaspecificdirectory

exposedaspartofawebapplication.Whenarequestismade

foraJWSfile,AxiscompilesthefileasifitwereaJavafile,



addingadditionalwrapperstomaketheobjectsandmethods

withinavailabletotheremotecaller.Inthisway,itoperates

muchlikeaJSPfile,butinsteadofprovidingHTMLdocuments

towebbrowsers,JWSfilesprovidewebservices.

OneofJWS'skeyadvantagesisthatitisamucheasier

developmentmodelthanatraditionaledit/compilecycle,like

JSPsorservlets.InsteadofpackagingyourfilesasaWARfile

andthendeployingthem,youcanworkdirectlyonthefilesina

deploymentdirectory,withAxishandlingcompilation(and

recompilation)asrequestscomeinfromclients,allduetothe

.jwsextension.



15.3.2.2Copyingthefiles

TofacilitateusingJWSfiles,installAxisinJBossnotasasealed

WAR,butasadirectorythatyoucandeploydirectly,asshown

below:



[Luthien:~/Public/xml-axis-10]wiverson%ls

READMElibsamples

docsrelease-notes.htmlwebapps



[Luthien:~/Public/xml-axis-10]wiverson%cdwebapps/axi



[Luthien:xml-axis-10/webapps/axis]wiverson%mkdir/usr

default/deploy/axis.war



[Luthien:xml-axis-10/webapps/axis]wiverson%cp-r*/u

server/default/deploy/axis.war/

TosupportthedynamiccompilationofJWSfileswithJBoss,add

theservletlibrarytotheAxiswebapplication'sWEB-INF/lib

directory:



[Luthien:xml-axis-10/webapps/axis]wiverson%cd/usr/lo

default/lib/



[Luthien:server/default/lib]wiverson%cpjavax.servlet

war/WEB-INF/lib/

IfJBossisn'talreadyrunning,startitnow.Youcanverifythat

AxisisproperlyinstalledbyviewingthedefaultAxis

managementpageathttp://localhost:8080/axis/.Ifeverything

isworkingproperly,you'llseetheconfigurationpageshownin

Figure15-7.

Figure15-7.Axisconfiguration



15.3.3SOAPBasics

SOAPisadirectdescendentofXML-RPC,proposedbysomeof

thesamevendorsthatoriginallyworkedonXML-RPC.It'sbeen

positionedastheenterpriseversionofwebservices,adding

functionalitysuchassupportformorecomplexobjects,

namespaces,andenvelopes.Itisalsoassociatedwithrelated

technologiessuchastheWebServicesDescriptionLanguage

(WSDL).Thistopicisbeyondthescopeofthistext,however.If



you'reinterestedintheseadvancedfeaturesofSOAP,consult

O'Reilly'sJavaWebServices,byDavidChappellandTyler

Jewell.

Foryourpurposeshere,SOAPisjustanotherRPCmechanism,

similartoXML-RPC.Therearesignificantdifferencesinthe

protocolsusedtocommunicatebetweensystemsandthe

implementationlibraries,buttheconceptualmodelisthesame

astheoneshowninFigure15-2.

ServerapplicationdevelopmentismosteasilyhandledviaJWS

files,describedabove.Clientdevelopmentissimilartothatof

XML-RPC,withaslightlydifferentsetofclasses.An

org.apache.axis.client.Serviceobjectbindstoa

specificremoteserver,andan

org.apache.axis.client.Callobjectexecutesaremote

method.Thissectioncreatesa.jwsfileforyourserveranduses

theseclientAPIstoretrievethemethods'results.



15.3.4BuildingaSOAPWebService

Thewebserviceyou'llbuildforAxisismuchliketheoneyou

builtforXML-RPC.AddafilecalledSimpleWebService.jwstothe

/usr/local/jboss/server/default/deploy/axis.wardirectorywith

thecontentsshowninExample15-6.

Example15-6.Asimplewebservice



publicclassSimpleWebService

{

publicSimpleWebService()

{

}





publicintadd(inta,intb)

{

returna+b;

}



publicStringnow()

{

returnnewjava.util.Date().toString();

}



publicStringslownow()

{

synchronized(this)

{

try

{

this.wait(5000);

}catch(java.lang.InterruptedExceptione)

{}

}

returnnewjava.util.Date().toString();

}



}

You'llnoticethattheJWSappearstobeanordinaryJavaclass.

AxisoffersothermechanismsforhandlingSOAPrequeststhat

providemorecontrol,butformanyservices,theJWS

mechanismismorethanadequate.



15.3.5AccessingaSOAPWebServicefromJava

Theeasiestwaytotalktothewebserviceisdirectlyfromyour



browser'saddressbar.AsshowninFigure15-8,youcansimply

requestawebserviceviaanHTMLrequest,like

http://localhost:8080/axis/SimpleWebService.jws?

method=now.

Figure15-8.The"now"functionviaanHTTPGETrequest



Youcanalsosendparametersviatherequestparametersofa

URL,suchashttp://localhost:8080/axis/SimpleWebService.jws?

method=add&a=1&b=2.Inthisexample,theparameternames

providedontheURL(aandb)aren'tsignificant.However,for

morecomplexwebservicestheyareimportant,asthey

associatevalueswithspecificparametersincode.Figure15-9

showstheresultsofthisrequest.

Figure15-9.The"add"functionalityviaanHTTPGET

request



Example15-7showshowtoaccessSOAPviaJava.SOAPis

morecomplexthanXML-RPC,andthereforerequiresabitmore

setupandconfiguration.Italsoaffordsagreatdealmore

sophistication,however,andifyourapplicationrequiresvery

specificdetailsaboutthemethodsinvokedandhowtheyare

interactedwith,itcanbewellworththeextrawork.

Example15-7.AccessingSOAPservices



packagecom.wiverson.macosbook.webservices;

importorg.apache.axis.client.Call;

importorg.apache.axis.client.Service;

importjavax.xml.namespace.QName;

importcom.wiverson.macosbook.SimpleEdit;



publicclassSOAPClientPluginimplements

com.wiverson.macosbook.SimpleEditPlugin

{

publicSOAPClientPlugin()

{

}



publicvoiddoAction(SimpleEditframe,java.awt.eve

{

frame.appendDocumentText(this.remoteCall());

}



publicStringgetAction()

{

return"SOAPClient";

}



publicvoidinit(SimpleEditframe)

{

}



publicstaticvoidmain(String[]args)

{

System.out.println(newSOAPClientPlugin().remot

}





publicStringremoteCall()

{

try

{

StringwebserviceLocation=

"http://localhost:8080/axis/SimpleWebServic



Serviceservice=newService();

Callcall=(Call)service.createCall(



call.setTargetEndpointAddress(newjava.net.



return(String)call.invoke("now",null);



}catch(Exceptione)

{

System.err.println(e.toString());

}

return"Unabletoconnect.";



}



}

15.3.6AccessingaSOAPWebServicefromAppleScript

SOAPmightbemorecomplexthanXML-RPC,butaSOAPclient

isbuiltintoAppleScriptaswell,asshowninFigure15-10.

Figure15-10.ScriptingaSOAPclient



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

Chapter 9. The Mac OS X Speech Framework

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

×