Tải bản đầy đủ - 0 (trang)
Chapter 9. Modifying Samples Using Ranges

Chapter 9. Modifying Samples Using Ranges

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

Chapter9.ModifyingSamplesUsing

Ranges

9.1 MANIPULATINGDIFFERENTSECTIONSOFASOUND

DIFFERENTLY

9.2 CREATEASOUNDCLIP

9.3 SPLICINGSOUNDS

9.4 REVERSINGASOUND

9.5 MIRRORINGASOUND

9.6 CONCEPTSSUMMARY



ChapterLearningObjectives

Themedialearninggoalsforthischapterare:

Tomanipulatepartsofasounddifferently.

Tocreateasoundclip.

Tosplicesoundstogethertomakesoundcompositions.

Toreversesounds.

Tomirrorsounds.

Thecomputersciencegoalsforthischapterare:



Toreturnavaluefromamethod.

Touserangesiniteration.

Tochangemorethanonevariableinaloop.

Toidentifyalgorithmsthatcrossmediaboundaries.



[Page293(continued)]



9.1.ManipulatingDifferentSectionsofaSound

Differently

Manipulatingallofthesamplesinasoundinthesamewaycan

beuseful,butreallyinterestingeffectscomefromchoppingup

soundsandmanipulatingthemdifferentially:Somewordsthis

way,othersoundsthatway.Howwouldyoudothat?Weneed

tobeabletoloopthroughportionsofthesample,without

walkingthroughthewholething.Thisturnsouttobeaneasy

thingtodo,butweneedtomanipulatesamplessomewhat

differently(e.g.,wehavetouseourforloopinaslightly

differentway).

Recallthateachsamplehasanindexnumber,andthatwecan

geteachindividualsamplevaluewithgetSampleValue(intindex)

(withanindexnumberasinput).Wecansetanysamplewith

setSampleValue(intindex,intvalue)(withinputsofanindex

number,andanewvalue).That'showwecanmanipulate

sampleswithoutusinggetSamples()andSoundSampleobjects.But

westilldon'twanttohavetowritecodelike:



[Page294]

sound.setSampleValue(0,12);

sound.setSampleValue(1,28);



Notfortensofthousandsofsamples!Sowewillcontinuetouse

aforloop.However,ifwearenotprocessingtheentiresoundin

thesameway,theindexvaluethatwestartatwon'tnecessarily

be0,andthelastindexvaluewon'tnecessarilybethelengthof

thesoundminus1.



Whatifwewanttoincreasethesoundforthefirsthalfofthe

sound,thendecreaseitinthesecondhalf.Howcouldwedo

that?Firstwewillneedtocalculatethehalfwaypoint.Wecan

determinethatbydividingthelengthofthesoundby2.Since

thelengthand2arebothintegers,theresultwillalsobean

integer,sonocastingisneeded(anyvaluesafterthedecimal

pointwillbethrownaway).Wewillneedtwoloops.Oneloop

willstartatthebeginningofsound(0)andlooptillthehalfway

point.Thesecondloopwillstartatthehalfwaypointandloopto

theendofthesound(length1).



Program71.IncreasetheVolumethenDecrease

(Thisitemisdisplayedonpages294-295intheprint

version)



/**

*Methodtoincreasethefirsthalfofthesound

*(doubleit)andthendecreasethe

*secondhalf(halfit).

*/

publicvoidincreaseAndDecrease()

{

inthalf=this.getLength()/2;

intvalue=0;

//loopthroughthefirsthalfofthesound

for(inti=0;i
{

//getthecurrentvalue

value=this.getSampleValueAt(i);

//setthevalueto2xtheoriginal

this.setSampleValueAt(i,value*2);

}

//loopthroughthesecondhalfofthesound

for(inti=half;i
{



//getthecurrentvalue

value=this.getSampleValueAt(i);



[Page295]

//setthevaluetohalftheoriginal

this.setSampleValueAt(i,(int)(value*0.5));

}

}



TherearetwoloopsinincreaseAndDecrease(),eachofwhichdeals

withonehalfofthesound.

Thefirstloopdealswiththesamplesfrom0tohalfway

throughthesound.Thosesamplesallgetmultipliedby2,to

doubletheiramplitude.

Thesecondloopgoesfromhalfwaythroughtotheendof

thesound.Here,wemultiplyeachsampleby0.5thus

decreasingthesoundby50%.



AnotherWayofWritingArrayReferences

It'sworthpointingoutthatinmanylanguages,squarebrackets

([])arestandardnotationsformanipulatingarrays.Itworks

thatwayinJava.Foranyarray,array[index]returnstheindex-th

elementinthearray.Thenumberinsidethesquarebracketsis

alwaysanindexvariable,butit'ssometimesreferredtoasa

subscript,becauseofthewaythatmathematiciansrefertothe

i-thelementofa,e.g.,ai.

Let'sdemonstratehowtogettheelementsatvariousindex

values.



>Soundsound=newSound(FileChooser.getMediaPath("croak.wav")



>SoundSample[]sampleArray=sound.getSamples();

>System.out.println(sampleArray[0]);

Sampleatindex0hasvalue0

>System.out.println(sampleArray[1]);

Sampleatindex1hasvalue0

>System.out.println(sampleArray[8000]);

Sampleatindex8000hasvalue512







[Page295(continued)]



9.2.CreateaSoundClip

Sometimesasoundistoolongandyouwantjustpartofit.This

canhappenwhenyourecordasound.Theremaybesilence

beforeandaftertheactualsound.Or,youmaywanttopullone

wordoutofasound.Youcan"clip"asoundjustasweclippeda

picturebycopyingjustpartofthesound.Whatifwewantto

pullthe"This"outofthesoundthisisatest.wav?Howcanwetell

whereitends?Openanexploreronthesoundusing

sound.explore();.Clickatthefirstflatareaafterthefirstnon-flat

area(silenceshouldhavevaluesnear0).ClickthePLAY

BEFOREbuttontoplaythepartofthesoundbeforethecurrent

index.Youcanusethearrowbuttonstochangethecurrent

indexaswell.Usingtheexplorerweseethattheword"this"

endsatabout8,500(Figure9.1).



Figure9.1.Exploringthe"Thisisatest''tofind

theendofthefirstword.

(Thisitemisdisplayedonpage296intheprintversion)



[Viewfullsizeimage]



Sotocopyjustpartofasoundintoanothersoundwewillneed

tocreateanewSoundobject.Oneofthewaystomakeanew

Soundobjectistotellithowmanysamplesitwillhave.To

calculatethenumberofsampleswecansubtracttheending

valuefromthestartingvalueandadd1.



[Page296]

Wecanthencreateanewsoundandloopcopyingfromthe

starttotheendfromthesourceSoundobjectintothetargetSound

objectstartingatthebeginningofthetargetsound.Wehaveto

makesuretoincrementboththeindexinthesourceandthe

indexinthetarget.Ifweforgettoincrementthesourceindex,

wewillcopythesamesourcesampleoverandover,andifwe

failtoincrementthetargetindex,wewillcopytothesame

placeinthetargetoverandover.

Weneedtoreturnournewsoundobjectinordertobeableto

refertoitagain.Toreturnsomethingfromamethod,weneed

tospecifythetypeofthethingthatwillbereturnedinthe



methoddeclaration(replacingthevoidkeyword).Wealsoneed

tousethekeywordreturnfollowedbywhatwewanttoreturn.



Program72.CreateaSoundClip

(Thisitemisdisplayedonpages296-297intheprint

version)



/**

*Methodtocreateanewsoundbycopyingjustpartof

*thecurrentsoundtoanewsound

*@paramstarttheindextostartthecopyat(inclusive)

*@paramendtheindextostopthecopyat(inclusive)

*@returnanewsoundwithjustthesamplesfromstartto

*endinit

*/

publicSoundclip(intstart,intend)

{

//calculatethenumberofsamplesintheclip



[Page297]

intlengthInSamples=end-start+1;

Soundtarget=newSound(lengthInSamples);//holdclip

intvalue=0;//holdsthecurrentsamplevalue

inttargetIndex=0;//indexintargetsound

//copyfromstarttoendfromsourceintotarget

for(inti=start;i<=end;i++,targetIndex++)

{

value=this.getSampleValueAt(i);

target.setSampleValueAt(targetIndex,value);

}

returntarget;

}



NoticethatwesaidthatwewouldreturnaSoundobjectfromthis

methodbysayingthatthetypeofthingreturnedisfromthe

classSound.Attheendofthemethod,weusethekeywordreturn



followedbythevariablethatreferstothenewSoundobject.So

inordertorefertothisnewSoundobjectagain,wewillneedto

declareavariableandsetthevalueofthatvariabletoreferto

thereturnedSoundobject.

>Soundtest=new

Sound(FileChooser.getMediaPath("thisisatest.wav"));

>test.explore();

>Sounds1=test.clip(0,8500);

>s1.play();

>s1.explore();



Usetheexplorerontheoriginalsoundandtheclippedsound.

Changethenumberofsamplesbetweenpixelstobe100inthe

clippedsound.Thencomparethesamplevalues.Convince

yourselfthattheclippedsounddoeshavethesamevaluesas

theoriginal(Figure9.2).



Figure9.2.Exploringthesoundclip.

(Thisitemisdisplayedonpage298intheprintversion)



[Viewfullsizeimage]



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

Chapter 9. Modifying Samples Using Ranges

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

×