SlideShare a Scribd company logo
Javascript For Sound Artists Learn To Code With
The Web Audio Api William Turner Steve Leonard
download
https://ebookbell.com/product/javascript-for-sound-artists-learn-
to-code-with-the-web-audio-api-william-turner-steve-
leonard-55920178
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Javascript For Sound Artists Learn To Code With The Web Audio Api 2nd
Ed 2nd Edition William Turner
https://ebookbell.com/product/javascript-for-sound-artists-learn-to-
code-with-the-web-audio-api-2nd-ed-2nd-edition-william-turner-43705376
Javascript For Sound Artists Learn To Code With The Web Audio Api 2nd
Ed 2nd Edition William Turner
https://ebookbell.com/product/javascript-for-sound-artists-learn-to-
code-with-the-web-audio-api-2nd-ed-2nd-edition-william-turner-43852254
Javascript For Sound Artists Learn To Code With The Web Audio Api 1st
Edition Leonard
https://ebookbell.com/product/javascript-for-sound-artists-learn-to-
code-with-the-web-audio-api-1st-edition-leonard-5744048
Javascript For R Chapman Hallcrc The R Series 1st Edition John Coene
https://ebookbell.com/product/javascript-for-r-chapman-hallcrc-the-r-
series-1st-edition-john-coene-45035150
Javascript For Web Developers Understanding The Basics 1st Edition
Mark Simon
https://ebookbell.com/product/javascript-for-web-developers-
understanding-the-basics-1st-edition-mark-simon-53488768
Javascript For Hackers Learn To Think Like A Hacker Heyes Gareth
https://ebookbell.com/product/javascript-for-hackers-learn-to-think-
like-a-hacker-heyes-gareth-57673010
Javascript For Programmers 1st Edition Paul J Deitel Harvey M Deitel
https://ebookbell.com/product/javascript-for-programmers-1st-edition-
paul-j-deitel-harvey-m-deitel-2016688
Javascript For Web Designers Mat Marquis
https://ebookbell.com/product/javascript-for-web-designers-mat-
marquis-22892838
Javascript For Impatient Programmers Es2020 Edition Dr Axel
Rauschmayer
https://ebookbell.com/product/javascript-for-impatient-programmers-
es2020-edition-dr-axel-rauschmayer-22933706
Javascript For Sound Artists Learn To Code With The Web Audio Api William Turner Steve Leonard
Javascript For Sound Artists Learn To Code With The Web Audio Api William Turner Steve Leonard
Javascript For Sound Artists Learn To Code With The Web Audio Api William Turner Steve Leonard
JavaScript for
Sound Artists
Learn to Code with the Web Audio API
JavaScript for
Sound Artists
Learn to Code with the Web Audio API
Authored by: William Turner
Edited by: Steve Leonard
CRC Press
Taylor & Francis Group
6000 Broken Sound Parkway NW, Suite 300
Boca Raton, FL 33487-2742
© 2017 by Taylor & Francis Group, LLC
CRC Press is an imprint of Taylor & Francis Group, an Informa business
No claim to original U.S. Government works
Printed on acid-free paper
Version Date: 20161208
International Standard Book Number-13: 978-1-138-96153-1 (Paperback)
This book contains information obtained from authentic and highly regarded sources. Reasonable efforts have been made to publish
reliable data and information, but the author and publisher cannot assume responsibility for the validity of all materials or the
consequences of their use. The authors and publishers have attempted to trace the copyright holders of all material reproduced in
this publication and apologize to copyright holders if permission to publish in this form has not been obtained. If any copyright
material has not been acknowledged please write and let us know so we may rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or utilized in any
form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopying, microfilming, and
recording, or in any information storage or retrieval system, without written permission from the publishers.
For permission to photocopy or use material electronically from this work, please access www.copyright.com
(http://www.copyright.com/) or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923,
978-750-8400. CCC is a not-for-profit organization that provides licenses and registration for a variety of users. For organizations
that have been granted a photocopy license by the CCC, a separate system of payment has been arranged.
Trademark notice: Product or corporate names may be trademarks or registered trademarks, and are used only for identification
and explanation without intent to infringe.
Library of Congress Cataloging-in-Publication Data
Names: Turner, William (Web site developer), author. | Leonard, Steve
(Web site developer), author.
Title: JavaScript for sound artists : learn to code with the Web Audio API /
William Turner, Steve Leonard.
Description: Boca Raton : Taylor & Francis, CRC Press, 2017.
Identifiers: LCCN 2016032832| ISBN 9781138961531 (pbk. : alk. paper) |
ISBN 9781138731134 (hardback : alk. paper)
Subjects: LCSH: Computer sound processing. | JavaScript (Computer program language) | Webcasting.
Classification: LCC TK7881.4 .T87 2017 | DDC 006.5--dc23
LC record available at https://lccn.loc.gov/2016032832
Visit the Taylor & Francis Web site at
http://www.taylorandfrancis.com
and the CRC Press Web site at
http://www.crcpress.com
Contents
Preface
Acknowledgment
1. Overview and Setup
What Is a Program?
What Is JavaScript?
HTML, CSS, and JavaScript
What Is a Web Application?
What Is the Web Audio API?
Setting Up Your Work Environment
Setup View in Browser for Windows
Setup View in Browser for Mac
How to Create Code Snippets
Accessing the Chrome Developer Tools
Troubleshooting Problems and Getting Help
2. Getting Started with JavaScript and the Web Audio API
Hello Sound Program
Variables
null
Documenting Your Code with Comments
Exploring Variables with an Oscillator
console.log()
String
Built-In String Methods
toUpperCase()
toLowerCase()
charAt()
replace()
slice()
The length Property
Numbers
How to Determine the Data Type of a Variable
Examples of Arithmetic Operators
Examples of Precedence
Math.min() and Math.max()
Math.ceil() and Math.floor()
Math.random()
Math.abs()
Number-to-String Conversion
Arrays
push()
pop()
shift()
unshift()
concat()
Summary
3. Operators
What Are Operators?
Assignment Operators
Assignment
Addition Assignment
Subtraction Assignment
Multiplication Assignment
Division Assignment
Modulo Assignment
The Boolean Data Type
Comparison Operators
Equality Operator
Strict Equality Operator
Greater Than and Less Than Operators
Greater Than or Equal to Operator
Less Than or Equal to Operator
Not Equal to Operator
Strict Not Equal to Operator
Logical Operators
The Logical AND Operator
The Logical OR Operator
The NOT Operator
Summary
4. Conditional Statements and Loops
Conditional Statements
The if Statement
The switch Statement
Ternary Operator
Loops
for Loops
Using for Loops with Arrays
while Loops
When to Use for Loops and When to Use while Loops
Summary
5. Functions
Functions—A Simple Example
Parts of a Function
Function Expressions
Abstracting Oscillator Playback
A Working Effects Box Example
The Arguments Object
Function Scope
Why You Should Always Declare Your Variables with var
Variable Hoisting
How Hoisting Affects Functions
Anonymous Functions
Closures
What Is a Closure?
Callback Functions
Working with JavaScript’s Built-In Callback Functions
filter()
map()
Recursion
Summary
6. Objects
JavaScript Data Types
Looping through Objects
When to Use Objects Rather Than Arrays
How to Check If an Object Has Access to a Particular Property or Method
Cloning Objects
Prototypal Inheritance
The "this" Keyword
The bind Function
Summary
7. Node Graphs and Oscillators
The AudioContext() Method
Node Graphs
Oscillators
The stop Method
The onended Property
How to Stop Oscillators and Restart Them
The type Property
The frequency Property
The detune Property
Summary
8. Using HTML and CSS to Build User Interfaces
What Is a User Interface?
HTML
Explanation of the HTMLTemplate
Understanding HTMLElements
Form and Input Elements
CSS
Comments
Element Selectors
Grouping Selectors
Descendent Selectors
Child Selectors
class and id
Modifying the App Interface
Margin, Border, and Padding
Removing List Element Bullet Points
Font Size, Style (Type), and Color
Centering Block-Level Elements
Summary
9. DOM Programming with JavaScript
How Does JavaScript Communicate with the DOM?
HTML
JavaScript
Building the Application
How to Trigger an Oscillator by Clicking a Button
Toggling the Start/Stop Text
Programming the Frequency Slider
Changing the Frequency in Real Time
Changing Waveform Types
Completed Code with Waveform Selection
Giving an Outline to the Selected Waveform Type
Summary
10. Simplifying DOM Programming with JQuery
What Is JQuery?
JQuery Setup
Referencing JQuery Directly
Using JQuery from a CDN
How to Use JQuery
Selecting HTMLElements
Storing DOM Selectors as Variables
Using Methods
HTML
JQuery/JavaScript to Change a Single Property
JQuery/JavaScript to Change Multiple Properties
Method Chaining
HTML
CSS
JQuery/JavaScript
HTML
JQuery/JavaScript
The this Keyword
HTML
JQuery/JavaScript
Refactoring the Oscillator Player to Use JQuery
Without JQuery
With JQuery
Setting Up the Event Listener for the User-Selected List Element
Event Listener without JQuery
Event Listener with JQuery
Modifying the Code in setInterval
setInterval Method without JQuery
setInterval Method with JQuery
onOff Method without JQuery
$onOff Selector with JQuery
Summary
11. Loading and Playing Audio Files
Prerequisites
The Two Steps to Loading an Audio File
The XMLHttpRequest Object
get Requests
A Word on Audio File Type Compatibility
Synchronous versus Asynchronous Code Execution
Processing the Audio Buffer with the Node Graph
Summary
12. Factories and Constructors
JavaScript and the Concept of Class
What Are Classes?
The Factory Pattern
Dynamic Object Extension
Private Data
Getters and Setters
Constructors and the new Keyword
Adding Methods to Constructors
The Prototype Object and the Prototype Property
Why Do Constructors Exist If You Can Do the Same Thing with Factories?
Summary
13. Abstracting the File Loader
Thinking about Code Abstraction
Creating the Abstraction
Walking through the Code
Summary
14. The Node Graph and Working with Effects
How to Think About the Node Graph
Gain Nodes
The Placement of Nodes Is Up to You
What Effects Are Available?
How to Determine the Nodes You Need to Create the Effect You Want
A Real-World Example
Some Effects Require Development Work
Summary
15. The Biquad Filter Node
Using the Biquad Filter Node
Filter Types
Creating an Equalizer
Graphic EQ
Parametric EQ
Summary
16. The Convolver Node
Convolution Reverb
Where to Get Pre-Recorded Impulse Response Files
Using Impulse Response Files
HTML
JavaScript
Controlling the Amount of Reverberation
Summary
17. Stereo Panning, Channel Splitting, and Merging
The Stereo Panner Node
The Channel Splitter
The Channel Merger
Merging All Channels of a Multichannel File into a Single Mono Channel
Using the Merger and Splitter Nodes Together
Summary
18. The Delay Node
The Delay Node
Creating Echo Effects
Creating Slap Back Effects
Creating a Ping-Pong Delay
Summary
19. Dynamic Range Compression
The Dynamics Compressor Node
Summary
20. Time
The Timing Clock
The start Method
Looping Sounds
Update Your Audio Loader Library
Changing Audio Parameters over Time
The Audio Parameter Methods
The setValueAtTime Method
The exponentialRampToValueAtTime Method
The linearRampToValueAtTime Method
The setTargetAtTime() Method
The setValueCurveAtTime() Method
Summary
21. Creating Audio Visualizations
A Brief Word on Fourier Analysis
A Brief Explanation of Binary-Coded Decimal Numbers
The Spectrum Analyzer
JavaScript/JQuery
HTML
CSS
Walking through the Code
Storing the Frequency Data in an Array
How to Think About the frequencyData Array
Building the Display Interface
Connecting the Analyzer to the DOM
Summary
22. Adding Flexibility to the Audio Loader Abstraction
The Updated Interface
Modifying the Library
Modifying audioBatchLoader
An Explanation of the Previous Code Edit
Summary
23. Building a Step Sequencer
The Problem
Can I Use setInterval or setTimeout?
The Solution
How It Works
Changing Tempo
Building the Sequencer
Playing Back Sounds in Sequence
Creating the User Interface Grid
HTML
CSS
Adding Interactivity to the Grid Elements
Summary
24. AJAX and JSON
AJAX
JSON
Making an AJAX Call to the iTunes Search API
How the Code Works
HTML
JavaScript
Creating Your Own Web API to Reference Synthesizer Patch Data
The Data Structure
HTML
CSS
How the Code Works
Building on the API
data.js
module.js
Extend the JSON Object
Summary
25. The Future of JavaScript and the Web Audio API
The Web Audio API 1.0
3D Spacial Positioning
Raw Modification of Audio Buffer Data
Suggestions for Continued Learning
JavaScript 6
node.js
The Web MIDI API
Open Sound Control
Summary
Further Reading
Book Website
Index
Preface
Learning to program can be daunting, and we want to be the first to congratulate you for taking on
the challenge! Second, we want to thank you for choosing this book.
Who Is This Book For?
This book is for anyone who is involved in the world of creative audio and wants to learn to
program using the JavaScript language. There are many programming books directed toward
artists to help them build websites, mobile applications, games, and other things, but next to none
is directed exclusively toward the sound arts community. This book is designed to fill this role
and to teach the fundamentals of web-based software development, and specifically, the basics of
the JavaScript programming language to sound artists.
What This Book Is Not
This book is not an audio technology reference. It does not take the time to explain the
fundamentals of audio theory or sound engineering in depth. Words and phrases like dynamic
range compression, convolution reverb, and sample rate are thrown around like candy with only
a cursory explanation (if they are explained at all). We assume that you are either familiar with
many of these core audio concepts or know enough to find the answers on your own. If you need
an accommodating audio technology reference, we suggest David Miles Huber’s excellent book
Modern Recording Techniques, Taylor & Francis.
This book is also not directed toward experienced programmers who are simply interested in
JavaScript or the Web Audio API. If this describes you, then you may find some value here, but
you are not the intended audience.
How to Learn to Program
The following are a few tips to help you get the most from this book.
Make Connections
Generally, it is easier to learn new things by making associations and connections to areas that
you are already familiar with. If you have ever programmed a synth or a MIDI sequencer, then you
have already done a form of programming. The contents of this book are designed to be a bridge
that connects a world you are (presumably) familiar with (sound and audio technology) to a topic
you are less familiar with—JavaScript and programming. We suggest that you tap into whatever
has drawn you to sound art while learning the material in this book.
Flow and Frustration Are Not Opposites
It’s very important to embrace a sense of flow when learning to program. It is also important to
embrace frustration as part of the flow state and not as the antithesis of it. When you learn
something new, the neurons in your brain are making connections; this may physically feel like
frustration, but it just means your brain is rewiring—literally. Embrace this.
Make It Habitual
Programming is all about learning a bunch of little things that combine to make big things. The
best way to learn a lot of little things is through repetition and habit. One way to do this is to
simply accept programming as a new part of your lifestyle and do a little bit (or a lot) every day.
Be Creative and Have Personal Projects
It is a good idea to have your own personal programming projects. The more you are personally
invested in a project, the more you will learn.
Talk and Teach
One of the best ways to validate your own learning is to teach someone else. If you don’t have
anyone to teach, then you can substitute this by writing tutorials. This will force you to collect
your thoughts and express them clearly.
Keep Going
Our final piece of advice is to simply stick with it.
Best of luck!
If you have any questions or comments, you can find us at:
http://www.javascriptforsoundartists.com
William Turner
Steve Leonard
Acknowledgment
Thanks to technical assistant Keith Oppel.
1 Overview and Setup
What Is a Program?
A program is any set of instructions that is created or followed. In this book, we focus on writing
computer programs, which are lists of instructions that a computer carries out. These instructions
can be written and stored in various forms. Some of the first modern computers used punched
cards, switches, and cables. Early analog music synthesizers were a type of computer that used a
patchbay style interface to manually allow a programmer to create specific sounds.
What Is JavaScript?
JavaScript is a multipurpose programming language initially created to aid developers in adding
dynamic features to websites. The language was initially created in 11 days and released in 1995
by a company called Netscape. Developed by Brendan Eich, its original release name was
LiveScript. When Netscape introduced support for the language in its browser, LiveScript was
renamed JavaScript. Although JavaScript is similar in name to the Java programming language,
they are completely unrelated. Today, JavaScript is used in everything from robotics to home
automation systems.
HTML, CSS, and JavaScript
The three main technologies used to build websites and web applications are HTML, CSS, and
JavaScript.
HTML stands for hypertext markup language and is the standard by which we create
documents for the World Wide Web. You program HTML by writing elements (sometimes
referred to as tags for brevity). These elements contain text and other nested elements, which
make up the document’s content.
CSS stands for cascading style sheets and is a tool used to modify how HTML elements and
text are presented. CSS is primarily a visual design tool. For example, with CSS you could
modify an HTML element and give it an orange background, change its font size, place it
vertically or horizontally, or perform any number of creative visual changes.
JavaScript is used to add interactive responses to user input. Every time a user clicks, scrolls,
taps, moves the mouse cursor, types, or performs an interactive event, JavaScript code can be
triggered to change the page in some manner. The JavaScript language was initially designed to
perform these functions within the context of designing websites and applications.
What Is a Web Application?
A web application is any website that contains more than static, non-interactive pages. This
means that, in a web application, the pages have some interactive components in addition to the
static text and images displayed. In the early days of the World Wide Web, websites were
composed mostly of collections of static documents connected through highlighted text called
hyperlinks. These static pages had no interaction with databases. In the early 1990s, this began to
change, and web developers began creating websites that had features similar to desktop
applications that allowed users to interact with the page via form fields, buttons, and other
interactive means to send data over a web server to and from a database.
Early web applications were slow and limited by the technology of the time. In the early
2000s, a culmination of technical shifts that included client-side- rather than server-side-focused
web applications helped make web applications more responsive. Part of this shift is attributable
to a technology called AJAX (asynchronous JavaScript and XML). This technology pushed
dynamic web application development forward by allowing the browser to retrieve and send data
to a web server without having to automatically refresh the page in the process. As the J in AJAX
indicates, JavaScript is central to this technology, and web applications began to approach the
interactive speed of their desktop counterparts.
As you might expect, within the audio world there were attempts to leverage this new
technology, which resulted in browser-based audio players, editors, and musical instruments.
Many of these applications were initially written using a technology called Flash. This is a
proprietary technology that required the user to download and install an additional plug-in to run
all programs written in it.
In 2008, a newer version of the HTML standard was written, called HTML-5. This version
included an audio player that could directly stream sound files off a web server using a single
line of HTML code. The player also included built-in, user-facing controls for play, fast-forward,
rewind, pause, stop, loop, and other actions. However, for serious audio development, this was
inadequate. Web application developers and audio aficionados wanted something more fully
featured.
What Is the Web Audio API?
The Web Audio API is a series of exposed code pieces that you can use to accomplish musical
and audio tasks in a web browser with less effort than if you were to create them all from scratch.
The unexposed portion of the Web Audio API lies in the web browser’s source code and is
written in whatever language the web browser itself is written in. The technical core of web
browsers is usually written in multiple lower-level languages, which can include (but are not
limited to) C++, Java, and machine language.
To understand the Web Audio API, you must first understand what an API is. API stands for
application programming interface. An API is a portion of code that a programmer is given
access to, which controls a larger unseen body of code within certain constraints. Imagine if, in
order to learn how to play your favorite musical instrument, you had to literally build it from
scratch. As you can imagine, this would get very tedious—especially if the instrument were to
break. Thus, it’s much more convenient to learn to play a premade musical instrument. The
convenience here is that the construction process is removed and your only concern is what is
important to you, which is the controls needed to use the instrument. In a similar manner,
programmers write APIs that expose only small pieces of code for developers to use, and these
small pieces of code allow you to do a lot of work with minimal effort.
In addition to being able to load and play back sound files, the Web Audio API also allows
you to generate sound from scratch in the form of oscillators. You can then manipulate any sound
playback or generation using filters, reverb effects, dynamic compressors, delay effects, and a
host of other options.
Setting Up Your Work Environment
To begin working, you must first determine what browser you are going to troubleshoot with. In
real-world environments, you would use a test suite to troubleshoot among different browsers and
platforms. In this book, we are going to keep things simple and only use Google Chrome. The next
thing you need is a code editor. For the exercises, we assume you will be using the Sublime Text
editor. Technically, you can use any code editor you want, but Sublime Text is offered as a free
trial download and is extremely powerful and widely used. We think it’s worth your investment of
time to learn it.
The next thing you need to do is create a folder with a basic work template.
1. If you are not already using it, go to this URL to download and install Google Chrome:
https://www.google.com/chrome/browser/desktop/.
2. Go to http://www.sublimetext.com/ and download and install Sublime Text.
3. Create a folder on your desktop or in a directory and call it web audio template.
4. Open Sublime Text, and in the window that appears, type the following code into it. Then
save the file (go to the File menu in Sublime Text and click Save As) as index.html and
choose your web audio template folder as the directory to save it in.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>app</title>
<script src="js/app.js"></script>
<link rel="stylesheet" href="css/app.css">
</head>
<!--__________________________________________BEGIN APP-->
<body>
</body>
<!--____________________________________________END APP-->
</html>
5. Inside the web audio template folder, create another folder called css.
6. In Sublime Text, create a new file by going to the File menu and click New. Save this file in
your css folder as app.css. Leave the contents of this file empty.
7. In the web audio template folder, create another folder called js.
8. Create a new empty document in Sublime Text, then type "use strict"; (including
quotations and semicolon) at the top of it and save it as app.js in the js folder you just
created. This places your JavaScript in strict mode. Strict mode is a restrictive form of
JavaScript that enforces better programming practices. All JavaScript code examples in this
book will assume you have strict mode enabled.
You are now going to add a few extensions to Sublime Text that will make working with the
editor easier in the long term. To do this, you must first download and install the package manager
plug-in. Go to the following link and follow the directions on the left side of the window:
https://packagecontrol.io/installation. When done, close the console by entering the keys: Ctrl + `
(apostrophe, on the key with the ~).
1. In the Sublime Text menu, go to Tools > Command Palette, and in the form field that
appears, type install. You should see an option menu appear that says Package control:
Install package. Click this menu option.
2. Another form field with a series of options appears. This form field allows you to search and
explore various plug-ins for Sublime Text. You are now going to install a plug-in that allows
you to create a local web server that will be necessary when working with audio files. In the
form field, type Sublime server. A list of search results should appear. Click the first
one. Look at the bottom of the Sublime Text window, and you should see “installing” in
small text. When this process is done, quit and restart Sublime Text. We will cover the
specifics of the web server in a later chapter. But rest assured that this setup will be time
well spent. To verify that the plug-in is installed, go to Tools > SublimeServer > Start
SublimeServer. Open your web browser to http://localhost:8080/, and it should display
SublimeServer at the top of the page.
3. This last plug-in you are going to install lets you open HTML files in Chrome from within
Sublime Text. To install the View in Browser plug-in, go to Tools > Command Palette and
in the form field that appears, type install. Click Package control: Install package.
Then do a search for View in Browser, and select the first option that appears. Once the
installation is done, you will need to go to the following menu to set up the plug-in to work
with Chrome.
Setup View in Browser for Windows
In Sublime Text, go to the Preferences menu and click Package Settings. Look for the View in
Browser menu item, hover over it, and select Settings – Default. Select all the code you see and
copy it. You are now going to paste it into the Settings – User page of the same plug-in. So go
back to the Preferences menu and select Package Settings > View in Browser > Settings – User.
Paste all the code you just copied into this window. At the very bottom, you should see a line of
code that says “browser”: “firefox”. Change the word firefox to either chrome, or chrome64 if
you have a 64-bit operating system. It should look like this: “browser”: “chrome” or “browser”:
“chrome64”. If you open an empty document in Sublime Text and use the key command Ctrl + Alt
+ V
, Chrome should launch and open that page.
Setup View in Browser for Mac
As soon as the plug-in is downloaded, you should be able to open an empty Sublime Text
document in Chrome using the key command Control + Option + C.
How to Create Code Snippets
It can be helpful to know how to create code snippets that you can access without writing them
out character-by-character every time. Thankfully, Sublime Text has a feature that allows you to
do this with snippets. To create a snippet, do the following steps:
1. In Sublime Text menu, go to Tools > New Snippet.
2. In the window that appears, delete everything on line 3 and paste the following text: This
is a test snippet.
3. On line 6, remove the <!-- and --> characters and type the word test in between the two
elements. The result should look like this: <tabTrigger>test</tabTrigger>.
4. Save the file in the default directory that appears and call it test.sublime-snippet.
5. Open your index.html file in Sublime Text, type the word test, then tap the TAB button on
your keyboard. The phrase "this is a test snippet" should appear in the editor.
Accessing the Chrome Developer Tools
Google Chrome has a built-in suite of troubleshooting tools called the Chrome Developer Tools.
You can access these tools by opening the browser and using the key commands:
Windows OS or Linux: Ctrl + Shift + J
Mac: Command + Option + J
We are not going to go over the utility of the developer tools just yet, but they will be highlighted
throughout the book.
Troubleshooting Problems and Getting Help
If you have any trouble, try using search engines to research solutions. One very good resource is
http://stackoverflow.com, which is a community of programmers who ask and answer questions.
They have a nice section on JavaScript as well as a lively Web Audio API community that you
can find at: http://stackoverflow.com/questions/tagged/web-audio.
2 Getting Started with JavaScript and the
Web Audio API
Hello Sound Program
In an introduction to a programming language, the first program you write is often called “Hello
World,” which prints the words “Hello World” on the screen. Because we are using the Web
Audio API to create sounds, this section explains how to create a “Hello Sound” application that
immediately plays a sound when you run it.
Copy the folder web audio template from the last chapter to a new directory, and rename the
copy to hello_sound.
Type the code below into the app.js file that is present within the hello_sound folder. Save it
and then launch the index.html file from your web browser. You should hear a basic sine wave
oscillator playing.
var audioContext = new AudioContext();
var osc = audioContext.createOscillator();
osc.type = "sine";
osc.connect(audioContext.destination);
osc.start(audioContext.currentTime);
After you verify that the Hello Sound program works, close the browser. You just wrote your
first Web Audio API program!
The code you just ran is a basic oscillator generation and playback script. The first line in the
script is called the “Audio Context” and this tells the browser that you are using the Web Audio
API. The next line of code creates an oscillator. The third line of code assigns a waveform type to
the oscillator, whereas line four connects the oscillator to a virtual audio output called the
destination, which is analogous to the speakers of your computer. The last line starts the
oscillator playing. We will cover detailed operation of the Web Audio API in future chapters.
First, though, we need to cover the basics of the JavaScript language.
Variables
One of the first steps in writing a program is understanding variables and variable assignment.
Variables are word forms that are used to store data. For example:
var waveformType = "sawtooth";
The variable here is named waveformType. This is preceded by the var keyword. You
always specify the var keyword prior to declaring the variable. Declaring a variable means you
are creating a new variable. After the var keyword, you type a space and give a name to your
variable. Variable names are typically a reflection of something they represent. In this case, the
variable is being used to describe a type of oscillator waveform and so is named
waveformType. You probably noticed the odd capitalization of the word “type” in
waveformType. The convention of capitalizing words to distinguish them within variable
names is called camel case. This convention is used because variable names cannot contain white
space to separate them. If you rewrote the variable in the following manner, you get an error:
var waveform type = "sawtooth"; //____returns an error
Type the above code into the app.js file of your hello_sound template. Launch Chrome and
open the developer tools (Windows: Ctrl + Shift + J or Mac: Command + Option + J). Inside the
console tab, you should see an error similar to the one in the following image.
The text in gray is the actual error and is identified as a syntax error. To the right of the error,
you can see the file and the line number where the error occurred. This number corresponds to the
line number in your file, which might differ from the one in the image. After you see the error,
remove the line you added that is causing the error in app.js and save the file.
After you declare and name a variable, you can assign some data to it. You use the assignment
operator “=” to do this.
It is important to understand that in JavaScript the “=” symbol is not called the equal sign and
its functionality does not mean equal to. The “=” symbol indicates assignment, so it is called the
assignment operator. The value on the right side of the assignment operator contains the data you
want to assign to the variable name on the left side. In the following example, the string
"sawtooth" is assigned to the variable waveformType.
var waveformType = "sawtooth";
When you assign a string of words to a variable, you must place them between quotation
marks. The resulting data type is called a string. Data types represent the types of data that you
can use in your program. Different programming languages have different data types. JavaScript
has six data types, and one of these is the string data type (see Chapter 6 for a list of JavaScript
data types).
After you assign data to your variable, you must end the variable declaration with a semicolon.
In summary, there are five parts to a variable declaration:
■ The var keyword
■ The variable name
■ The assignment operator
■ The data you wish to assign to the variable
■ The closing semicolon
You can assign multiple variables at once using the following syntax:
var osc1 = 1200,
osc2 = 1300,
osc3 = 100;
In some cases, you might want to declare a variable and not assign data to it, as in the
following example:
var waveformType;
If you do this, JavaScript automatically assigns undefined to it. You can also assign
undefined explicitly like this:
var waveformType = undefined;
The keyword undefined is another JavaScript data type. Notice that undefined is not
enclosed in quotation marks because it is not a string but represents a data type.
null
The primitive value null is similar to the primitive value undefined. Both can act as a
placeholder for empty variables. When the typeof operator (discussed later in this chapter) is
used to determine the type of null, the result is object. This is not what you might expect and
is a flaw in the language. The correct returned value should be null. Because of this, we suggest
that you never use null and always use undefined.
Documenting Your Code with Comments
When you are programming, it is a good habit to type messages into your code that are intended to
be read by human beings (yourself or others) and not be interpreted by the computer. These
messages are called comments. You can write either single-line or multiline comments in your
program, and they look like this:
//This is a single line comment.
//It begins with two forward slash characters
//These end at the end of the line
/* This is a multi-line comment and begins with a forward slash
and asterisk. It ends with an asterisk and a forward slash */
In a real-world scenario, we might comment our code like this:
var waveformType = "sawtooth"; // oscillator variable
All the characters from the // to the end of the line are ignored by the computer.
Exploring Variables with an Oscillator
Now that you understand what variables are, the following example shows how you use them.
Open up the code you wrote at the beginning of this chapter, and add the variable
waveformType to it, as in the following code:
var audioContext = new AudioContext();
var waveformType = "sawtooth"; //___added variable
var osc = audioContext.createOscillator();
osc.type = "sine";
osc.connect(audioContext.destination);
osc.start(audioContext.currentTime);
Replace the osc.type assignment with the waveformType variable like this:
var audioContext = new AudioContext();
var waveformType = "sawtooth"; //___added variable
var osc = audioContext.createOscillator();
osc.type = waveformType; //__Assigned it to our oscillator type
osc.connect(audioContext.destination);
osc.start(audioContext.currentTime);
Launch your web browser, and instead of hearing a sine waveform, you should hear a sawtooth
waveform.
In this example, the following declarations assign values to variables that represent other
waveform types.
var audioContext = new AudioContext();
//___ 4 variables that represent oscillator waveforms
var saw = "sawtooth";
var sine = "sine";
var tri = "triangle";
var square = "square";
//___ A variable intended to contain one of these waveforms
var currentWaveform = undefined;
currentWaveform = square;
//_____________________________Start of oscillator
var osc = audioContext.createOscillator();
osc.type = currentWaveform; // Assigned it to our oscillator type
osc.connect(audioContext.destination);
osc.start(audioContext.currentTime);
Each of the four new variables contains a string that represents an oscillator waveform type.
The square variable is assigned to the currentWaveform variable in the following line:
currentWaveform = square;
Notice that no new declaration is required for the currentWaveform variable to assign
(and replace) whatever was previously assigned to it. The new data on the right side of “=” is
assigned to currentWaveform. If you launch your web browser, you will hear a square wave
play. In programming, being able to overwrite variables in this manner is referred to as
mutability (changeability), and we say that variables are mutable. The opposite of this is called
immutability.
console.log()
When programs begin to get big, it can be difficult to know what value is assigned to a variable at
any given moment. One way you can find out is by using a built-in feature called
console.log().
The way you do this is by typing console.log() into your code at the point where you
want to check a given variable’s assignment. You then place the variable name inside the
parentheses.
To see what the currentWaveform variable has as its assignment, you do this:
var audioContext = new AudioContext();
//Added 4 variables that represent oscillator waveforms
var saw = "sawtooth";
var sine = "sine";
var tri = "triangle";
var square = "square";
var currentWaveform = undefined;
currentWaveform = square;
console.log(currentWaveform); //___ square
//____________________________________Start of oscillator
var osc = audioContext.createOscillator();
osc.type = currentWaveform; // Assigned it to our oscillator type
osc.connect(audioContext.destination);
osc.start(audioContext.currentTime);
Launch Chrome, open the developer tools and click the console tab; you will see the output of
our console.log().
One thing to remember is that because variables can have different values at different times,
the output of console.log() depends on where it is placed in the program. If you modify the
last example and place console.log() immediately after the currentWaveform
variable, which has undefined assigned to it, then undefined is output to the log.
//__________A variable intended to contain one of these waveforms
var currentWaveform = undefined;
console.log(currentWaveform); //______results in "undefined"
currentWaveform = square;
So far we’ve mentioned three of the six data types in JavaScript. The first was string, the
second was undefined, and the last was null.
Before we go further, let’s explore the string data type a bit more in depth.
String
As we already discovered, strings are denoted by quotation marks. The variable below is a
string:
var oscillator = "square";
You can manipulate strings in different ways. One of the most common is by combining
multiple strings into one string. This is called concatenation, and it works by using the plus sign
(+) like this:
var oscillator = "saw" + "tooth";
console.log(oscillator); // sawtooth
Here is another example of concatenating two variables and storing them in a new variable.
var phrase = "This sound is an ";
var soundType = "oscillator";
var sentence = phrase + soundType;
console.log(sentence); // "This sound is an oscillator".
Notice that strings can contain white space.
This is a perfectly valid string, even though it contains a lot of white-space characters:
var myFavoriteSynthCompany = "My favorite synth company is Moog";
If you want to get the number of characters in a string, you can use what is called the length
property like this:
console.log(myFavoriteSynthCompany.length); // 33
The output of the length property includes the white-space characters of the string.
Built-In String Methods
JavaScript has a series of built-in tools called methods that allow you to manipulate data. Some
of these methods are specifically designed to manipulate string data.
These are called string methods.
To see how to use a string method, take a look at the examples of the toUpperCase() and
toLowerCase() methods.
toUpperCase()
This method changes all the characters in a string to uppercase.
var oscillator = "sawtooth";
oscillator.toUpperCase(); // SAWTOOTH
toLowerCase()
This method changes all the characters in a string to lowercase.
var oscillator = "SAWTOOTH";
oscillator.toLowerCase(); // "sawtooth"
Some useful string methods are:
charAt() Returns a character at any given index in a string
replace() Finds and replaces a group of characters in a string
slice() Extracts part of a string
You do not need to immediately memorize how each of these methods works, but it’s a good
idea to know about them. This way, when you do need to implement any of the functionalities they
provide, you know which tool to reach for. If you would like to explore more string methods, a
good resource is the Mozilla Developer Network at: https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/String.
Let’s go through each one of these and explain how to use them.
charAt()
This method gets a character at any given index value within a string. For example, if you have
the string "oscillator-1" and want to know what the second letter of this string is without actually
looking at it, you can do this:
var sound = "oscillator";
console.log(sound.charAt(1)); // "s"
Now you might be wondering why charAt(1) returns “s” and not "o". The reason is that the
count begins at zero. So, to get the first letter do this:
console.log(sound.charAt(0)); // "o"
When an index list begins with zero, it is called a zero-based index.
replace()
This method finds a group of characters in a string and replaces them with another string. If you
want to replace an entire word, you can do it like this:
var myFavoriteSynthCompany = "My favorite synth company is
Moog. Moog is great!";
var myNewFavoriteSynthCompany = myFavoriteSynthCompany.
replace("Moog","Dave Smith Instruments");
console.log(myNewFavoriteSynthCompany); /*My favorite synth
company is Dave Smith Instruments. Moog is great!*/
As you probably noticed, when using the replace method in this manner it only replaces the
first instance of the word you select. To replace all instances of the word, you need to use the
following syntax to globally replace them in the string.
var myFavoriteSynthCompany = "My favorite synth company is
Moog. Moog is great!";
var myNewFavoriteSynthCompany = myFavoriteSynthCompany.
replace(/Moog/gi,"Dave Smith Instruments");
console.log(myNewFavoriteSynthCompany); /*My favorite synth company
is Dave Smith Instruments. Dave Smith Instruments is great!*/
The g stands for global and the i denotes case insensitivity. If you want the string
replacement to be case sensitive, you use a g and omit the i. These characters are part of a
pattern-matching language for string data called regular expressions. Regular expressions are an
advanced topic that will not be covered further in this book.
slice()
This method extracts part of a string.
var oscillator = "sawtooth";
var sound = oscillator.slice(0,3);
console.log(sound); // saw
Like charAt(), slice() works on a zero-based index. This means the first character is
always zero. The slice method takes two values: a beginning index value and an ending index
value. When a method takes values, they are called arguments. The charAt() method takes one
argument. The slice() method takes two arguments. The slice method’s first argument is where
the slice starts, and this value is included in the slice. The second value is where the slice ends
and is noninclusive. This means all the characters up to, but not including, the second value are
included in the slice.
The length Property
The length property is an additional tool that allows you to get the number of characters in a
string. A property looks similar to a method but does not include parentheses and does not require
arguments to return a value. The character count of the length property starts at one, not zero.
var instrument = "piano";
console.log(instrument.length); // 5
If you want to get the last value of a string, you can combine the length property with the
charAt() method. This allows you to retrieve the last character in a string in a manner that
doesn’t require you to know how long the string is. The code shows an example of this. The
reason you subtract 1 from the length property is because the length property begins
counting at one, whereas charAt() begins counting at zero. Therefore, you subtract 1 from the
length property to compensate for the offset.
var sound = "oscillator-1";
var oscNumber = sound.charAt(sound.length - 1);
console.log(oscNumber); // 1
Numbers
In JavaScript, numbers are a distinct data type. Below is a variable named frequencyValue,
and it is assigned a number of 200. It is then assigned to the oscillator’s pitch. If you place the
code below in a new JavaScript file and run it, you will hear an oscillator play at a frequency of
200 Hz. Modify the number value assigned to the frequencyValue variable and launch the
code to hear the oscillator play at different pitches.
var audioContext = new AudioContext();
var frequencyValue = 200; //___Create variable frequencyValue
var waveform = "sawtooth";
var osc = audioContext.createOscillator();
osc.type = waveform;
//_____ assign it to the oscillators pitch
osc.frequency.value = frequencyValue;
osc.connect(audioContext.destination);
osc.start(audioContext.currentTime);
How to Determine the Data Type of a Variable
You can discern the difference between data types in variables by using the typeof operator.
var waveform = "sine";
var polyphony = 16;
console.log(typeof waveform); // string
console.log(typeof polyphony); // number
Unlike strings, numbers do not use quotation marks. In fact, if you did use a number with
quotation marks, its data type would not be number, it would be string.
Here’s an example:
var oscillators = "6";
var polyphony = 6;
console.log(typeof oscillators); // string
console.log(typeof polyphony); // number
You can do basic math with numbers using the following symbols. These symbols are called
arithmetic operators.
+ Addition
− Subtraction
* Multiplication
/ Division
% Modulo
Examples of Arithmetic Operators
console.log(5 + 5); // 10
console.log(10 - 5); // 5
console.log(5 * 5); // 25
console.log(25 / 5); // 5
console.log(10 % 9); // 1
The last symbol (%) might be new to you, and it is pronounced moj-uh-loh. The purpose of
this symbol is to output the remainder of a division. So, for example:
console.log(12 % 9); // This equals 3
The precedent rules of algebra also apply. If you wrap a calculation in parentheses, the
calculation inside the parentheses is performed first.
Examples of Precedence
var oscillator1 = 1000;
var oscillator2 = 100;
var oscillator3 = 20;
var combinedOscillator = oscillator1 +(oscillator2 * oscillator3);
console.log(combinedOscillator); // 3000
If you want to do more elaborate calculations, JavaScript has a built-in tool called the Math
object, which allows you to use a collection of math methods to manipulate numbers.
So, for example, if you want to round a decimal number to its nearest integer, you can use
Math.round() like this:
Math.round(1000.789); // outputs 1001
Some useful math object methods are:
Let’s go over each of these one by one. If you would like to explore more math methods, a
good site is the Mozilla Developer Network at: https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Math.
Math.min() and Math.max()
Math.min() finds the smallest number in a collection of numbers, whereas Math.max()
allows you to find the largest number in a collection of numbers.
Math.min(5000, 2000, 80); // 80
Math.max(5000, 2000, 80); // 5000
//___________________________With variables
var freq_1 = 5000;
var freq_2 = 2000;
var freq_3 = 80;
Math.min(freq_1, freq_2, freq_3); // 80
Math.max(freq_1, freq_2, freq_3); // 5000
Math.ceil() and Math.floor()
These two methods turn a decimal number into an integer. Math.ceil() rounds up to the next
higher integer value if there are any nonzero digits to the right of the decimal, whereas
Math.floor() keeps the integer value after discarding the digits to the right of the decimal.
Math.ceil(3.00333); // 4
Math.floor(3.9999); // 3
Math.random()
The random method creates a random number between zero and one.
var randomNumber = Math.random();
console.log(randomNumber); // example: 0.019790495047345757
You can combine Math.random() with Math.floor() to create a random number
between two values. The expression in the following example creates a random integer between
20 and 20,000.
var max = 20000;
var min = 20;
var randomInteger = Math.floor(Math.random() *
(max - min + 1) + min);
console.log(randomInteger); // Between 20 and 20000
Math.abs()
The abs method allows you to get the absolute value of a number.
var num = Math.abs(-100);
console.log(num); // 100
This is useful for finding the difference between numeric variables of unknown values.
var a = 1000;
var b = 5000;
console.log(Math.abs(b - a)); // 4000
Number-to-String Conversion
If you want to convert between numbers and numeric strings, you can use the following
techniques.
To convert a string to a number, place the plus symbol (+) before the string like this:
var numericString = "120";
var num = +numericString; // plus symbol
console.log(num); // 120
console.log(typeof num); // number
If you want to convert a number to a numeric string, concatenate the number with an empty
string like this:
var num = 80;
var numericString = num + "";
console.log(numericString); // 80
console.log(typeof numericString); // string
If you attempt to do a math operation using nonnumeric values, sometimes you will receive a
returned value of NaN. This stands for not a number. Here is an example of attempting to add two
values in which one value is a number and the other is not.
var osc1 = undefined;
var osc2 = 200;
console.log(osc1 + osc2); // NaN
Arrays
Arrays are a construct that holds multiple pieces of data. You can think of them as variables that
hold more than one item. Arrays are expressed using brackets, where each item is separated by a
comma. Each item in the array is designated an index number with the first item starting at zero.
var waveforms = [ ]; // empty array
var waveforms = ["square", "sawtooth", "triangle", "sine"]; //
array with some data
If you want to access any of these data, you can use the following notation:
waveforms[0]; // square
waveforms[1]; // sawtooth
waveforms[2]; // triangle
waveforms[3]; // sine
waveforms[4]; // undefined (no data)
If you want to know how many items are inside an array, use the length property like this:
var waveforms = ["square", "sawtooth", "triangle", "sine"];
waveforms.length; // 4
Arrays come with built-in methods that you can use to manipulate the data in them. A full list of
these are available at the Mozilla Developer Network at this URL:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array. We
are only going to go over a handful of these and they are:
push() Adds additional items to the end of an array
pop() Removes a single item from the end of an array
shift() Removes a single item from the beginning of an array
unshift() Adds additional items to the beginning of an array
concat() Concatenates arrays together into one array
push()
This method adds items to the end of an array.
var synthFrequencies = [5000, 1000, 500];
synthFrequencies.push(100); /*This places a new item at the end of
the array*/
console.log(synthFrequencies); // [5000, 1000, 500, 100]
You can use the push method to add multiple items at once.
var synthFrequencies = [5000, 1000, 500];
synthFrequencies.push(100, 50, 30);
console.log(synthFrequencies); // [5000, 1000, 500, 100, 50, 30]
pop()
This method removes a single item at the end of an array.
var synthFrequencies = [5000, 1000, 500];
synthFrequencies.pop();
console.log(synthFrequencies); // [5000, 1000]
If you want to capture the last item you removed from an array in a variable, do this:
var synthFrequencies = [5000, 1000, 500];
var lastItem = synthFrequencies.pop();
console.log(lastItem); // 500
shift()
This method removes an item from the beginning of an array.
var synthFrequencies = [5000, 1000, 500];
synthFrequencies.shift();
console.log(synthFrequencies); // [1000, 500]
If you want to capture the first item you removed from an array in a variable, do this:
var synthFrequencies = [5000, 1000, 500];
var firstItem = synthFrequencies.shift();
console.log(firstItem); // 5000
unshift()
This method adds new items to the beginning of an array.
var synthFrequencies = [5000, 1000, 500];
synthFrequencies.unshift(7500, 6000);
console.log(synthFrequencies); // [7500, 6000, 5000, 1000, 500]
concat()
This method merges multiple arrays together into one array.
var drumMachines = ["MPC", "Machine", "TR 808"];
var keyboards = ["Juno", "ARP", "Jupiter"];
var percussion = ["vibraphone", "bongos"];
var stringed = ["guitar", "bass", "harp"];
var instruments = drumMachines.concat(keyboards, percussion,
stringed);
console.log(instruments); /* ['MPC','Machine','TR 808','Juno','ARP',
'Jupiter','vibraphone','bongos','guitar','bass','harp'] */
Summary
In this chapter, you learned about variables, comments, numbers, strings, and arrays. In the next
chapter, you will learn about various assignment and logical operators.
3 Operators
You learned about the basic assignment operator (=) and some of the arithmetic operators in the
previous chapter. In this chapter, we are going to explore other assignment operators, as well as
comparison operators, that allow you to determine the relationship between variables and values,
such as whether they have the same value. We will also explore the Boolean data type, which has
either a true or a false value that can be assigned to variables or is the result of a comparison
operation.
What Are Operators?
Operators represent actions that you use to change the value of a variable, or compare values or
variables. The word operand is used to describe a value being used in an operation involving
operators. So in the following example, the operands are 300 and 400. The output of the
comparison is said to be what the expression evaluates to. In the following example, the operation
evaluates to false.
300 == 400 /*The values here (300 and 400) are called operands,
and the output evaluates to false.*/
Operators fall into arithmetic, assignment, or logical categories. The arithmetic operators that
we covered in the previous chapter are used with numbers. The assignment operators are used to
assign values to variables. The logical operators are used to compare two values and return a
true or false value based on the result of the comparison.
Assignment Operators
Assignment operators are used to assign data to variables. Here is a list of assignment operators:
Assignment
This operator assigns a value to a variable.
var osc = 100;
With assignment operators, you can also assign variables to other variables.
var osc1 = 100;
var osc2 = osc1;
console.log(osc2); // 100
Addition Assignment
This operator increments a numeric variable or appends a string to a variable. In the following
example, an oscillator is assigned a value of 100 and then incremented by 100 to give it a value
of 200.
var osc = 100;
osc += 100;
console.log(osc); // 200
To demonstrate the use of the addition assignment operator, the following code sets an ever-
increasing frequency change to an oscillator and you can listen to the effect. A method called
setInterval() is defined, although the specifics of setInterval() are not important at
this time. What is important is understanding that the addition assignment operator is incrementing
the frequency value by 100 every 0.5 seconds when setInterval() is called.
var audioContext = new AudioContext();
var osc = audioContext.createOscillator();
osc.frequency.value = 300;
osc.connect(audioContext.destination);
osc.start(audioContext.currentTime);
setInterval(function(){
osc.frequency.value += 100; /*____Increment frequency value by
100 every 0.5 seconds*/
console.log(osc.frequency.value); //_____View change
},500); //________________________500 milliseconds is 0.5 seconds
When you use the addition assignment operator with a string, the string you supply is
concatenated with the variable. Here is an example:
var keyboards = "";
keyboards += "Korg ";
keyboards += "Yamaha ";
keyboards += "Kurzweil ";
console.log(keyboards); // Korg Yamaha Kurzweil
Subtraction Assignment
This operator is used to decrement a numeric variable.
var osc = 500;
osc -= 100;
console.log(osc); // 400
Multiplication Assignment
This operator multiplies a variable with a value and assigns it to the variable.
var osc = 200;
osc *= 2;
osc *= 2;
console.log(osc); // 800
Division Assignment
This operator divides a variable by a value and assigns it to the variable.
var osc = 200;
osc /= 2;
osc /= 2;
console.log(osc); // 50
Modulo Assignment
This operator divides a variable by a value and assigns the remainder of that division to the
variable.
var osc = 200;
osc %= 150;
console.log(osc); // 50
The Boolean Data Type
The Boolean data type is either true or false. This is conveyed by the word-form values true
and false. Booleans are important because you can use them to program on or off (true or false)
values into the code. So, for example, you could use them as a value that toggles an oscillator on
or off. Assigning a Boolean value to a variable in JavaScript looks like this:
var oscillatorIsOn = true; // true
oscillatorIsOn = false; // changed to false
Boolean values can also be the result of the comparison operators described below or used in
conditionals statements, which we will cover in the next chapter.
Comparison Operators
Comparison operators are used to compare two variables or values. They output a true or
false value depending on whether the variables or values are similar or different from one
another in some way. The similarity or difference being tested for is dependent on the operator
used. So, for example, if you test whether two values are the same using the strict equality
operator (= = =) and they are not the same, the resulting value is false. There are eight
comparison operators.
Equality Operator
This operator checks whether the left operand is equal to the right operand. It then returns a
Boolean value to represent the outcome of the comparison.
200 == 200; // true
"200hz" == "200hz"; // true
var osc1 = "200hz";
var osc2 = "200hz";
console.log(osc1 == osc2); // true
The equality operator can be a bit tricky because it attempts to do a data type coercion before
comparing operands. Data type coercion occurs when the code interpreter (in our case the web
browser) attempts to convert one data type into another. In the following example, we compare a
number and a numeric string. JavaScript tries to convert the string to a number before doing the
comparison. If the string is a numeric string, the conversion is successful, and the comparison is
performed. In this case, the result of the comparison is the Boolean value true because the
numeric string “200” is successfully converted to the value 200, which matches the value of
osc1.
var osc1 = 200;
var osc2 = "200";
console.log(osc1 == osc2); // true
If a nonnumeric string is compared against a number, the result is always false.
200 == "oscillator" // false
Strict Equality Operator
To protect against the confusion of type coercion using the equality operator, you can use the strict
equality operator. This operator does not do data type coercion. This means that, if any numeric
string is compared against a number, the result is always false. For newer JavaScript
programmers, we suggest that you always use this operator. Restricting yourself to this operator
helps to mitigate problems involving coercion before they start.
//_________________________Examples
900 === 900 // true
var osc1 = 200;
var osc2 = "200";
console.log(osc1 === osc2); // false
Greater Than and Less Than Operators
These operators produce a Boolean result that is based on whether the left operand is less than or
greater than the right operand.
100 < 200 // true
300 < 200 // false
300 > 200 // true
300 > 500 // false
The greater than and less than operators do data type coercion as shown in this example:
600 > "500" // true
600 < "500" // false
Greater Than or Equal to Operator
This operator returns a Boolean value of true if the first operand is greater than or equal to the
second operand.
var osc1 = 300;
var osc2 = 500;
var osc3 = 300;
osc3 >= osc1 // true
osc2 >= osc1 // true
osc1 >= osc2 // false
The greater than or equal to operator does data type coercion as shown in this example:
300 >= "300" // true
Less Than or Equal to Operator
This operator returns a Boolean value of true if the left operand is less than or equal to the right
operand.
300 <= 300 // true
300 <= 500 // true
300 <= 200 // false
The less than or equal to operator does data type coercion as shown in these examples:
300 <= "300" // true
300 <= "500" // true
300 <= "200" // false
Not Equal to Operator
This operator is a combination of the NOT symbol and the equal sign. The NOT symbol is
expressed as an exclamation mark and is sometimes referred to as the bang operator. When NOT
is coupled with an equal sign to produce the not equal to operator, it can be used to return a
Boolean value that is based on whether two values are not equal to each other. If the two values
are not equal, the result is true. If the two values are equal, the result is false.
300 != 200 // true
300 != 300 // false
The not equal to operator does data type coercion as shown in this example:
"300" != 300 // false
Strict Not Equal to Operator
This operator returns a Boolean value that is based on whether two values are not equal to each
other. The strict not equal to operator, unlike the not equal to operator, does not do type coercion.
"300" !== 300 // true
300 !== 300 // false
Logical Operators
Logical operators allow you to check if a collection of statements is true or false and return a
Boolean value based on this information.
Logical Operator Name
&& AND
|| OR
! NOT
The Logical AND Operator
The logical AND operator evaluates to true only if all the operands are true. The way it works
is that first, the value on the right side of the operator is evaluated, and if its value is false, the
Boolean value of false is returned. In this case, the value on the left side of the operator is
never considered!
If the value on the right side of the operator evaluates to true, then and only then does the AND
operator check the value on the left side of the operator. If the value on the left side of the
operator is false, then the Boolean value false is returned. In the case where both the values on
the left and right sides of the logical AND operator are true, the Boolean value true is returned.
true && true // true
true && false // false
false && true // false
false && false // false
The Logical OR Operator
This operator returns true as long as either of the operands is true.
true || true // true
true || false // true
false || true // true
false || false // false
The NOT Operator
This operator inverts a Boolean value.
!false // true
!true // false
Another way to look at this code is that, if a value is not false, then it is true, and if its value
is not true, then it is false.
In JavaScript, there are six values that evaluate to false. They are the following:
false
""
null
undefined
0
NaN
All other values evaluate to true.
When you specify the NOT operator twice in a row before a variable or an operand, the
resultant value is its original Boolean value.
!!false // false
!!true // true
!!0 // false
!!"" // false
!!null // false
!!undefined // false
!!NaN // false
Summary
In this chapter, you learned about JavaScript assignment and logical operators, the Boolean data
type, and what values evaluate to false. In the next chapter, you will learn to leverage these
tools using two new concepts: conditionals and loops.
4 Conditional Statements and Loops
Conditional statements and loops are two of the most widely used constructs in programming.
Conditional statements allow your program to make choices based on a set of criteria. Loops use
repetition, allowing your program to complete many tasks quickly.
Conditional Statements
To create programs that do more than basic calculations or print text, they must be able to make
decisions. You can program these decisions by using conditional statements. Conditional
statements check if a value is true or false and then execute a branch of code based on this
condition. We are going to go over the following three conditional statements:
■ if
■ switch
■ ternary
The if Statement
The syntax of an if statement consists of the if keyword, a pair of parentheses, and two curly
braces. This is what an empty if statement looks like:
if(){
}
To use an if statement, you place a value or condition inside the parentheses and some code
to execute inside the curly braces. If the condition inside the parentheses evaluates to true, the
code inside the curly braces is executed. If the condition evaluates to false, no action is taken and
the code inside the curly braces is skipped. In the following code, an if statement is used to
Random documents with unrelated
content Scribd suggests to you:
But while they were there a body of armed men entered the
house.
They wore the uniform of the King’s guard: there was no regular
army in those days, every man was a soldier in time of need, but
there was a small body of men kept about the King’s person, who
were sent from time to time on special services, and were called the
King’s “beef-eaters.”
And these were some of them.
“Landlord, bring us some mulled sack,” said one who appeared to
be their leader, “and tell us, have you seen that fox the Abbot of
Glastonbury pass this way to-day on his road home?”
“He has not yet returned from London?”
“Nay, but he is on his way,—we have no listening ears have we?”
The boys were separated by a partition. “Are you for Abbot or King?”
“I am a friend to the King.”
“Well said, so should every good Englishman be; and we have
charge to arrest this wily Abbot on his return, as a foe to King Harry,
and take him to Wells to be tried for his life.”
“Has he not been tried and acquitted?”
“He has been solemnly condemned in a Court where Thomas
Cromwell sat as prosecutor, jury and judge: but that is not quite the
law, so he has been dismissed home, and we have been sent by an
after thought to take him to Wells for a regular trial.”[16]
“On what charge?”
“Robbing the Abbey Church.”
“Good heavens!”
“Why, I thought thee a friend of the King.”
“So I am, but what can all this mean?”
“That he hid the Abbey plate, so that the King’s visitors could not
find it, when they wanted to make an inventory, and confiscate
patens and chalices for the King’s use.”
“But it was his own.”
“Only in trust, you see.”
“Still he might hide it in trust for the Abbey, that would not be
robbery.”
“Friend, I should advise thee to consider it robbery in these days;
it is better for all men who do not want their necks stretched to think
as the King and his minister, Thomas Cromwell, think; don’t fear but
we shall find men to bring him in guilty.”
The poor inn-keeper was silent; perhaps he remembered that one
of his predecessors had been hanged for saying he would make his
son heir to the “Crown,” meaning the “Crown Inn.”
The boys stole out unobserved.
“What shall we do?”
“Go and meet the Abbot and warn him, he will pass Headly Cross.”
“But then we may but share his fate,” said several.
“I shall go if I go alone,” said Cuthbert.
“And so shall I,” said Gregory Bell.
“Well, two are as good as the lot of us, and better; more likely to
pass unobserved,” said Adam Banister; “the rest of us had better get
home, and tell the monks all we have heard and seen.”
It was a wild place, Headly Cross, where two woodland roads
crossed each other. Report said that a cruel murder had been
committed there years agone, and that the place was haunted;
every one believed in haunted places then.
But as there was a choice of routes, and the Abbot might come
either way, it was the right thing to await him where the roads
converged.
And there Cuthbert and Gregory waited all alone, as the dark
hours rolled away, until they heard the “Angelus” ring from a distant
tower, and knew it was nine o’clock, when decent people, in those
days, went to bed.
The chime had hardly died away, when they heard the tread of
horses, and soon three riders came in view in the dim light of the
stars; and the boys recognised the Abbot, with two attendants, one
his faithful serving man, the other a stranger.
Cuthbert dashed forward. “My Lord Abbot,” he said, “one moment,
it is I, Cuthbert, and here is Gregory Bell.”
“Cuthbert and Gregory Bell; why are you here, boys?”
“We have heard a plot against you: men are waiting at the ‘Cross
Keys’ to arrest you, and take you for trial at Wells; they say it will
cost your life.”
“On what charge?”
“Concealing the Abbey plate.”
The Abbot smiled sadly.
“My children,” he said, “this can hardly be true, yet if it be as you
say, I will not fly a jury of my countrymen.”
“Neither could he,” said the stranger on his left hand, “if he would;
my duty is to see him safe to Glastonbury, unless relieved
beforehand by royal authority.”
“You see, my Cuthbert and Gregory, that your devotion is all in
vain; neither would I avail myself of it if I could. Mount on the pillion
behind me, Cuthbert; my good Ballard here will take Gregory behind
him, and you may return with us to Glastonbury, if such return be
permitted.”
“It never will be, never will be,” said Cuthbert, with sinking heart.
And how that young heart beat, as they approached the “Cross
Keys,” and as a line of men, forming across the road, stopped the
cavalcade.
“My Lord Abbot, we arrest you in the King’s name.”
“On what charge?”
“Robbery of the Abbey Church.”
“This is a base pretence, to deprive me of the credit of martyrdom
for my convictions: but there was One who suffered more for me.”
And the Abbot yielded himself peacefully to those who sought his
life.
FOOTNOTES
[15] Advantage was taken of the Abbot’s compulsory absence
to take the necessary steps for the dissolution of the monastery.
(Froude.)
[16] In some private memoranda of Thomas Cromwell, which
still exist in his own hand-writing, occur the words,—“Item. The
Abbot of Glaston to be tried at Glaston, and also to be executed
there with his accomplices.” The trial, however, took place at
Wells, the execution (a foregone conclusion) at Glastonbury, as
related in the story.
CHAPTER VI.
THE TRIAL.
he period of English history of which we are now writing
has been aptly called “The Reign of Terror.” England
under Thomas Cromwell, and France under Robespierre,
were alike examples of the utter prostration which may
befall a mighty nation beneath the sway of one ruthless
intellect.
To make the King absolute, and himself to rule through the King,
was the one aim of the man whom Fox, the Martyrologist,
grotesquely calls “The valiant soldier of Christ:”—for this end he
smote down the Church and the nobility: Bishop Fisher and the
Carthusians represented the ecclesiastical world, the Courtenays and
the Poles the aristocracy, Sir Thomas More the new-born culture of
the time; and Cromwell chose his victims from the noblest and the
best. The piety of Fisher, once the King’s tutor, to whom his mother
had committed her royal boy on her death-bed, could not save him;
nor his learning, Sir Thomas More; nor her grey hairs, the Countess
of Salisbury. Spies were scattered through the land; it was
dangerous to speak one’s mind in one’s own house; nay, the new
inquisition claimed empire over men’s thoughts; we have seen that
the concealment of one’s sentiments was treason.
Will my more youthful readers wonder then that men could be
found to convict upon such charges as those preferred against the
aged Abbot of Glastonbury? They need wonder at nothing that
occurred while Bloody Harry was King, and Thomas Cromwell Prime
Minister.
The juries themselves sat with a rope around their necks; when
the Prior and the chief brethren of the Charter-house waited upon
Cromwell to explain their conscientious objections to the Oath of
Supremacy, loyally and faithfully, he sent them from his house to the
tower; when the juries would not convict the ecclesiastics, he
detained them in court a second day, and threatened them with the
punishment reserved for the prisoners, unless they found a verdict
for the crown; finally, he visited the jurymen in person, and by
individual intimidation forced the reluctant men to find a verdict of
guilty, whereupon the unfortunate monks were hanged, drawn, and
quartered, with every circumstance of barbarity, suspended, cut
down alive, disembowelled, and finally dismembered.[17]
Thursday, the fourteenth of November, 1539, was a gloomy day:
black leaden clouds floated above, the ground was sodden with
moisture, the leaves, fallen leaves, no inapt emblem, rotted in the
slime, a heavy damp air oppressed the breath; the day suited the
deed, for on that day the aged Abbot of Glastonbury was formally
arraigned at Wells, together with his brethren the Prior and Sub-
Prior, on the charge of felony,—“Robbery of the Abbey Church with
intent to defraud the King.”
They might well have proceeded against him under the Act of
Supremacy, but variety has charms, and this new idea of felony
commended itself to the mind of Cromwell, as a good device for
humbling the clergy.
Lord Russell, one of Henry’s new nobility who supplied the places
left vacant by so many ruthless executions, whose own fortunes
were built on the plunder of the Church, sat as judge, and there
were empannelled, we are told, “as worshipful a jury as was ever
charged in Wells.”
The indictment set forth that the prisoners had feloniously hidden
the treasures of the Abbey, to wit, sundry chalices, patens,
reliquaries, parcels of plate, gold and silver in vessels, ornaments,
and money, with the intent of depriving our sovereign lord the King
of his rightful property, conferred upon him by Act of Parliament.
“What say you, Richard Whiting, guilty or not guilty?”
The aged prisoner looked around him with wondering eyes; he
scanned the crowded array of spectators, then the jury, who looked
half ashamed of their work, and finally rested his eyes upon his
judge.
“How can I plead guilty where there can be no guilt? These
treasures were committed to my care to keep for God and Holy
Church; it is not meet to cast them to swine; no earthly power may
lawfully take to itself the houses of God for a possession, or break
down the carved work thereof with axes and hammers. Am I tried
before an assembly of Christian men, or before heathen, Turks,
infidels, and heretics?”
“It is not meet for a prisoner to revile his judges,” said Russell; “as
an Englishman you are bound by the Acts of Parliament.”
“Talk not to me of Parliament; you have on your side but the
Parliament of this sinful generation, and against you are all the
Parliaments who have sat from the Witan-agemot downwards, who
have granted and confirmed to us of Glastonbury, those possessions
which you would snatch from a house which has been the light of
this country for a thousand years; to resist such oppression and
sacrilege is not guilt, and I plead in that sense, ‘Not Guilty.’”
“Thou showest but little wisdom in pressing thine own opinion
against the consent of the realm.”
“I would fain hold my peace; but that I may satisfy my conscience,
I will tell thee that while thou hast on thy side but a minority in a
single kingdom, the whole of the Christian world, save that kingdom,
is dead against you, and even the majority here condemn your
proceedings, although the fear of a barbarous death silences their
tongues.”
“Of whom art thou speaking?”
“Of all the good men present.”
“Why hast thou persuaded so many people to disobey the King
and Parliament?”
“Nay, I have sinned in dissembling my opinions, but now I will
speak. I disallow these changes as impious and damnable (general
sensation); I neither look for mercy nor desire it; my cause I commit
to God, I am aweary of this wicked world, and long for peace.”
He sank upon the bench behind him, as did his fellow prisoners,
and none of them took any further obvious interest in the
proceedings.
Formal evidence was brought to prove the discovery of treasure
hidden in secret places, but all this fell very flat upon the audience,
the fact was tacitly admitted on both sides, the difference of opinion
only existed as to the guilt thereof.
There was no room for doubt in Lord Russell’s mind; he summed
up the evidence against the prisoners, and reminded the jurymen
that their own loyalty was on trial, a very forcible hint in those days,
and one which few men dared disregard.
They retired; returned with downcast looks, and gave a verdict in
accordance with the evidence: theirs not to argue the point of law,
the fact was sufficient.
“Prisoners at the bar,” said the judge, “you have been convicted on
the clearest evidence of an act of felony—of seeking to deprive the
King of the property willed to him by the high estates of the realm,
in trust for the nation. Into your motives I need not enquire, but no
man can be a law unto himself; born within these realms you are
subject to the authorities thereof, and for your disobedience to them
you must now die. The only duty remaining to me is to pronounce
upon you the awful sentence the law provides against your particular
crime—that you be taken hence to the prison whence you came, and
from thence be drawn on the morrow, upon a hurdle, to the summit
of Glastonbury Tor, that all men far and wide may witness the royal
justice, where you are to be hanged by the neck, but not until you
are dead, for while you are still living, your bodies are to be taken
down, your bowels torn out and burnt before your faces; your heads
are then to be cut off, and your bodies divided, each into four
quarters, to be at the King’s disposal, and may God have mercy
upon your souls.”[18]
A dead silence followed, broken at last by the Abbot’s voice.
“We appeal from this judgment of guilty and time-serving men to
the judgment of God, before Whose bar we shall at length meet
again.”
It was late in the same evening, the curfew had already rung, the
rain was still falling at intervals in the streets of Glastonbury, as if
nature wept at the approaching dissolution of the venerable fane
which had been the ornament of western England so long.
In spite of the weather, many groups formed from time to time
outside the gatehouse of the Abbey, for there the three prisoners
had been brought from Wells, and there, in the chamber over the
gateway, in strict ward, they were passing the last night the royal
mercy permitted them to live.
A youth, repulsed from the door which gives admittance to the
upper chambers, retired with despairing gesture; his face bore
marks of intense emotion, the tears had worn furrows therein, and
from time to time a sob escaped him.
A companion pressed up to his side.
“Will they not let you in?”
“No, Gregory, I have begged in vain these three times.”
“Why not try the sheriff, he is said to be merciful?”
“I can but try, I will go to his house at once.”
As due to his office, the high sheriff of the county was charged
with the details of the morrow’s tragedy; he liked the task but little,
still he viewed it as a simple matter of duty, and could not flinch
from it.
He was resting after the fatigues of the day, and in truth, thinking
very uneasily over the events of the trial.
“What if, after all, he is in the right—that appeal to the judgment
bar above was very solemn—when that great assize takes place, in
whose shoes would it be best to stand, in the place of the judge or
the felon of to-day?”
A domestic entered—“A lad craves a moment’s speech.”
“Who is he?”
“I know him not, but he has been weeping bitterly, as one may
see by his face.”
The sheriff hesitated, but he was in a merciful mood; he
suspected the object of the visitor, and it was a good sign for the
success of the suppliant that he permitted the visit.
“Well, my lad,” said he, as Cuthbert entered, “what is the matter
now?”
“I have a boon to crave, your worship; you will not refuse it me?”
“Let me first hear what it is.”
“The Abbot has been my adopted father, my best friend from
childhood; let me see him once more, let me receive his parting
blessing, ere wicked hands slay him.”
“Wicked hands, my lad, you forget yourself, and where you are.”
“Pardon me, I meant no offence; I know it is no fault of your
worship.”
“It is but a slight boon, after all,” said the sheriff, “and one which
may be conceded;” and as he spoke he wrote a few lines on a slip of
parchment. “They will give you admission for half-an-hour, if you
show them this at the gateway.”
“May I not stay longer?”
“It would not be kind to those who are to die; they need their
time to make their peace with God.”
“That is already made, your worship.”
“I trust so,” said the sheriff, with a sad faint smile at the boy’s
earnestness.
“Who art thou, my lad?” he said.
“The Abbot’s adopted son.”
“But who were your real parents?”
“I know not.”
“What name do they call you?”
“Cuthbert, I have none other.”
“Poor lad,” said the sheriff, as the boy departed, “it seems almost
like a familiar face, yet I have never met him before; some
accidental likeness, I suppose.”
FOOTNOTES
[17] Lingard v. 19.
[18] This terrible sentence is copied from the form in actual use
until the present century.
CHAPTER VII.
GLASTONBURY TOR.
dead silence reigned around the precincts of the once
mighty Abbey, many of the monks had fled, fearing lest
they should share the fate which had befallen their
superiors, and having no decided predilection for
martyrdom; but many still shuddered in their cells, or
wandered aimlessly about the doomed cloisters, so soon to be a
refuge for bats and owls.
Only a few lights burned here and there in the darkness of that
November night, but one shone steadily from the window of the
strong room over the gatehouse, where the three fated monks
awaited their doom.
Scantily furnished was that chamber; three wooden chairs with
high backs grotesquely carved, a massive table in the centre, a huge
hearth decorated with the Abbey arms, upon which smouldered two
or three logs, for fuel was cheap, and the night was cold and damp.
Against the wall hung a crucifix, and there, with their faces towards
the memorial of the martyrdom which redeemed a world, knelt the
three.
We cannot follow their mental struggles, which found relief in
prayer—in intense prayer, in burning words of supplication, which
wafted their spirits on high, and gave them strength to say “not my
will but Thine be done.”
A step on the stairs, but they rose not from their knees; they felt
that one had entered and was kneeling behind them, and at length
they heard sobs escape from their visitor, which he could not
repress.
They rose slowly from their devotions, and the Abbot grasped
Cuthbert’s hands and raised him from the floor.
“My child,” he said, “dost thou grieve for me?”
A sob was the only answer.
“Listen, my child, which is best, heaven or earth, Paradise or
Glastonbury?”
Still no answer.
“And they but rob us of a few brief years, which to aged men like
us must be years of suffering; they separate us from the ranks of
the Church Militant, but not from those of the Church Triumphant,
that is beyond their power; they may kill the body, but after that
they have no more that they can do.”
“But the shame, the disgrace!”
“Is it greater than the Son of God bore on Calvary? Nay, my son,
let us not grieve that it has pleased Him, of Whom are all things, to
ordain this painful road, which He Himself has trodden before us;
nay, sob not, nor sorrow as those without hope, but live so that thou
mayest rejoin us in the regions of Paradise.”
Cuthbert gazed upon the calm majestic face of the old man, and it
seemed to him irradiated by a light from above. He repressed his
grief, and listened to the last words of his friend.
“It is written that in the last days perilous times shall come, and
we have fallen upon them; happy then that God removes us to His
secret chambers, where He shall hide us until the iniquity of a world
be overpast, and His redeemed come with triumph to Zion. Before
us now is the via Dolorosa of a brief hour, but from the gibbet we
shall scale the skies. For thee, my son, is the life-time of trial and
temptation, wherefore I pray for thee, and will pray for thee when
thou shall see my face no more. Remember, dear child, he that
endureth to the end, the same shall be saved, and let neither men
nor devils rob thee of thy crown.”
“By God’s help I will endure.”
“I believe that thou wilt strive, yea, and prevail. But one more
thought to earthly things, and I resign the world for ever. Thou
rememberest the secret chamber?”
“I do, Father.”
“And the ring which is now on the finger of him who shall claim
thy promise?”
“Well, my Father.”
“Await him, my son, in Glastonbury, not in the Abbey, that will be
destroyed by wicked hands, but in the house of thy foster father,
Giles Hodge, whose name thou must take, and be content to pass as
his foster son till the time comes, and thy services are claimed. He
who bears the ring will provide for thy future.”
“Oh, think not of that.”
“I have thought of it, and now, my child, thou mayest again join
us in prayer.”
“The half-hour has passed,” said a rough voice at the door.
“Thy blessing, Father.”
“It is thine, my child: Benedicat et custodiat te Deus omnipotens,
Pater, Filius, et Spiritus Sanctus, nunc et in sæcula sæculorum.”
Upon the summit of the hill men are working all through the
storms of the night, erecting a huge gibbet, from the cross-beam of
which three ropes are now dependent; beneath is a huge block, like
a butcher’s block, and a ghastly cleaver and saw rest upon it; hard
by stands a caldron of pitch, which but awaits the kindling match to
boil and bubble.
Through the dark shadows of the clouds, or in the bright light of
the moon when the winds open a path for her rays, ghostly figures
flit about. It is well that they should work in darkness,—it were
better that such work were not done at all. Thus they execute the
will of the ruthless Tudor, the Nero of English history; well, he and
his victims have long since met before a more awful bar.
The winds blow ceaselessly all through the night, but in the morn
the clouds are breaking; in the east a faint roseate light appears,
and soon brighter streaks of crimson fringe the clouds, which hang
over the dawn; anon the monarch of day arises in his strength, the
shadows flee away, and from the summit of the hill a vast extent of
sea and land is beheld, rejoicing in his beams.
A crowd gathers around the gatehouse, some few royal parasites
to jeer, men at arms to guard the prisoners, and prevent any
attempt at rescue, more sad and tearful faces of women, or sternly
indignant visages of bearded men.
“Here they come.”
The trampling of horse, a train of strong wooden hurdles, each
drawn by a single horse, appears; hard carriages these on which to
take the ride to eternity, but many an innocent victim has fared no
better.
The doors are opened, and the Abbot appears first: a blush
overspreads his aged cheeks, as the indignity thus palpably presents
itself, but uttering, “And this, too, I offer to Thee,” he lies down upon
the hurdle, and they bind his hands and feet to the crossbars,
carefully, that they may not touch the ground, for those in charge of
the execution would not willingly offer additional pain—some of
them are sick at heart as they fulfil the will of the tyrant Tudor.
The Prior and Sub-Prior submit to the same painful restraint, and
the via Dolorosa is entered.
All through the streets of the town, where the Abbot has often
ridden in triumphant processions, the highest in dignity of all far and
wide, the hurdles jolt along: the aged frames of the sufferers are
fearfully shaken by the rude joltings, but they remember that via
Dolorosa which led to Calvary, and accept the pain for the sake of
the Divine Sufferer, in Whom our sufferings are sanctified.
There are those present who are paid to raise hisses and hootings,
and to revile the passing victims, but they are awed by the attitude
of the spectators in general, and forfeit their wages.
Up the hill with labouring steps the horses tread: at length the
rounded summit appears, and the gibbet looms in sight.
The sufferers see it not, owing to their prostrate condition, until
they are beneath it. “It is easier to bear than the cross, brethren,”
says Abbot Richard.
The victims are unbound from the hurdles, and one after the other
resigns himself to the rude hands of the executioners; for now,
under this reign of terror and bloodshed, ecclesiastics are led forth in
their habits to die without being first stripped of their robes, and
degraded. There is a meaning in this, it is not of mercy.[19]
The Abbot yields himself first, calmly reciting the words of the
31st Psalm, “In manus tuas, Domine, commendo Spiritum meum.”
The two pray for him until their own turn comes.
“Go forth, O Christian soul, from this world, in the Name of God
the Father Who created thee, of God the Son, Who redeemed thee,
of God the Holy Ghost Who hath sanctified thee; may thy place be
this day in peace, and thine abode in Mount Sion.”
Their faces did not grow pale, neither did their voices tremble—
they declared as they died that they were true subjects of the king
in all things lawful, and obedient children of Holy Church.
So one after the other they suffered—we spare the reader the
sickening details, which Englishmen could look on in those days, and
which innocent men were called upon to suffer, but which we
shudder even to read.
But we will conclude with a letter written by Lord Russell to
Cromwell on the 16th of November, being the day following the
tragedy.
“My Lorde—thies shal be to asserteyne, that on Thursday the xiii. daye
of this present moneth, the Abbot was arrayned, and the next daye putt
to execution, with ii. other of his monkes, for the robbyng of
Glastonburye Churche; on the Torre Hill, the seyde Abbottes body beyng
devyded in fower partes, and his heedd stryken off, whereof oone
quarter stondyth at Welles, another at Bathe, and at Ylchester and
Brigewater the rest, and his hedd upon the abbey gate at Glaston.”[20]
As the traveller, in modern times, passes swiftly along the Great
Western line between Weston and Bridgewater, he may see, on his
left, a round conical hill, rising abruptly from the flat plain, a plain
which was once a sea, a hill which was once an island. This is
Glastonbury Tor.
Fair and beautiful it looks in the summer sunlight, but it was once
the scene of the foul judicial murder which we have endeavoured to
describe.[21]
FOOTNOTES
[19] “While he was waiting for the hangman, he was
questioned again by Pollard as to the concealment of plate, but
he had nothing more to say, and would accuse neither himself
nor others, but thereupon took his death very patiently.”—Blunt.
[20] This letter is authentic, spelling and all.
[21] See Note G. Death of Abbot Whiting.
CHAPTER VIII.
ON THE TRACK.
“We grieve not o’er our abbey lands, e’en pass they as they
may,
But we grieve because the tyrant found a richer spoil than they;
He cast aside, as a thing defiled, the remembrance of the just,
And the bones of saints and martyrs he scattered to the dust.”
Neale.
t was in vain that Bishop Latimer besought the tyrant,
mad after the spoils which a venal parliament had given
him, to let at least some of the monasteries remain as
the houses of learning. Few countries could boast of
such shrines as those which adorned like jewels the
shires of England—but all were ruthlessly sacrificed, from the fane
which rose over the mighty dead at Battle, to the humblest cell
which but sheltered half-a-dozen poor brethren or sisters.
Such was the value of the noble library at Glastonbury that Leland,
an old English antiquarian, tells us, when first he beheld it, “The
sight of its vast treasures of antiquity so struck me with awe, that I
hesitated to enter.”
Yet we learn from Bale, that such noble collections were sold to
grocers for waste paper, and that he knew a man who had bought
for that purpose two large monastic libraries at the dissolution, and
added that he had been using their contents for ten years, and had
hardly got through half his store.
So strongly built were many of the Abbeys, that they had to be
blown up with gunpowder, after they were stripped of all that could
be sold; the lands were given to greedy favourites, Cromwell himself
is said to have secured thirty Abbeys, and the ready money was
spent at court in gambling and dissolute living.
So, in a few years, all the wealth which flowed into the hands of
the crown was dissipated, and instead of the remission of taxation,
by the hope of which many had been bribed to assent to the fall of
the monasteries, the burdens laid upon the people were heavier
than before.
Four months had passed away since the tragical events recorded
in our last chapter, and the blustering month of March was in mid-
career; the winds swept over the ruined Abbey, now in great part
roofless, and dismantled, the abode of bats and owls; they swept
over the bare and rounded summit of Glastonbury Tor, stained so
lately by a foul deed of blood. Many a violent storm of rain had
beaten upon that blood-stained summit, and the traces of the
butchery had long since vanished; but the peasants yet gazed up to
the hill top with awe and wonder.
But the storm which had desolated the proud Abbey had left the
humble cottage of Giles Hodge untouched: there the old man and
his wife lived in peace, like their neighbours, and went through their
daily round, their trivial task—
Each morning saw some work begun
Each evening saw its close.
Their foster son was often present to their remembrances, but he
had not been with them in person since the martyrdom. They had
wisely judged it best to remove him from the immediate
neighbourhood of such harrowing recollections, and as old Giles had
a brother who lived at Lyme Regis, a seafaring man, thither he had
sent Cuthbert to spend the winter.
The change of scene had wrought good. The poor boy had gone
there broken-hearted, and suffering from the nervous excitement
which he had passed through; the shock had been very great, but
youth is elastic, and soon recovers from such a strain. The sea and
its wonders, the romantic scenery around, all contributed to the
beneficial change. Sometimes Cuthbert would go out fishing with his
uncle, as he had learned to call the brother of his foster father; the
fishing awakened all his interest: on the deep all the night, watching
the moonbeams on the waves, the gradual breaking of the dawn,
the “many dimpled smile of ocean:” all this was new to the land-
bred youth, and exercised a most happy effect upon his health and
spirits.
But it must not be supposed that he forgot the Abbot, or that he
was unmindful of the secret entrusted to him; he had told his foster
father that he expected some communication from the friends of the
late Abbot, and old Hodge had promised that if anyone arrived, and
presented the ring which was to serve as a token, he would send for
Cuthbert without any delay.
And at last the message came, just when Cuthbert returned home
with his “uncle,” after a most successful night at sea, bringing the
scaly spoils of the deep in their boats. A rustic messenger had ridden
across the country from Glastonbury, through Langport, Ilminster,
Chard, and Axminster, a distance of from thirty to forty miles.
Old Giles could not write, he only sent word by his envoy, “Come
home, I have seen the ring, he expects thee to-morrow.”
We have not hitherto explained fully the social position of Giles
Hodge. Well, he was a yeoman, having no lands of his own; only he
had a farm of three or four pounds a year,[22] and hereupon he tilled
as much as kept five or six men. He had walk for a hundred sheep,
and his wife milked thirty kine. He was able and bound to provide
one man and horse, with “harness” for both, when the king had
need of him; for this species of feudal tenure yet lingered, and
supplied the want of a standing army. In short, he was an English
yeoman, “all of the olden time.”
The fire was burning brightly on the hearth in old Giles’ cottage,
which looked as pleasant as in days of yore; he and his old dame
occupied their chairs on either side, for the day’s work was over, and
they were resting after its fatigues, whilst they anxiously awaited the
arrival of their foster son, their Cuthbert.
It was only just dark, not yet seven o’clock; the evening meal was
already prepared, and set forth with many a tempting dish upon a
comely white cloth, to tempt the appetite of the darling of their old
age.
A knock at the door—the hearts of the old couple beat with
anticipation—yet the knock! Would Cuthbert stop to knock? “Come
in,” they cried.
The latch lifted, and their parish priest entered, Doctor Adam
Tonstal.
“Good even to you, my worthy friends; I have come for a chat
with you about a matter of importance.”
“Nothing amiss about Cuthbert, I hope,” said the old dame,
anxiously.
“No, there is naught amiss, yet still my errand is about him. Are
you not expecting him home?”
“Yes, thank God, this very night; we thought when you knocked
that it was he.”
“Well, I know you will be glad to see him again, for he is a worthy
lad, and there are few who have not a good word for him, but it will
be just as well not to let anyone know of his arrival, and to get him
away again as soon as possible. My object was to warn you against
allowing him to return, and also to advise you not to tell anyone
where he may be found.”
“But why,” inquired Giles, aghast, as soon as he could get a word
in; “what harm hath the poor lad done?”
“Harm, forsooth!” then lowering his voice, “what harm had Richard
Whiting done?”
“But Cuthbert is too young to be answerable for such weighty
matters.”
“I know that, but not too young to be an object of interest just
now. You see it is reported that he was deep in the Abbot’s secrets.”
“They would indeed be weighty secrets, which the Abbot would
entrust to a mere boy.”
“Ordinarily your remarks would be just, but the case is peculiar.
The Abbot was suspected to be in possession of lists of names, of
papers, nay of treasure, in connection with the rising in the north,
which had been entrusted to him after the disastrous collapse of the
Pilgrimage of Grace: we are all friends here,” added the priest,
fearing lest he might have committed himself, for had such an
expression as “disastrous,” applied to the royal triumph, been
reported to Cromwell, it might have been his death-warrant.[23]
“We are alone, my wife and I, and we be no tale-bearers.”
“Well then, it is said that there must be a secret chamber,
somewhere in the Abbey, not yet discovered, in spite of all the
search made for it by Sir John Redfyrne, the administrator of the
property of the Abbey for the king; who is also an ally of Cromwell,
that arch-heretic, and oppressor of the Church. You are sure there is
no one in the house save yourselves?”
“Quite sure, don’t fear; but what has this to do with Cuthbert?”
“Only that a lad named Nicholas Grabber offers to make oath that
he heard the Abbot reveal the secret to Cuthbert, when the two
were in his private chamber, and bid him await the arrival of some
mysterious person, with a ring: Grabber’s account is very defective,
but he says the Abbot discovered his presence, and ordered him
roughly away.”
“As I live,”—said Giles.
“Of course you know nothing,” said the priest, interrupting, “but I
have learned through friends that a warrant is about to be issued
against the lad: now if he is taken——”
“But they can lay no crime to his charge, to know a secret is no
crime.”
“But they may, and probably will consider that secret of sufficient
importance to the State to insist upon its disclosure, and if the poor
boy, as will very likely be the case, refuse to tell, they will see what
the thumb-screw, or failing that, even the rack, may effect.”
“Good heavens! Saint Joseph forbid.”
“Amen; but the best way is to keep Cuthbert out of the way.”
“Too late; for here he is!”
The door opened and our hero entered, all flushed with travel,
and with the delight of meeting his old friends, whom he embraced
warmly; after which he saluted the priest with a lowly reverence.
“How well he is looking, poor lad,” said the dame: for his face was
flushed with pleasure, or she might still have seen some traces of his
recent trial. A more thoughtful expression sat on his features, such a
period as he had gone through had done the work of years in
sobering his boyish spirits, and bringing on, prematurely, the
thoughts and cares of manhood.
“Now, Cuthbert,” said the good priest, “I will take a turn on the
green, while you tell all your news to your kind friends, and satisfy
your hunger, and after that I will return for a little talk with you;”
and he went out, but only to pace up and down the green, keeping
the cottage still in sight.
And we too will leave the good souls within to their endearments
for the same space of time; they will soon know the extent of the
danger in which their foster boy is placed.
But the priest knows it, and he walks up and down, peering
sometimes into the darkness beyond the green, in the direction of
the town, scrutinizing the faces of the passers-by, until curfew rings
from the tower of his own church. Then he re-enters the cottage.
Cuthbert, hunger satisfied, is seated in the chimney-corner; the
logs sparkle in the draughts of wind, which find their entrance
through every cranny; the aged couple are seated as before.
“Father, we have told Cuthbert that you think he ought not to stay
here, but he says he is bound to remain over the morrow; that will
not hurt, will it?”
“Not if he is unseen, and the news of his coming has not got
abroad.”
“Did anyone see thee, child, as thou enteredst the town?”
“Alas, I fear one did; Nicholas Grabber was hanging about the
gate on the common.”
“Nicholas Grabber; then, my boy, thou must not tarry an hour; it is
he who hast already betrayed thee.”
“Betrayed me! how?” said Cuthbert, alarmed.
Then the priest told Cuthbert all that our readers have already
learned from his lips, and the lad at once recognized his danger, for
he remembered how Nicholas had lurked about the Abbot’s chamber
that eventful night, when the secret was revealed to him.
“You are right, Father,” he said, “I must go.”
“Too late!” said the priest, “too late!”
For at that moment the tramp of many feet was heard without,
followed by a violent knocking at the door, which the priest
fortunately had barred when he entered.
“Hide him,” said the good man; “I will keep them at bay for a few
minutes.”
And the old people hurried Cuthbert out of the room.
“The back door,” said the boy.
“Nay, that is watched too; I hear them whispering without.”
“Then I am lost.”
“No! no! my boy,” said the old woman, “come up stairs, and get
into the loft.”
They went hastily up the stairs, into the old people’s bedroom.
There was no ceiling, but that which plain boards overhead,
separating them from the attic beneath the roof, afforded; knocking
one of these aside with his staff, the old man bade Cuthbert mount
on his shoulders, and get into the loft. The lad did so easily, for the
roof of the room was low, and then replaced the boards, so that no
one could see that there had been any disturbance thereof.
The loft was often used for the storage of fruit, corn, flax, and the
like, and there was a quantity of the latter material stored therein;
on this Cuthbert lay.
Meanwhile the priest below fulfilled his task.
“Who are ye, disturbing an honest family after curfew?”
“Officers of the law, constables; open, in the name of the law.”
“There be many who avail themselves of that name, with very
little title; robbers be about, and I must have surer warrant ere I
admit you.”
“Open, or we will break down the door.”
“Nay, and thou come to that game, there be those within, good at
the game of quarter staff; meanwhile we will blow the horn and
rouse the watch.”
“Thou old fool, we will break thy bones, as well as the door; we
tell thee we are the constables—the watch.”
“’Tisn’t old Hodge’s voice,” said another; “ask the fellow who he
is.”
“Who art thou, fool?”
“That is for wise men like thee to find out.”
“Well, then, here are Roger Hancock, John Sprygs, James Griggs,
Denis Howlet, the four constables, and Laurence Craveall, a body
servant of Sir John Redfyrne.”
“I fear me, friend, thou art taking the names of better men in
vain; more to the token, thou showest thyself a liar: for well do I
know that neither Jack Sprygs nor Jim Griggs ever leave the ale-tap
after curfew, until it is time to tumble, drunk, into their sinful beds.”
“Break open the doors,” cried the two impugned worthies, in a
rage.
“I will loose the mastiff upon you.”
But in spite of this direful threat, which it would have been difficult
to fulfil, as no mastiff was in the house, the men commenced
breaking down the door.
At that instant old Hodge appeared, and signifying by a sign all
was right, cried aloud—
“What are you doing at my door?”
“Breaking it down, with a search warrant for our justification.”
“Thou mayst save thyself the trouble; I have nought here to hide;”
and the old man withdrew the bars.
Four ill-looking men, Jacks in office, entered, and behind them two
faces appeared, whose owners preferred to stay without; the one
was the valet of Sir John Redfyrne, the other Nicholas Grabber.
The two constables whom he had so grievously aspersed fixed
their eyes upon the priest.
“So it was thou, was it, who kept us waiting?”
“Your pardon, if I mistook you; doubtless you have good cause for
your untimely errand.”
“We have pulled down monks, and your turn may come next,” said
the surly John Sprygs, “and then you may not have the chance of
taking sober folks’ reputation away; but enough of this, where is
that young rascal, Cuthbert Hodge, if that is his name, we have a
warrant for his apprehension?”
“Why, he has been away ever since November.”
“But came home to-night; here is the witness. Nick Grabber, when
didst thou last see Cuthbert Hodge?”
“This evening, riding with another lad through the common gate,
on the Langport Road.”
“And does thy worshipful father permit thee, now thy school days
are over, to spend thy time in Glastonbury as a spy?” said old Hodge.
“My worshipful father has given me to the care of Sir John
Redfyrne, as a page, old man, so thou hadst better keep a civil
tongue in thine head, and it will be better for thy young bastard’s
bones; he shall pay for it.”
“I think, my son,” said the priest very quietly, “that when thou
wast coupled between two hounds, as a truant, thou must have
learnt from them to bite and snarl.”
“We have no time for all this nonsense,” said the head constable,
“where is this youngster?”
“Since you say he is here, you had better find him.”
“He has not gone out by the back door,” said Grabber.
“Or you would have grabbed him.”
“Even so, with right good will.”
They proceeded to search the house, but all in vain, and they
were at length about to conclude that the boy had left the place
before their entrance, when Grabber remarked to one of the
constables, that he might be above the boards of the bedroom.
“When we were schoolfellows,” he said, “I have often heard him say
that very good apples were kept there.”
“The boy has got the right sow by the ear,” says James Griggs,
and followed by the others, he went upstairs again, whereupon the
old lady began to cry.
“Ah,” said Nicholas, “the scent is hot, the old lady gives tongue.”
A board was withdrawn, chests piled beneath, and John Sprygs
cried out, “Now, young Nick, you go and grab him.”
“After you,” said Nicholas, who remembered the weight of his
young opponent’s fist that night in the woods.
John Sprygs mounted, and was no sooner in the loft than he
cried,—
“The place is as dark as pitch, pass me up the torch.”
“Nay! nay!” cried Giles Hodge, “the place is full of flax.”
“We will take care of that; thou dost not want thy precious brat
found.”
Up went the torch which the men had brought with them, a flaring
pine torch, to assist in the operations; in very wantonness Nick
Grabber tossed it into the fellow’s hand, crying “Catch.” He missed it,
and it fell into a heap of flax. The man started back to avoid the
blaze which instantly sprang up, and so put the fire between him
and the moveable planks—the only moveable ones—which served as
a trap-door.
“Come down, come down,” called out the appalled voices below.
But the wretch could not face that sea of flame, until, maddened
by desperation, he took a header as boys might say, at the opening
through the fire, and falling head foremost on the bedroom floor,
split his skull and died on the spot. The others could do nothing for
him, the loft was one mass of flame, and shouting “Fire! Fire!” they
ran to get water, in a vain attempt to save the cottage. But of this
there was little hope; the roof was of thatch, and the building mainly
of timber, so they saw in a few minutes that there was nothing for it
but to help the aged couple to save their furniture.
But what of Cuthbert? they had forgotten him, for the time, then
they said,—
“The boy couldn’t have been there, nor in the house, or he would
be driven from his hiding-place now. See how unconcerned the old
man looks; he wouldn’t look so if his precious boy were in danger.”
FOOTNOTES
[22] Multiply by twelve for the modern equivalent. See Note H.
[23] A priest of Chichester, named Christopherson, suffered
death for saying that the king would be damned for the
destruction of the monasteries.
CHAPTER IX.
IN THE RUINS OF THE ABBEY.
o, Cuthbert was not burnt, as the reader has already
conjectured, or our tale would come to an untimely
close, untimely as the death of our hero, and we will
now explain the manner of his escape.
Once in the loft, he remembered that in the innocent confidence
of his boyhood, he had prated of its treasures to Grabber, who he
doubted not was with his pursuers, and he felt that there was scant
safety in his hiding place.
But there was yet an avenue of escape: a little opening at the end
of the loft, which the ill-fated constable had overlooked, like a
dormer window, admitted light and air to the loft; if he could force
himself through that, and it was only a very small opening, he would
emerge on the roof, and in the darkness might descend and escape
unseen.
He tried and succeeded, and sliding down the long sloping roof, as
he had often done when a small boy, alighted at the back of the
house, while all the officers were within, those who had kept guard
without, having joined the rest, when they judged by the uproar,
that the lad was found.
But one yet watched there,—the priest who rejoiced to see him.
He had left the house when Grabber told the secret, from reluctance
to witness the capture of the harmless boy.
“Thank God, my boy,” he said, “thou hast outwitted them; go and
hide in the Abbey ruins, I shall be there at midnight, I have business
there, in the desecrated church; I will tell thy friends thou art safe;
go at once.”
The boy darted away for the Abbey, but soon he heard loud
shouts of “Fire!” “Fire!” and saw the reflection of the flames in
objects around. Full of anxiety for his foster parents, he could not
help turning back, and would again have run into danger, for the
officers, anticipating such a result, were looking everywhere
amongst the crowd, and would surely have seen him, had not his
wise friend, the good parish priest, also anticipated the same, and
met him.
“Nay, nay, my lad, thou canst do no good, and wilt only add to
their troubles; go into the Abbey church and wait there till midnight;
thou art not afraid?”
“No,” said Cuthbert, “only take care of them,” and he retraced his
steps to the Abbey.
“The Boy darted away for the Abbey.”
Page 92.
The moon had arisen, and illuminated the scene, when through a
gap in the boundary wall Cuthbert entered the once sacred
precincts; his heart was very heavy as he gazed upon the mutilated
cloisters, doors torn from their hinges, windows dashed out, roofless
chambers from which the lead had been torn,—gazed as well as a
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

PPT
Web Services - Lectures and architecture.ppt
PPT
Web2 And Java
PPT
Best Web services tutorial | Websoles Strategic Digital Solutions
PPT
Web services Tutorial /Websoles Strategic Digital Solutions
PPT
Detailed information on webservice by websoles
PDF
Path Analyzer X-Files: How We Built the Ultimate xDB Forensic Tool
PPT
Konsep pembangunan tapak web & laman web
Web Services - Lectures and architecture.ppt
Web2 And Java
Best Web services tutorial | Websoles Strategic Digital Solutions
Web services Tutorial /Websoles Strategic Digital Solutions
Detailed information on webservice by websoles
Path Analyzer X-Files: How We Built the Ultimate xDB Forensic Tool
Konsep pembangunan tapak web & laman web

Similar to Javascript For Sound Artists Learn To Code With The Web Audio Api William Turner Steve Leonard (20)

PPTX
Front End Lecture 1.pptx
PDF
Practical Web Development 1st Edition Wellens Paul
PDF
Process Engineering and Design Using Visual Basic 2nd Edition Datta
PPT
Introduction to the Windows Live Platform
PDF
Fundamentals of Web Development For Non-Developers
PDF
Bc460 Sapscript Form Printing And Text Management Sap Technology
PDF
Web Development Presentation
PPTX
Introduction to Web Architecture
PDF
The Ember.js Framework - Everything You Need To Know
PDF
Frontend Development The Ultimate Guide Sufyan Bin Uzayr
ZIP
The Power of Open Data
PDF
Javascript Essentials For Dummies Paul Mcfedries
ODP
Integrating CC Licensing with Applications
PPT
Microformats Workshop (2009)
PDF
webdevelopment, engineering, institue of engineering purwanchal campus , Nepa...
PPT
Lecture7
PDF
Introduction to the Web and HTML
PDF
Meteor Workshop - Open Sanca
KEY
Extend Your Use of JIRA by Solving Your Unique Concerns: An Exposé of the New...
KEY
Extend Your Use of JIRA by Solving Your Unique Concerns: An Exposé of the New...
Front End Lecture 1.pptx
Practical Web Development 1st Edition Wellens Paul
Process Engineering and Design Using Visual Basic 2nd Edition Datta
Introduction to the Windows Live Platform
Fundamentals of Web Development For Non-Developers
Bc460 Sapscript Form Printing And Text Management Sap Technology
Web Development Presentation
Introduction to Web Architecture
The Ember.js Framework - Everything You Need To Know
Frontend Development The Ultimate Guide Sufyan Bin Uzayr
The Power of Open Data
Javascript Essentials For Dummies Paul Mcfedries
Integrating CC Licensing with Applications
Microformats Workshop (2009)
webdevelopment, engineering, institue of engineering purwanchal campus , Nepa...
Lecture7
Introduction to the Web and HTML
Meteor Workshop - Open Sanca
Extend Your Use of JIRA by Solving Your Unique Concerns: An Exposé of the New...
Extend Your Use of JIRA by Solving Your Unique Concerns: An Exposé of the New...
Ad

Recently uploaded (20)

PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
Classroom Observation Tools for Teachers
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
master seminar digital applications in india
PDF
01-Introduction-to-Information-Management.pdf
PDF
Computing-Curriculum for Schools in Ghana
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
Institutional Correction lecture only . . .
Abdominal Access Techniques with Prof. Dr. R K Mishra
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Pharmacology of Heart Failure /Pharmacotherapy of CHF
O7-L3 Supply Chain Operations - ICLT Program
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Classroom Observation Tools for Teachers
Supply Chain Operations Speaking Notes -ICLT Program
human mycosis Human fungal infections are called human mycosis..pptx
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
master seminar digital applications in india
01-Introduction-to-Information-Management.pdf
Computing-Curriculum for Schools in Ghana
VCE English Exam - Section C Student Revision Booklet
Anesthesia in Laparoscopic Surgery in India
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Microbial diseases, their pathogenesis and prophylaxis
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Institutional Correction lecture only . . .
Ad

Javascript For Sound Artists Learn To Code With The Web Audio Api William Turner Steve Leonard

  • 1. Javascript For Sound Artists Learn To Code With The Web Audio Api William Turner Steve Leonard download https://ebookbell.com/product/javascript-for-sound-artists-learn- to-code-with-the-web-audio-api-william-turner-steve- leonard-55920178 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Javascript For Sound Artists Learn To Code With The Web Audio Api 2nd Ed 2nd Edition William Turner https://ebookbell.com/product/javascript-for-sound-artists-learn-to- code-with-the-web-audio-api-2nd-ed-2nd-edition-william-turner-43705376 Javascript For Sound Artists Learn To Code With The Web Audio Api 2nd Ed 2nd Edition William Turner https://ebookbell.com/product/javascript-for-sound-artists-learn-to- code-with-the-web-audio-api-2nd-ed-2nd-edition-william-turner-43852254 Javascript For Sound Artists Learn To Code With The Web Audio Api 1st Edition Leonard https://ebookbell.com/product/javascript-for-sound-artists-learn-to- code-with-the-web-audio-api-1st-edition-leonard-5744048 Javascript For R Chapman Hallcrc The R Series 1st Edition John Coene https://ebookbell.com/product/javascript-for-r-chapman-hallcrc-the-r- series-1st-edition-john-coene-45035150
  • 3. Javascript For Web Developers Understanding The Basics 1st Edition Mark Simon https://ebookbell.com/product/javascript-for-web-developers- understanding-the-basics-1st-edition-mark-simon-53488768 Javascript For Hackers Learn To Think Like A Hacker Heyes Gareth https://ebookbell.com/product/javascript-for-hackers-learn-to-think- like-a-hacker-heyes-gareth-57673010 Javascript For Programmers 1st Edition Paul J Deitel Harvey M Deitel https://ebookbell.com/product/javascript-for-programmers-1st-edition- paul-j-deitel-harvey-m-deitel-2016688 Javascript For Web Designers Mat Marquis https://ebookbell.com/product/javascript-for-web-designers-mat- marquis-22892838 Javascript For Impatient Programmers Es2020 Edition Dr Axel Rauschmayer https://ebookbell.com/product/javascript-for-impatient-programmers- es2020-edition-dr-axel-rauschmayer-22933706
  • 7. JavaScript for Sound Artists Learn to Code with the Web Audio API
  • 8. JavaScript for Sound Artists Learn to Code with the Web Audio API Authored by: William Turner Edited by: Steve Leonard
  • 9. CRC Press Taylor & Francis Group 6000 Broken Sound Parkway NW, Suite 300 Boca Raton, FL 33487-2742 © 2017 by Taylor & Francis Group, LLC CRC Press is an imprint of Taylor & Francis Group, an Informa business No claim to original U.S. Government works Printed on acid-free paper Version Date: 20161208 International Standard Book Number-13: 978-1-138-96153-1 (Paperback) This book contains information obtained from authentic and highly regarded sources. Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot assume responsibility for the validity of all materials or the consequences of their use. The authors and publishers have attempted to trace the copyright holders of all material reproduced in this publication and apologize to copyright holders if permission to publish in this form has not been obtained. If any copyright material has not been acknowledged please write and let us know so we may rectify in any future reprint. Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopying, microfilming, and recording, or in any information storage or retrieval system, without written permission from the publishers. For permission to photocopy or use material electronically from this work, please access www.copyright.com (http://www.copyright.com/) or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978-750-8400. CCC is a not-for-profit organization that provides licenses and registration for a variety of users. For organizations that have been granted a photocopy license by the CCC, a separate system of payment has been arranged. Trademark notice: Product or corporate names may be trademarks or registered trademarks, and are used only for identification and explanation without intent to infringe. Library of Congress Cataloging-in-Publication Data Names: Turner, William (Web site developer), author. | Leonard, Steve (Web site developer), author. Title: JavaScript for sound artists : learn to code with the Web Audio API / William Turner, Steve Leonard. Description: Boca Raton : Taylor & Francis, CRC Press, 2017. Identifiers: LCCN 2016032832| ISBN 9781138961531 (pbk. : alk. paper) | ISBN 9781138731134 (hardback : alk. paper) Subjects: LCSH: Computer sound processing. | JavaScript (Computer program language) | Webcasting. Classification: LCC TK7881.4 .T87 2017 | DDC 006.5--dc23 LC record available at https://lccn.loc.gov/2016032832 Visit the Taylor & Francis Web site at http://www.taylorandfrancis.com and the CRC Press Web site at http://www.crcpress.com
  • 10. Contents Preface Acknowledgment 1. Overview and Setup What Is a Program? What Is JavaScript? HTML, CSS, and JavaScript What Is a Web Application? What Is the Web Audio API? Setting Up Your Work Environment Setup View in Browser for Windows Setup View in Browser for Mac How to Create Code Snippets Accessing the Chrome Developer Tools Troubleshooting Problems and Getting Help 2. Getting Started with JavaScript and the Web Audio API Hello Sound Program Variables null Documenting Your Code with Comments Exploring Variables with an Oscillator console.log() String Built-In String Methods
  • 11. toUpperCase() toLowerCase() charAt() replace() slice() The length Property Numbers How to Determine the Data Type of a Variable Examples of Arithmetic Operators Examples of Precedence Math.min() and Math.max() Math.ceil() and Math.floor() Math.random() Math.abs() Number-to-String Conversion Arrays push() pop() shift() unshift() concat() Summary 3. Operators What Are Operators? Assignment Operators Assignment Addition Assignment Subtraction Assignment Multiplication Assignment Division Assignment Modulo Assignment The Boolean Data Type Comparison Operators Equality Operator Strict Equality Operator Greater Than and Less Than Operators Greater Than or Equal to Operator Less Than or Equal to Operator Not Equal to Operator
  • 12. Strict Not Equal to Operator Logical Operators The Logical AND Operator The Logical OR Operator The NOT Operator Summary 4. Conditional Statements and Loops Conditional Statements The if Statement The switch Statement Ternary Operator Loops for Loops Using for Loops with Arrays while Loops When to Use for Loops and When to Use while Loops Summary 5. Functions Functions—A Simple Example Parts of a Function Function Expressions Abstracting Oscillator Playback A Working Effects Box Example The Arguments Object Function Scope Why You Should Always Declare Your Variables with var Variable Hoisting How Hoisting Affects Functions Anonymous Functions Closures What Is a Closure? Callback Functions Working with JavaScript’s Built-In Callback Functions filter() map() Recursion
  • 13. Summary 6. Objects JavaScript Data Types Looping through Objects When to Use Objects Rather Than Arrays How to Check If an Object Has Access to a Particular Property or Method Cloning Objects Prototypal Inheritance The "this" Keyword The bind Function Summary 7. Node Graphs and Oscillators The AudioContext() Method Node Graphs Oscillators The stop Method The onended Property How to Stop Oscillators and Restart Them The type Property The frequency Property The detune Property Summary 8. Using HTML and CSS to Build User Interfaces What Is a User Interface? HTML Explanation of the HTMLTemplate Understanding HTMLElements Form and Input Elements CSS Comments Element Selectors Grouping Selectors Descendent Selectors Child Selectors
  • 14. class and id Modifying the App Interface Margin, Border, and Padding Removing List Element Bullet Points Font Size, Style (Type), and Color Centering Block-Level Elements Summary 9. DOM Programming with JavaScript How Does JavaScript Communicate with the DOM? HTML JavaScript Building the Application How to Trigger an Oscillator by Clicking a Button Toggling the Start/Stop Text Programming the Frequency Slider Changing the Frequency in Real Time Changing Waveform Types Completed Code with Waveform Selection Giving an Outline to the Selected Waveform Type Summary 10. Simplifying DOM Programming with JQuery What Is JQuery? JQuery Setup Referencing JQuery Directly Using JQuery from a CDN How to Use JQuery Selecting HTMLElements Storing DOM Selectors as Variables Using Methods HTML JQuery/JavaScript to Change a Single Property JQuery/JavaScript to Change Multiple Properties Method Chaining HTML CSS JQuery/JavaScript HTML
  • 15. JQuery/JavaScript The this Keyword HTML JQuery/JavaScript Refactoring the Oscillator Player to Use JQuery Without JQuery With JQuery Setting Up the Event Listener for the User-Selected List Element Event Listener without JQuery Event Listener with JQuery Modifying the Code in setInterval setInterval Method without JQuery setInterval Method with JQuery onOff Method without JQuery $onOff Selector with JQuery Summary 11. Loading and Playing Audio Files Prerequisites The Two Steps to Loading an Audio File The XMLHttpRequest Object get Requests A Word on Audio File Type Compatibility Synchronous versus Asynchronous Code Execution Processing the Audio Buffer with the Node Graph Summary 12. Factories and Constructors JavaScript and the Concept of Class What Are Classes? The Factory Pattern Dynamic Object Extension Private Data Getters and Setters Constructors and the new Keyword Adding Methods to Constructors The Prototype Object and the Prototype Property Why Do Constructors Exist If You Can Do the Same Thing with Factories?
  • 16. Summary 13. Abstracting the File Loader Thinking about Code Abstraction Creating the Abstraction Walking through the Code Summary 14. The Node Graph and Working with Effects How to Think About the Node Graph Gain Nodes The Placement of Nodes Is Up to You What Effects Are Available? How to Determine the Nodes You Need to Create the Effect You Want A Real-World Example Some Effects Require Development Work Summary 15. The Biquad Filter Node Using the Biquad Filter Node Filter Types Creating an Equalizer Graphic EQ Parametric EQ Summary 16. The Convolver Node Convolution Reverb Where to Get Pre-Recorded Impulse Response Files Using Impulse Response Files HTML JavaScript Controlling the Amount of Reverberation Summary 17. Stereo Panning, Channel Splitting, and Merging The Stereo Panner Node
  • 17. The Channel Splitter The Channel Merger Merging All Channels of a Multichannel File into a Single Mono Channel Using the Merger and Splitter Nodes Together Summary 18. The Delay Node The Delay Node Creating Echo Effects Creating Slap Back Effects Creating a Ping-Pong Delay Summary 19. Dynamic Range Compression The Dynamics Compressor Node Summary 20. Time The Timing Clock The start Method Looping Sounds Update Your Audio Loader Library Changing Audio Parameters over Time The Audio Parameter Methods The setValueAtTime Method The exponentialRampToValueAtTime Method The linearRampToValueAtTime Method The setTargetAtTime() Method The setValueCurveAtTime() Method Summary 21. Creating Audio Visualizations A Brief Word on Fourier Analysis A Brief Explanation of Binary-Coded Decimal Numbers The Spectrum Analyzer JavaScript/JQuery HTML
  • 18. CSS Walking through the Code Storing the Frequency Data in an Array How to Think About the frequencyData Array Building the Display Interface Connecting the Analyzer to the DOM Summary 22. Adding Flexibility to the Audio Loader Abstraction The Updated Interface Modifying the Library Modifying audioBatchLoader An Explanation of the Previous Code Edit Summary 23. Building a Step Sequencer The Problem Can I Use setInterval or setTimeout? The Solution How It Works Changing Tempo Building the Sequencer Playing Back Sounds in Sequence Creating the User Interface Grid HTML CSS Adding Interactivity to the Grid Elements Summary 24. AJAX and JSON AJAX JSON Making an AJAX Call to the iTunes Search API How the Code Works HTML JavaScript Creating Your Own Web API to Reference Synthesizer Patch Data The Data Structure
  • 19. HTML CSS How the Code Works Building on the API data.js module.js Extend the JSON Object Summary 25. The Future of JavaScript and the Web Audio API The Web Audio API 1.0 3D Spacial Positioning Raw Modification of Audio Buffer Data Suggestions for Continued Learning JavaScript 6 node.js The Web MIDI API Open Sound Control Summary Further Reading Book Website Index
  • 20. Preface Learning to program can be daunting, and we want to be the first to congratulate you for taking on the challenge! Second, we want to thank you for choosing this book. Who Is This Book For? This book is for anyone who is involved in the world of creative audio and wants to learn to program using the JavaScript language. There are many programming books directed toward artists to help them build websites, mobile applications, games, and other things, but next to none is directed exclusively toward the sound arts community. This book is designed to fill this role and to teach the fundamentals of web-based software development, and specifically, the basics of the JavaScript programming language to sound artists. What This Book Is Not This book is not an audio technology reference. It does not take the time to explain the fundamentals of audio theory or sound engineering in depth. Words and phrases like dynamic range compression, convolution reverb, and sample rate are thrown around like candy with only a cursory explanation (if they are explained at all). We assume that you are either familiar with many of these core audio concepts or know enough to find the answers on your own. If you need an accommodating audio technology reference, we suggest David Miles Huber’s excellent book Modern Recording Techniques, Taylor & Francis. This book is also not directed toward experienced programmers who are simply interested in JavaScript or the Web Audio API. If this describes you, then you may find some value here, but you are not the intended audience.
  • 21. How to Learn to Program The following are a few tips to help you get the most from this book. Make Connections Generally, it is easier to learn new things by making associations and connections to areas that you are already familiar with. If you have ever programmed a synth or a MIDI sequencer, then you have already done a form of programming. The contents of this book are designed to be a bridge that connects a world you are (presumably) familiar with (sound and audio technology) to a topic you are less familiar with—JavaScript and programming. We suggest that you tap into whatever has drawn you to sound art while learning the material in this book. Flow and Frustration Are Not Opposites It’s very important to embrace a sense of flow when learning to program. It is also important to embrace frustration as part of the flow state and not as the antithesis of it. When you learn something new, the neurons in your brain are making connections; this may physically feel like frustration, but it just means your brain is rewiring—literally. Embrace this. Make It Habitual Programming is all about learning a bunch of little things that combine to make big things. The best way to learn a lot of little things is through repetition and habit. One way to do this is to simply accept programming as a new part of your lifestyle and do a little bit (or a lot) every day. Be Creative and Have Personal Projects It is a good idea to have your own personal programming projects. The more you are personally invested in a project, the more you will learn. Talk and Teach One of the best ways to validate your own learning is to teach someone else. If you don’t have anyone to teach, then you can substitute this by writing tutorials. This will force you to collect your thoughts and express them clearly. Keep Going
  • 22. Our final piece of advice is to simply stick with it. Best of luck! If you have any questions or comments, you can find us at: http://www.javascriptforsoundartists.com William Turner Steve Leonard
  • 23. Acknowledgment Thanks to technical assistant Keith Oppel.
  • 24. 1 Overview and Setup What Is a Program? A program is any set of instructions that is created or followed. In this book, we focus on writing computer programs, which are lists of instructions that a computer carries out. These instructions can be written and stored in various forms. Some of the first modern computers used punched cards, switches, and cables. Early analog music synthesizers were a type of computer that used a patchbay style interface to manually allow a programmer to create specific sounds. What Is JavaScript? JavaScript is a multipurpose programming language initially created to aid developers in adding dynamic features to websites. The language was initially created in 11 days and released in 1995 by a company called Netscape. Developed by Brendan Eich, its original release name was LiveScript. When Netscape introduced support for the language in its browser, LiveScript was renamed JavaScript. Although JavaScript is similar in name to the Java programming language, they are completely unrelated. Today, JavaScript is used in everything from robotics to home automation systems. HTML, CSS, and JavaScript The three main technologies used to build websites and web applications are HTML, CSS, and JavaScript. HTML stands for hypertext markup language and is the standard by which we create documents for the World Wide Web. You program HTML by writing elements (sometimes referred to as tags for brevity). These elements contain text and other nested elements, which make up the document’s content.
  • 25. CSS stands for cascading style sheets and is a tool used to modify how HTML elements and text are presented. CSS is primarily a visual design tool. For example, with CSS you could modify an HTML element and give it an orange background, change its font size, place it vertically or horizontally, or perform any number of creative visual changes. JavaScript is used to add interactive responses to user input. Every time a user clicks, scrolls, taps, moves the mouse cursor, types, or performs an interactive event, JavaScript code can be triggered to change the page in some manner. The JavaScript language was initially designed to perform these functions within the context of designing websites and applications. What Is a Web Application?
  • 26. A web application is any website that contains more than static, non-interactive pages. This means that, in a web application, the pages have some interactive components in addition to the static text and images displayed. In the early days of the World Wide Web, websites were composed mostly of collections of static documents connected through highlighted text called hyperlinks. These static pages had no interaction with databases. In the early 1990s, this began to change, and web developers began creating websites that had features similar to desktop applications that allowed users to interact with the page via form fields, buttons, and other interactive means to send data over a web server to and from a database. Early web applications were slow and limited by the technology of the time. In the early 2000s, a culmination of technical shifts that included client-side- rather than server-side-focused web applications helped make web applications more responsive. Part of this shift is attributable to a technology called AJAX (asynchronous JavaScript and XML). This technology pushed dynamic web application development forward by allowing the browser to retrieve and send data to a web server without having to automatically refresh the page in the process. As the J in AJAX indicates, JavaScript is central to this technology, and web applications began to approach the interactive speed of their desktop counterparts. As you might expect, within the audio world there were attempts to leverage this new technology, which resulted in browser-based audio players, editors, and musical instruments. Many of these applications were initially written using a technology called Flash. This is a proprietary technology that required the user to download and install an additional plug-in to run all programs written in it. In 2008, a newer version of the HTML standard was written, called HTML-5. This version included an audio player that could directly stream sound files off a web server using a single line of HTML code. The player also included built-in, user-facing controls for play, fast-forward, rewind, pause, stop, loop, and other actions. However, for serious audio development, this was inadequate. Web application developers and audio aficionados wanted something more fully featured. What Is the Web Audio API? The Web Audio API is a series of exposed code pieces that you can use to accomplish musical and audio tasks in a web browser with less effort than if you were to create them all from scratch. The unexposed portion of the Web Audio API lies in the web browser’s source code and is written in whatever language the web browser itself is written in. The technical core of web browsers is usually written in multiple lower-level languages, which can include (but are not limited to) C++, Java, and machine language. To understand the Web Audio API, you must first understand what an API is. API stands for application programming interface. An API is a portion of code that a programmer is given access to, which controls a larger unseen body of code within certain constraints. Imagine if, in order to learn how to play your favorite musical instrument, you had to literally build it from scratch. As you can imagine, this would get very tedious—especially if the instrument were to break. Thus, it’s much more convenient to learn to play a premade musical instrument. The
  • 27. convenience here is that the construction process is removed and your only concern is what is important to you, which is the controls needed to use the instrument. In a similar manner, programmers write APIs that expose only small pieces of code for developers to use, and these small pieces of code allow you to do a lot of work with minimal effort. In addition to being able to load and play back sound files, the Web Audio API also allows you to generate sound from scratch in the form of oscillators. You can then manipulate any sound playback or generation using filters, reverb effects, dynamic compressors, delay effects, and a host of other options. Setting Up Your Work Environment To begin working, you must first determine what browser you are going to troubleshoot with. In real-world environments, you would use a test suite to troubleshoot among different browsers and platforms. In this book, we are going to keep things simple and only use Google Chrome. The next thing you need is a code editor. For the exercises, we assume you will be using the Sublime Text editor. Technically, you can use any code editor you want, but Sublime Text is offered as a free trial download and is extremely powerful and widely used. We think it’s worth your investment of time to learn it. The next thing you need to do is create a folder with a basic work template. 1. If you are not already using it, go to this URL to download and install Google Chrome: https://www.google.com/chrome/browser/desktop/. 2. Go to http://www.sublimetext.com/ and download and install Sublime Text. 3. Create a folder on your desktop or in a directory and call it web audio template. 4. Open Sublime Text, and in the window that appears, type the following code into it. Then save the file (go to the File menu in Sublime Text and click Save As) as index.html and choose your web audio template folder as the directory to save it in. <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>app</title> <script src="js/app.js"></script> <link rel="stylesheet" href="css/app.css"> </head> <!--__________________________________________BEGIN APP--> <body> </body> <!--____________________________________________END APP--> </html> 5. Inside the web audio template folder, create another folder called css.
  • 28. 6. In Sublime Text, create a new file by going to the File menu and click New. Save this file in your css folder as app.css. Leave the contents of this file empty. 7. In the web audio template folder, create another folder called js. 8. Create a new empty document in Sublime Text, then type "use strict"; (including quotations and semicolon) at the top of it and save it as app.js in the js folder you just created. This places your JavaScript in strict mode. Strict mode is a restrictive form of JavaScript that enforces better programming practices. All JavaScript code examples in this book will assume you have strict mode enabled. You are now going to add a few extensions to Sublime Text that will make working with the editor easier in the long term. To do this, you must first download and install the package manager plug-in. Go to the following link and follow the directions on the left side of the window: https://packagecontrol.io/installation. When done, close the console by entering the keys: Ctrl + ` (apostrophe, on the key with the ~). 1. In the Sublime Text menu, go to Tools > Command Palette, and in the form field that appears, type install. You should see an option menu appear that says Package control: Install package. Click this menu option. 2. Another form field with a series of options appears. This form field allows you to search and explore various plug-ins for Sublime Text. You are now going to install a plug-in that allows you to create a local web server that will be necessary when working with audio files. In the form field, type Sublime server. A list of search results should appear. Click the first one. Look at the bottom of the Sublime Text window, and you should see “installing” in small text. When this process is done, quit and restart Sublime Text. We will cover the specifics of the web server in a later chapter. But rest assured that this setup will be time well spent. To verify that the plug-in is installed, go to Tools > SublimeServer > Start SublimeServer. Open your web browser to http://localhost:8080/, and it should display SublimeServer at the top of the page. 3. This last plug-in you are going to install lets you open HTML files in Chrome from within Sublime Text. To install the View in Browser plug-in, go to Tools > Command Palette and in the form field that appears, type install. Click Package control: Install package. Then do a search for View in Browser, and select the first option that appears. Once the installation is done, you will need to go to the following menu to set up the plug-in to work with Chrome. Setup View in Browser for Windows In Sublime Text, go to the Preferences menu and click Package Settings. Look for the View in Browser menu item, hover over it, and select Settings – Default. Select all the code you see and copy it. You are now going to paste it into the Settings – User page of the same plug-in. So go back to the Preferences menu and select Package Settings > View in Browser > Settings – User.
  • 29. Paste all the code you just copied into this window. At the very bottom, you should see a line of code that says “browser”: “firefox”. Change the word firefox to either chrome, or chrome64 if you have a 64-bit operating system. It should look like this: “browser”: “chrome” or “browser”: “chrome64”. If you open an empty document in Sublime Text and use the key command Ctrl + Alt + V , Chrome should launch and open that page. Setup View in Browser for Mac As soon as the plug-in is downloaded, you should be able to open an empty Sublime Text document in Chrome using the key command Control + Option + C. How to Create Code Snippets It can be helpful to know how to create code snippets that you can access without writing them out character-by-character every time. Thankfully, Sublime Text has a feature that allows you to do this with snippets. To create a snippet, do the following steps: 1. In Sublime Text menu, go to Tools > New Snippet. 2. In the window that appears, delete everything on line 3 and paste the following text: This is a test snippet. 3. On line 6, remove the <!-- and --> characters and type the word test in between the two elements. The result should look like this: <tabTrigger>test</tabTrigger>.
  • 30. 4. Save the file in the default directory that appears and call it test.sublime-snippet. 5. Open your index.html file in Sublime Text, type the word test, then tap the TAB button on your keyboard. The phrase "this is a test snippet" should appear in the editor. Accessing the Chrome Developer Tools Google Chrome has a built-in suite of troubleshooting tools called the Chrome Developer Tools. You can access these tools by opening the browser and using the key commands: Windows OS or Linux: Ctrl + Shift + J Mac: Command + Option + J We are not going to go over the utility of the developer tools just yet, but they will be highlighted throughout the book. Troubleshooting Problems and Getting Help If you have any trouble, try using search engines to research solutions. One very good resource is http://stackoverflow.com, which is a community of programmers who ask and answer questions. They have a nice section on JavaScript as well as a lively Web Audio API community that you can find at: http://stackoverflow.com/questions/tagged/web-audio.
  • 31. 2 Getting Started with JavaScript and the Web Audio API Hello Sound Program In an introduction to a programming language, the first program you write is often called “Hello World,” which prints the words “Hello World” on the screen. Because we are using the Web Audio API to create sounds, this section explains how to create a “Hello Sound” application that immediately plays a sound when you run it. Copy the folder web audio template from the last chapter to a new directory, and rename the copy to hello_sound. Type the code below into the app.js file that is present within the hello_sound folder. Save it and then launch the index.html file from your web browser. You should hear a basic sine wave oscillator playing. var audioContext = new AudioContext(); var osc = audioContext.createOscillator(); osc.type = "sine"; osc.connect(audioContext.destination); osc.start(audioContext.currentTime); After you verify that the Hello Sound program works, close the browser. You just wrote your first Web Audio API program! The code you just ran is a basic oscillator generation and playback script. The first line in the script is called the “Audio Context” and this tells the browser that you are using the Web Audio API. The next line of code creates an oscillator. The third line of code assigns a waveform type to the oscillator, whereas line four connects the oscillator to a virtual audio output called the destination, which is analogous to the speakers of your computer. The last line starts the oscillator playing. We will cover detailed operation of the Web Audio API in future chapters. First, though, we need to cover the basics of the JavaScript language.
  • 32. Variables One of the first steps in writing a program is understanding variables and variable assignment. Variables are word forms that are used to store data. For example: var waveformType = "sawtooth"; The variable here is named waveformType. This is preceded by the var keyword. You always specify the var keyword prior to declaring the variable. Declaring a variable means you are creating a new variable. After the var keyword, you type a space and give a name to your variable. Variable names are typically a reflection of something they represent. In this case, the variable is being used to describe a type of oscillator waveform and so is named waveformType. You probably noticed the odd capitalization of the word “type” in waveformType. The convention of capitalizing words to distinguish them within variable names is called camel case. This convention is used because variable names cannot contain white space to separate them. If you rewrote the variable in the following manner, you get an error: var waveform type = "sawtooth"; //____returns an error Type the above code into the app.js file of your hello_sound template. Launch Chrome and open the developer tools (Windows: Ctrl + Shift + J or Mac: Command + Option + J). Inside the console tab, you should see an error similar to the one in the following image. The text in gray is the actual error and is identified as a syntax error. To the right of the error, you can see the file and the line number where the error occurred. This number corresponds to the line number in your file, which might differ from the one in the image. After you see the error, remove the line you added that is causing the error in app.js and save the file. After you declare and name a variable, you can assign some data to it. You use the assignment operator “=” to do this. It is important to understand that in JavaScript the “=” symbol is not called the equal sign and its functionality does not mean equal to. The “=” symbol indicates assignment, so it is called the assignment operator. The value on the right side of the assignment operator contains the data you want to assign to the variable name on the left side. In the following example, the string "sawtooth" is assigned to the variable waveformType. var waveformType = "sawtooth"; When you assign a string of words to a variable, you must place them between quotation marks. The resulting data type is called a string. Data types represent the types of data that you
  • 33. can use in your program. Different programming languages have different data types. JavaScript has six data types, and one of these is the string data type (see Chapter 6 for a list of JavaScript data types). After you assign data to your variable, you must end the variable declaration with a semicolon. In summary, there are five parts to a variable declaration: ■ The var keyword ■ The variable name ■ The assignment operator ■ The data you wish to assign to the variable ■ The closing semicolon You can assign multiple variables at once using the following syntax: var osc1 = 1200, osc2 = 1300, osc3 = 100; In some cases, you might want to declare a variable and not assign data to it, as in the following example: var waveformType; If you do this, JavaScript automatically assigns undefined to it. You can also assign undefined explicitly like this: var waveformType = undefined; The keyword undefined is another JavaScript data type. Notice that undefined is not enclosed in quotation marks because it is not a string but represents a data type. null The primitive value null is similar to the primitive value undefined. Both can act as a placeholder for empty variables. When the typeof operator (discussed later in this chapter) is used to determine the type of null, the result is object. This is not what you might expect and is a flaw in the language. The correct returned value should be null. Because of this, we suggest that you never use null and always use undefined. Documenting Your Code with Comments
  • 34. When you are programming, it is a good habit to type messages into your code that are intended to be read by human beings (yourself or others) and not be interpreted by the computer. These messages are called comments. You can write either single-line or multiline comments in your program, and they look like this: //This is a single line comment. //It begins with two forward slash characters //These end at the end of the line /* This is a multi-line comment and begins with a forward slash and asterisk. It ends with an asterisk and a forward slash */ In a real-world scenario, we might comment our code like this: var waveformType = "sawtooth"; // oscillator variable All the characters from the // to the end of the line are ignored by the computer. Exploring Variables with an Oscillator Now that you understand what variables are, the following example shows how you use them. Open up the code you wrote at the beginning of this chapter, and add the variable waveformType to it, as in the following code: var audioContext = new AudioContext(); var waveformType = "sawtooth"; //___added variable var osc = audioContext.createOscillator(); osc.type = "sine"; osc.connect(audioContext.destination); osc.start(audioContext.currentTime); Replace the osc.type assignment with the waveformType variable like this: var audioContext = new AudioContext(); var waveformType = "sawtooth"; //___added variable var osc = audioContext.createOscillator(); osc.type = waveformType; //__Assigned it to our oscillator type osc.connect(audioContext.destination); osc.start(audioContext.currentTime); Launch your web browser, and instead of hearing a sine waveform, you should hear a sawtooth waveform. In this example, the following declarations assign values to variables that represent other waveform types. var audioContext = new AudioContext(); //___ 4 variables that represent oscillator waveforms var saw = "sawtooth"; var sine = "sine"; var tri = "triangle"; var square = "square"; //___ A variable intended to contain one of these waveforms var currentWaveform = undefined; currentWaveform = square;
  • 35. //_____________________________Start of oscillator var osc = audioContext.createOscillator(); osc.type = currentWaveform; // Assigned it to our oscillator type osc.connect(audioContext.destination); osc.start(audioContext.currentTime); Each of the four new variables contains a string that represents an oscillator waveform type. The square variable is assigned to the currentWaveform variable in the following line: currentWaveform = square; Notice that no new declaration is required for the currentWaveform variable to assign (and replace) whatever was previously assigned to it. The new data on the right side of “=” is assigned to currentWaveform. If you launch your web browser, you will hear a square wave play. In programming, being able to overwrite variables in this manner is referred to as mutability (changeability), and we say that variables are mutable. The opposite of this is called immutability. console.log() When programs begin to get big, it can be difficult to know what value is assigned to a variable at any given moment. One way you can find out is by using a built-in feature called console.log(). The way you do this is by typing console.log() into your code at the point where you want to check a given variable’s assignment. You then place the variable name inside the parentheses. To see what the currentWaveform variable has as its assignment, you do this: var audioContext = new AudioContext(); //Added 4 variables that represent oscillator waveforms var saw = "sawtooth"; var sine = "sine"; var tri = "triangle"; var square = "square"; var currentWaveform = undefined; currentWaveform = square; console.log(currentWaveform); //___ square //____________________________________Start of oscillator var osc = audioContext.createOscillator(); osc.type = currentWaveform; // Assigned it to our oscillator type osc.connect(audioContext.destination); osc.start(audioContext.currentTime); Launch Chrome, open the developer tools and click the console tab; you will see the output of our console.log(). One thing to remember is that because variables can have different values at different times, the output of console.log() depends on where it is placed in the program. If you modify the last example and place console.log() immediately after the currentWaveform variable, which has undefined assigned to it, then undefined is output to the log.
  • 36. //__________A variable intended to contain one of these waveforms var currentWaveform = undefined; console.log(currentWaveform); //______results in "undefined" currentWaveform = square; So far we’ve mentioned three of the six data types in JavaScript. The first was string, the second was undefined, and the last was null. Before we go further, let’s explore the string data type a bit more in depth. String As we already discovered, strings are denoted by quotation marks. The variable below is a string: var oscillator = "square"; You can manipulate strings in different ways. One of the most common is by combining multiple strings into one string. This is called concatenation, and it works by using the plus sign (+) like this: var oscillator = "saw" + "tooth"; console.log(oscillator); // sawtooth Here is another example of concatenating two variables and storing them in a new variable. var phrase = "This sound is an "; var soundType = "oscillator"; var sentence = phrase + soundType; console.log(sentence); // "This sound is an oscillator". Notice that strings can contain white space. This is a perfectly valid string, even though it contains a lot of white-space characters: var myFavoriteSynthCompany = "My favorite synth company is Moog"; If you want to get the number of characters in a string, you can use what is called the length property like this: console.log(myFavoriteSynthCompany.length); // 33 The output of the length property includes the white-space characters of the string. Built-In String Methods JavaScript has a series of built-in tools called methods that allow you to manipulate data. Some of these methods are specifically designed to manipulate string data. These are called string methods. To see how to use a string method, take a look at the examples of the toUpperCase() and toLowerCase() methods.
  • 37. toUpperCase() This method changes all the characters in a string to uppercase. var oscillator = "sawtooth"; oscillator.toUpperCase(); // SAWTOOTH toLowerCase() This method changes all the characters in a string to lowercase. var oscillator = "SAWTOOTH"; oscillator.toLowerCase(); // "sawtooth" Some useful string methods are: charAt() Returns a character at any given index in a string replace() Finds and replaces a group of characters in a string slice() Extracts part of a string You do not need to immediately memorize how each of these methods works, but it’s a good idea to know about them. This way, when you do need to implement any of the functionalities they provide, you know which tool to reach for. If you would like to explore more string methods, a good resource is the Mozilla Developer Network at: https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Global_Objects/String. Let’s go through each one of these and explain how to use them. charAt() This method gets a character at any given index value within a string. For example, if you have the string "oscillator-1" and want to know what the second letter of this string is without actually looking at it, you can do this: var sound = "oscillator"; console.log(sound.charAt(1)); // "s" Now you might be wondering why charAt(1) returns “s” and not "o". The reason is that the count begins at zero. So, to get the first letter do this: console.log(sound.charAt(0)); // "o" When an index list begins with zero, it is called a zero-based index. replace()
  • 38. This method finds a group of characters in a string and replaces them with another string. If you want to replace an entire word, you can do it like this: var myFavoriteSynthCompany = "My favorite synth company is Moog. Moog is great!"; var myNewFavoriteSynthCompany = myFavoriteSynthCompany. replace("Moog","Dave Smith Instruments"); console.log(myNewFavoriteSynthCompany); /*My favorite synth company is Dave Smith Instruments. Moog is great!*/ As you probably noticed, when using the replace method in this manner it only replaces the first instance of the word you select. To replace all instances of the word, you need to use the following syntax to globally replace them in the string. var myFavoriteSynthCompany = "My favorite synth company is Moog. Moog is great!"; var myNewFavoriteSynthCompany = myFavoriteSynthCompany. replace(/Moog/gi,"Dave Smith Instruments"); console.log(myNewFavoriteSynthCompany); /*My favorite synth company is Dave Smith Instruments. Dave Smith Instruments is great!*/ The g stands for global and the i denotes case insensitivity. If you want the string replacement to be case sensitive, you use a g and omit the i. These characters are part of a pattern-matching language for string data called regular expressions. Regular expressions are an advanced topic that will not be covered further in this book. slice() This method extracts part of a string. var oscillator = "sawtooth"; var sound = oscillator.slice(0,3); console.log(sound); // saw Like charAt(), slice() works on a zero-based index. This means the first character is always zero. The slice method takes two values: a beginning index value and an ending index value. When a method takes values, they are called arguments. The charAt() method takes one argument. The slice() method takes two arguments. The slice method’s first argument is where the slice starts, and this value is included in the slice. The second value is where the slice ends and is noninclusive. This means all the characters up to, but not including, the second value are included in the slice. The length Property The length property is an additional tool that allows you to get the number of characters in a string. A property looks similar to a method but does not include parentheses and does not require arguments to return a value. The character count of the length property starts at one, not zero.
  • 39. var instrument = "piano"; console.log(instrument.length); // 5 If you want to get the last value of a string, you can combine the length property with the charAt() method. This allows you to retrieve the last character in a string in a manner that doesn’t require you to know how long the string is. The code shows an example of this. The reason you subtract 1 from the length property is because the length property begins counting at one, whereas charAt() begins counting at zero. Therefore, you subtract 1 from the length property to compensate for the offset. var sound = "oscillator-1"; var oscNumber = sound.charAt(sound.length - 1); console.log(oscNumber); // 1 Numbers In JavaScript, numbers are a distinct data type. Below is a variable named frequencyValue, and it is assigned a number of 200. It is then assigned to the oscillator’s pitch. If you place the code below in a new JavaScript file and run it, you will hear an oscillator play at a frequency of 200 Hz. Modify the number value assigned to the frequencyValue variable and launch the code to hear the oscillator play at different pitches. var audioContext = new AudioContext(); var frequencyValue = 200; //___Create variable frequencyValue var waveform = "sawtooth"; var osc = audioContext.createOscillator(); osc.type = waveform; //_____ assign it to the oscillators pitch osc.frequency.value = frequencyValue; osc.connect(audioContext.destination); osc.start(audioContext.currentTime); How to Determine the Data Type of a Variable You can discern the difference between data types in variables by using the typeof operator. var waveform = "sine"; var polyphony = 16; console.log(typeof waveform); // string console.log(typeof polyphony); // number Unlike strings, numbers do not use quotation marks. In fact, if you did use a number with quotation marks, its data type would not be number, it would be string. Here’s an example: var oscillators = "6"; var polyphony = 6; console.log(typeof oscillators); // string console.log(typeof polyphony); // number
  • 40. You can do basic math with numbers using the following symbols. These symbols are called arithmetic operators. + Addition − Subtraction * Multiplication / Division % Modulo Examples of Arithmetic Operators console.log(5 + 5); // 10 console.log(10 - 5); // 5 console.log(5 * 5); // 25 console.log(25 / 5); // 5 console.log(10 % 9); // 1 The last symbol (%) might be new to you, and it is pronounced moj-uh-loh. The purpose of this symbol is to output the remainder of a division. So, for example: console.log(12 % 9); // This equals 3 The precedent rules of algebra also apply. If you wrap a calculation in parentheses, the calculation inside the parentheses is performed first. Examples of Precedence var oscillator1 = 1000; var oscillator2 = 100; var oscillator3 = 20; var combinedOscillator = oscillator1 +(oscillator2 * oscillator3); console.log(combinedOscillator); // 3000 If you want to do more elaborate calculations, JavaScript has a built-in tool called the Math object, which allows you to use a collection of math methods to manipulate numbers. So, for example, if you want to round a decimal number to its nearest integer, you can use Math.round() like this: Math.round(1000.789); // outputs 1001 Some useful math object methods are:
  • 41. Let’s go over each of these one by one. If you would like to explore more math methods, a good site is the Mozilla Developer Network at: https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Global_Objects/Math. Math.min() and Math.max() Math.min() finds the smallest number in a collection of numbers, whereas Math.max() allows you to find the largest number in a collection of numbers. Math.min(5000, 2000, 80); // 80 Math.max(5000, 2000, 80); // 5000 //___________________________With variables var freq_1 = 5000; var freq_2 = 2000; var freq_3 = 80; Math.min(freq_1, freq_2, freq_3); // 80 Math.max(freq_1, freq_2, freq_3); // 5000 Math.ceil() and Math.floor() These two methods turn a decimal number into an integer. Math.ceil() rounds up to the next higher integer value if there are any nonzero digits to the right of the decimal, whereas Math.floor() keeps the integer value after discarding the digits to the right of the decimal. Math.ceil(3.00333); // 4 Math.floor(3.9999); // 3 Math.random() The random method creates a random number between zero and one. var randomNumber = Math.random(); console.log(randomNumber); // example: 0.019790495047345757 You can combine Math.random() with Math.floor() to create a random number between two values. The expression in the following example creates a random integer between 20 and 20,000.
  • 42. var max = 20000; var min = 20; var randomInteger = Math.floor(Math.random() * (max - min + 1) + min); console.log(randomInteger); // Between 20 and 20000 Math.abs() The abs method allows you to get the absolute value of a number. var num = Math.abs(-100); console.log(num); // 100 This is useful for finding the difference between numeric variables of unknown values. var a = 1000; var b = 5000; console.log(Math.abs(b - a)); // 4000 Number-to-String Conversion If you want to convert between numbers and numeric strings, you can use the following techniques. To convert a string to a number, place the plus symbol (+) before the string like this: var numericString = "120"; var num = +numericString; // plus symbol console.log(num); // 120 console.log(typeof num); // number If you want to convert a number to a numeric string, concatenate the number with an empty string like this: var num = 80; var numericString = num + ""; console.log(numericString); // 80 console.log(typeof numericString); // string If you attempt to do a math operation using nonnumeric values, sometimes you will receive a returned value of NaN. This stands for not a number. Here is an example of attempting to add two values in which one value is a number and the other is not. var osc1 = undefined; var osc2 = 200; console.log(osc1 + osc2); // NaN Arrays
  • 43. Arrays are a construct that holds multiple pieces of data. You can think of them as variables that hold more than one item. Arrays are expressed using brackets, where each item is separated by a comma. Each item in the array is designated an index number with the first item starting at zero. var waveforms = [ ]; // empty array var waveforms = ["square", "sawtooth", "triangle", "sine"]; // array with some data If you want to access any of these data, you can use the following notation: waveforms[0]; // square waveforms[1]; // sawtooth waveforms[2]; // triangle waveforms[3]; // sine waveforms[4]; // undefined (no data) If you want to know how many items are inside an array, use the length property like this: var waveforms = ["square", "sawtooth", "triangle", "sine"]; waveforms.length; // 4 Arrays come with built-in methods that you can use to manipulate the data in them. A full list of these are available at the Mozilla Developer Network at this URL: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array. We are only going to go over a handful of these and they are: push() Adds additional items to the end of an array pop() Removes a single item from the end of an array shift() Removes a single item from the beginning of an array unshift() Adds additional items to the beginning of an array concat() Concatenates arrays together into one array push() This method adds items to the end of an array. var synthFrequencies = [5000, 1000, 500]; synthFrequencies.push(100); /*This places a new item at the end of the array*/ console.log(synthFrequencies); // [5000, 1000, 500, 100] You can use the push method to add multiple items at once. var synthFrequencies = [5000, 1000, 500]; synthFrequencies.push(100, 50, 30); console.log(synthFrequencies); // [5000, 1000, 500, 100, 50, 30]
  • 44. pop() This method removes a single item at the end of an array. var synthFrequencies = [5000, 1000, 500]; synthFrequencies.pop(); console.log(synthFrequencies); // [5000, 1000] If you want to capture the last item you removed from an array in a variable, do this: var synthFrequencies = [5000, 1000, 500]; var lastItem = synthFrequencies.pop(); console.log(lastItem); // 500 shift() This method removes an item from the beginning of an array. var synthFrequencies = [5000, 1000, 500]; synthFrequencies.shift(); console.log(synthFrequencies); // [1000, 500] If you want to capture the first item you removed from an array in a variable, do this: var synthFrequencies = [5000, 1000, 500]; var firstItem = synthFrequencies.shift(); console.log(firstItem); // 5000 unshift() This method adds new items to the beginning of an array. var synthFrequencies = [5000, 1000, 500]; synthFrequencies.unshift(7500, 6000); console.log(synthFrequencies); // [7500, 6000, 5000, 1000, 500] concat() This method merges multiple arrays together into one array. var drumMachines = ["MPC", "Machine", "TR 808"]; var keyboards = ["Juno", "ARP", "Jupiter"]; var percussion = ["vibraphone", "bongos"]; var stringed = ["guitar", "bass", "harp"]; var instruments = drumMachines.concat(keyboards, percussion, stringed); console.log(instruments); /* ['MPC','Machine','TR 808','Juno','ARP', 'Jupiter','vibraphone','bongos','guitar','bass','harp'] */
  • 45. Summary In this chapter, you learned about variables, comments, numbers, strings, and arrays. In the next chapter, you will learn about various assignment and logical operators.
  • 46. 3 Operators You learned about the basic assignment operator (=) and some of the arithmetic operators in the previous chapter. In this chapter, we are going to explore other assignment operators, as well as comparison operators, that allow you to determine the relationship between variables and values, such as whether they have the same value. We will also explore the Boolean data type, which has either a true or a false value that can be assigned to variables or is the result of a comparison operation. What Are Operators? Operators represent actions that you use to change the value of a variable, or compare values or variables. The word operand is used to describe a value being used in an operation involving operators. So in the following example, the operands are 300 and 400. The output of the comparison is said to be what the expression evaluates to. In the following example, the operation evaluates to false. 300 == 400 /*The values here (300 and 400) are called operands, and the output evaluates to false.*/ Operators fall into arithmetic, assignment, or logical categories. The arithmetic operators that we covered in the previous chapter are used with numbers. The assignment operators are used to assign values to variables. The logical operators are used to compare two values and return a true or false value based on the result of the comparison. Assignment Operators Assignment operators are used to assign data to variables. Here is a list of assignment operators:
  • 47. Assignment This operator assigns a value to a variable. var osc = 100; With assignment operators, you can also assign variables to other variables. var osc1 = 100; var osc2 = osc1; console.log(osc2); // 100 Addition Assignment This operator increments a numeric variable or appends a string to a variable. In the following example, an oscillator is assigned a value of 100 and then incremented by 100 to give it a value of 200. var osc = 100; osc += 100; console.log(osc); // 200 To demonstrate the use of the addition assignment operator, the following code sets an ever- increasing frequency change to an oscillator and you can listen to the effect. A method called setInterval() is defined, although the specifics of setInterval() are not important at this time. What is important is understanding that the addition assignment operator is incrementing the frequency value by 100 every 0.5 seconds when setInterval() is called. var audioContext = new AudioContext(); var osc = audioContext.createOscillator(); osc.frequency.value = 300; osc.connect(audioContext.destination); osc.start(audioContext.currentTime); setInterval(function(){ osc.frequency.value += 100; /*____Increment frequency value by 100 every 0.5 seconds*/ console.log(osc.frequency.value); //_____View change },500); //________________________500 milliseconds is 0.5 seconds
  • 48. When you use the addition assignment operator with a string, the string you supply is concatenated with the variable. Here is an example: var keyboards = ""; keyboards += "Korg "; keyboards += "Yamaha "; keyboards += "Kurzweil "; console.log(keyboards); // Korg Yamaha Kurzweil Subtraction Assignment This operator is used to decrement a numeric variable. var osc = 500; osc -= 100; console.log(osc); // 400 Multiplication Assignment This operator multiplies a variable with a value and assigns it to the variable. var osc = 200; osc *= 2; osc *= 2; console.log(osc); // 800 Division Assignment This operator divides a variable by a value and assigns it to the variable. var osc = 200; osc /= 2; osc /= 2; console.log(osc); // 50 Modulo Assignment This operator divides a variable by a value and assigns the remainder of that division to the variable. var osc = 200; osc %= 150; console.log(osc); // 50 The Boolean Data Type
  • 49. The Boolean data type is either true or false. This is conveyed by the word-form values true and false. Booleans are important because you can use them to program on or off (true or false) values into the code. So, for example, you could use them as a value that toggles an oscillator on or off. Assigning a Boolean value to a variable in JavaScript looks like this: var oscillatorIsOn = true; // true oscillatorIsOn = false; // changed to false Boolean values can also be the result of the comparison operators described below or used in conditionals statements, which we will cover in the next chapter. Comparison Operators Comparison operators are used to compare two variables or values. They output a true or false value depending on whether the variables or values are similar or different from one another in some way. The similarity or difference being tested for is dependent on the operator used. So, for example, if you test whether two values are the same using the strict equality operator (= = =) and they are not the same, the resulting value is false. There are eight comparison operators. Equality Operator This operator checks whether the left operand is equal to the right operand. It then returns a Boolean value to represent the outcome of the comparison. 200 == 200; // true "200hz" == "200hz"; // true var osc1 = "200hz"; var osc2 = "200hz"; console.log(osc1 == osc2); // true The equality operator can be a bit tricky because it attempts to do a data type coercion before comparing operands. Data type coercion occurs when the code interpreter (in our case the web browser) attempts to convert one data type into another. In the following example, we compare a
  • 50. number and a numeric string. JavaScript tries to convert the string to a number before doing the comparison. If the string is a numeric string, the conversion is successful, and the comparison is performed. In this case, the result of the comparison is the Boolean value true because the numeric string “200” is successfully converted to the value 200, which matches the value of osc1. var osc1 = 200; var osc2 = "200"; console.log(osc1 == osc2); // true If a nonnumeric string is compared against a number, the result is always false. 200 == "oscillator" // false Strict Equality Operator To protect against the confusion of type coercion using the equality operator, you can use the strict equality operator. This operator does not do data type coercion. This means that, if any numeric string is compared against a number, the result is always false. For newer JavaScript programmers, we suggest that you always use this operator. Restricting yourself to this operator helps to mitigate problems involving coercion before they start. //_________________________Examples 900 === 900 // true var osc1 = 200; var osc2 = "200"; console.log(osc1 === osc2); // false Greater Than and Less Than Operators These operators produce a Boolean result that is based on whether the left operand is less than or greater than the right operand. 100 < 200 // true 300 < 200 // false 300 > 200 // true 300 > 500 // false The greater than and less than operators do data type coercion as shown in this example: 600 > "500" // true 600 < "500" // false Greater Than or Equal to Operator This operator returns a Boolean value of true if the first operand is greater than or equal to the second operand.
  • 51. var osc1 = 300; var osc2 = 500; var osc3 = 300; osc3 >= osc1 // true osc2 >= osc1 // true osc1 >= osc2 // false The greater than or equal to operator does data type coercion as shown in this example: 300 >= "300" // true Less Than or Equal to Operator This operator returns a Boolean value of true if the left operand is less than or equal to the right operand. 300 <= 300 // true 300 <= 500 // true 300 <= 200 // false The less than or equal to operator does data type coercion as shown in these examples: 300 <= "300" // true 300 <= "500" // true 300 <= "200" // false Not Equal to Operator This operator is a combination of the NOT symbol and the equal sign. The NOT symbol is expressed as an exclamation mark and is sometimes referred to as the bang operator. When NOT is coupled with an equal sign to produce the not equal to operator, it can be used to return a Boolean value that is based on whether two values are not equal to each other. If the two values are not equal, the result is true. If the two values are equal, the result is false. 300 != 200 // true 300 != 300 // false The not equal to operator does data type coercion as shown in this example: "300" != 300 // false Strict Not Equal to Operator This operator returns a Boolean value that is based on whether two values are not equal to each other. The strict not equal to operator, unlike the not equal to operator, does not do type coercion. "300" !== 300 // true 300 !== 300 // false
  • 52. Logical Operators Logical operators allow you to check if a collection of statements is true or false and return a Boolean value based on this information. Logical Operator Name && AND || OR ! NOT The Logical AND Operator The logical AND operator evaluates to true only if all the operands are true. The way it works is that first, the value on the right side of the operator is evaluated, and if its value is false, the Boolean value of false is returned. In this case, the value on the left side of the operator is never considered! If the value on the right side of the operator evaluates to true, then and only then does the AND operator check the value on the left side of the operator. If the value on the left side of the operator is false, then the Boolean value false is returned. In the case where both the values on the left and right sides of the logical AND operator are true, the Boolean value true is returned. true && true // true true && false // false false && true // false false && false // false The Logical OR Operator This operator returns true as long as either of the operands is true. true || true // true true || false // true false || true // true false || false // false The NOT Operator This operator inverts a Boolean value. !false // true !true // false Another way to look at this code is that, if a value is not false, then it is true, and if its value is not true, then it is false.
  • 53. In JavaScript, there are six values that evaluate to false. They are the following: false "" null undefined 0 NaN All other values evaluate to true. When you specify the NOT operator twice in a row before a variable or an operand, the resultant value is its original Boolean value. !!false // false !!true // true !!0 // false !!"" // false !!null // false !!undefined // false !!NaN // false Summary In this chapter, you learned about JavaScript assignment and logical operators, the Boolean data type, and what values evaluate to false. In the next chapter, you will learn to leverage these tools using two new concepts: conditionals and loops.
  • 54. 4 Conditional Statements and Loops Conditional statements and loops are two of the most widely used constructs in programming. Conditional statements allow your program to make choices based on a set of criteria. Loops use repetition, allowing your program to complete many tasks quickly. Conditional Statements To create programs that do more than basic calculations or print text, they must be able to make decisions. You can program these decisions by using conditional statements. Conditional statements check if a value is true or false and then execute a branch of code based on this condition. We are going to go over the following three conditional statements: ■ if ■ switch ■ ternary The if Statement The syntax of an if statement consists of the if keyword, a pair of parentheses, and two curly braces. This is what an empty if statement looks like: if(){ } To use an if statement, you place a value or condition inside the parentheses and some code to execute inside the curly braces. If the condition inside the parentheses evaluates to true, the code inside the curly braces is executed. If the condition evaluates to false, no action is taken and the code inside the curly braces is skipped. In the following code, an if statement is used to
  • 55. Random documents with unrelated content Scribd suggests to you:
  • 56. But while they were there a body of armed men entered the house. They wore the uniform of the King’s guard: there was no regular army in those days, every man was a soldier in time of need, but there was a small body of men kept about the King’s person, who were sent from time to time on special services, and were called the King’s “beef-eaters.” And these were some of them. “Landlord, bring us some mulled sack,” said one who appeared to be their leader, “and tell us, have you seen that fox the Abbot of Glastonbury pass this way to-day on his road home?” “He has not yet returned from London?” “Nay, but he is on his way,—we have no listening ears have we?” The boys were separated by a partition. “Are you for Abbot or King?” “I am a friend to the King.” “Well said, so should every good Englishman be; and we have charge to arrest this wily Abbot on his return, as a foe to King Harry, and take him to Wells to be tried for his life.” “Has he not been tried and acquitted?” “He has been solemnly condemned in a Court where Thomas Cromwell sat as prosecutor, jury and judge: but that is not quite the law, so he has been dismissed home, and we have been sent by an after thought to take him to Wells for a regular trial.”[16] “On what charge?” “Robbing the Abbey Church.” “Good heavens!” “Why, I thought thee a friend of the King.” “So I am, but what can all this mean?”
  • 57. “That he hid the Abbey plate, so that the King’s visitors could not find it, when they wanted to make an inventory, and confiscate patens and chalices for the King’s use.” “But it was his own.” “Only in trust, you see.” “Still he might hide it in trust for the Abbey, that would not be robbery.” “Friend, I should advise thee to consider it robbery in these days; it is better for all men who do not want their necks stretched to think as the King and his minister, Thomas Cromwell, think; don’t fear but we shall find men to bring him in guilty.” The poor inn-keeper was silent; perhaps he remembered that one of his predecessors had been hanged for saying he would make his son heir to the “Crown,” meaning the “Crown Inn.” The boys stole out unobserved. “What shall we do?” “Go and meet the Abbot and warn him, he will pass Headly Cross.” “But then we may but share his fate,” said several. “I shall go if I go alone,” said Cuthbert. “And so shall I,” said Gregory Bell. “Well, two are as good as the lot of us, and better; more likely to pass unobserved,” said Adam Banister; “the rest of us had better get home, and tell the monks all we have heard and seen.” It was a wild place, Headly Cross, where two woodland roads crossed each other. Report said that a cruel murder had been committed there years agone, and that the place was haunted; every one believed in haunted places then.
  • 58. But as there was a choice of routes, and the Abbot might come either way, it was the right thing to await him where the roads converged. And there Cuthbert and Gregory waited all alone, as the dark hours rolled away, until they heard the “Angelus” ring from a distant tower, and knew it was nine o’clock, when decent people, in those days, went to bed. The chime had hardly died away, when they heard the tread of horses, and soon three riders came in view in the dim light of the stars; and the boys recognised the Abbot, with two attendants, one his faithful serving man, the other a stranger. Cuthbert dashed forward. “My Lord Abbot,” he said, “one moment, it is I, Cuthbert, and here is Gregory Bell.” “Cuthbert and Gregory Bell; why are you here, boys?” “We have heard a plot against you: men are waiting at the ‘Cross Keys’ to arrest you, and take you for trial at Wells; they say it will cost your life.” “On what charge?” “Concealing the Abbey plate.” The Abbot smiled sadly. “My children,” he said, “this can hardly be true, yet if it be as you say, I will not fly a jury of my countrymen.” “Neither could he,” said the stranger on his left hand, “if he would; my duty is to see him safe to Glastonbury, unless relieved beforehand by royal authority.” “You see, my Cuthbert and Gregory, that your devotion is all in vain; neither would I avail myself of it if I could. Mount on the pillion behind me, Cuthbert; my good Ballard here will take Gregory behind him, and you may return with us to Glastonbury, if such return be permitted.” “It never will be, never will be,” said Cuthbert, with sinking heart.
  • 59. And how that young heart beat, as they approached the “Cross Keys,” and as a line of men, forming across the road, stopped the cavalcade. “My Lord Abbot, we arrest you in the King’s name.” “On what charge?” “Robbery of the Abbey Church.” “This is a base pretence, to deprive me of the credit of martyrdom for my convictions: but there was One who suffered more for me.” And the Abbot yielded himself peacefully to those who sought his life. FOOTNOTES [15] Advantage was taken of the Abbot’s compulsory absence to take the necessary steps for the dissolution of the monastery. (Froude.) [16] In some private memoranda of Thomas Cromwell, which still exist in his own hand-writing, occur the words,—“Item. The Abbot of Glaston to be tried at Glaston, and also to be executed there with his accomplices.” The trial, however, took place at Wells, the execution (a foregone conclusion) at Glastonbury, as related in the story.
  • 60. CHAPTER VI. THE TRIAL. he period of English history of which we are now writing has been aptly called “The Reign of Terror.” England under Thomas Cromwell, and France under Robespierre, were alike examples of the utter prostration which may befall a mighty nation beneath the sway of one ruthless intellect. To make the King absolute, and himself to rule through the King, was the one aim of the man whom Fox, the Martyrologist, grotesquely calls “The valiant soldier of Christ:”—for this end he smote down the Church and the nobility: Bishop Fisher and the Carthusians represented the ecclesiastical world, the Courtenays and the Poles the aristocracy, Sir Thomas More the new-born culture of the time; and Cromwell chose his victims from the noblest and the best. The piety of Fisher, once the King’s tutor, to whom his mother had committed her royal boy on her death-bed, could not save him; nor his learning, Sir Thomas More; nor her grey hairs, the Countess of Salisbury. Spies were scattered through the land; it was dangerous to speak one’s mind in one’s own house; nay, the new inquisition claimed empire over men’s thoughts; we have seen that the concealment of one’s sentiments was treason. Will my more youthful readers wonder then that men could be found to convict upon such charges as those preferred against the aged Abbot of Glastonbury? They need wonder at nothing that
  • 61. occurred while Bloody Harry was King, and Thomas Cromwell Prime Minister. The juries themselves sat with a rope around their necks; when the Prior and the chief brethren of the Charter-house waited upon Cromwell to explain their conscientious objections to the Oath of Supremacy, loyally and faithfully, he sent them from his house to the tower; when the juries would not convict the ecclesiastics, he detained them in court a second day, and threatened them with the punishment reserved for the prisoners, unless they found a verdict for the crown; finally, he visited the jurymen in person, and by individual intimidation forced the reluctant men to find a verdict of guilty, whereupon the unfortunate monks were hanged, drawn, and quartered, with every circumstance of barbarity, suspended, cut down alive, disembowelled, and finally dismembered.[17] Thursday, the fourteenth of November, 1539, was a gloomy day: black leaden clouds floated above, the ground was sodden with moisture, the leaves, fallen leaves, no inapt emblem, rotted in the slime, a heavy damp air oppressed the breath; the day suited the deed, for on that day the aged Abbot of Glastonbury was formally arraigned at Wells, together with his brethren the Prior and Sub- Prior, on the charge of felony,—“Robbery of the Abbey Church with intent to defraud the King.” They might well have proceeded against him under the Act of Supremacy, but variety has charms, and this new idea of felony commended itself to the mind of Cromwell, as a good device for humbling the clergy. Lord Russell, one of Henry’s new nobility who supplied the places left vacant by so many ruthless executions, whose own fortunes were built on the plunder of the Church, sat as judge, and there were empannelled, we are told, “as worshipful a jury as was ever charged in Wells.” The indictment set forth that the prisoners had feloniously hidden the treasures of the Abbey, to wit, sundry chalices, patens,
  • 62. reliquaries, parcels of plate, gold and silver in vessels, ornaments, and money, with the intent of depriving our sovereign lord the King of his rightful property, conferred upon him by Act of Parliament. “What say you, Richard Whiting, guilty or not guilty?” The aged prisoner looked around him with wondering eyes; he scanned the crowded array of spectators, then the jury, who looked half ashamed of their work, and finally rested his eyes upon his judge. “How can I plead guilty where there can be no guilt? These treasures were committed to my care to keep for God and Holy Church; it is not meet to cast them to swine; no earthly power may lawfully take to itself the houses of God for a possession, or break down the carved work thereof with axes and hammers. Am I tried before an assembly of Christian men, or before heathen, Turks, infidels, and heretics?” “It is not meet for a prisoner to revile his judges,” said Russell; “as an Englishman you are bound by the Acts of Parliament.” “Talk not to me of Parliament; you have on your side but the Parliament of this sinful generation, and against you are all the Parliaments who have sat from the Witan-agemot downwards, who have granted and confirmed to us of Glastonbury, those possessions which you would snatch from a house which has been the light of this country for a thousand years; to resist such oppression and sacrilege is not guilt, and I plead in that sense, ‘Not Guilty.’” “Thou showest but little wisdom in pressing thine own opinion against the consent of the realm.” “I would fain hold my peace; but that I may satisfy my conscience, I will tell thee that while thou hast on thy side but a minority in a single kingdom, the whole of the Christian world, save that kingdom, is dead against you, and even the majority here condemn your proceedings, although the fear of a barbarous death silences their tongues.”
  • 63. “Of whom art thou speaking?” “Of all the good men present.” “Why hast thou persuaded so many people to disobey the King and Parliament?” “Nay, I have sinned in dissembling my opinions, but now I will speak. I disallow these changes as impious and damnable (general sensation); I neither look for mercy nor desire it; my cause I commit to God, I am aweary of this wicked world, and long for peace.” He sank upon the bench behind him, as did his fellow prisoners, and none of them took any further obvious interest in the proceedings. Formal evidence was brought to prove the discovery of treasure hidden in secret places, but all this fell very flat upon the audience, the fact was tacitly admitted on both sides, the difference of opinion only existed as to the guilt thereof. There was no room for doubt in Lord Russell’s mind; he summed up the evidence against the prisoners, and reminded the jurymen that their own loyalty was on trial, a very forcible hint in those days, and one which few men dared disregard. They retired; returned with downcast looks, and gave a verdict in accordance with the evidence: theirs not to argue the point of law, the fact was sufficient. “Prisoners at the bar,” said the judge, “you have been convicted on the clearest evidence of an act of felony—of seeking to deprive the King of the property willed to him by the high estates of the realm, in trust for the nation. Into your motives I need not enquire, but no man can be a law unto himself; born within these realms you are subject to the authorities thereof, and for your disobedience to them you must now die. The only duty remaining to me is to pronounce upon you the awful sentence the law provides against your particular crime—that you be taken hence to the prison whence you came, and from thence be drawn on the morrow, upon a hurdle, to the summit
  • 64. of Glastonbury Tor, that all men far and wide may witness the royal justice, where you are to be hanged by the neck, but not until you are dead, for while you are still living, your bodies are to be taken down, your bowels torn out and burnt before your faces; your heads are then to be cut off, and your bodies divided, each into four quarters, to be at the King’s disposal, and may God have mercy upon your souls.”[18] A dead silence followed, broken at last by the Abbot’s voice. “We appeal from this judgment of guilty and time-serving men to the judgment of God, before Whose bar we shall at length meet again.” It was late in the same evening, the curfew had already rung, the rain was still falling at intervals in the streets of Glastonbury, as if nature wept at the approaching dissolution of the venerable fane which had been the ornament of western England so long. In spite of the weather, many groups formed from time to time outside the gatehouse of the Abbey, for there the three prisoners had been brought from Wells, and there, in the chamber over the gateway, in strict ward, they were passing the last night the royal mercy permitted them to live. A youth, repulsed from the door which gives admittance to the upper chambers, retired with despairing gesture; his face bore marks of intense emotion, the tears had worn furrows therein, and from time to time a sob escaped him. A companion pressed up to his side. “Will they not let you in?” “No, Gregory, I have begged in vain these three times.” “Why not try the sheriff, he is said to be merciful?”
  • 65. “I can but try, I will go to his house at once.” As due to his office, the high sheriff of the county was charged with the details of the morrow’s tragedy; he liked the task but little, still he viewed it as a simple matter of duty, and could not flinch from it. He was resting after the fatigues of the day, and in truth, thinking very uneasily over the events of the trial. “What if, after all, he is in the right—that appeal to the judgment bar above was very solemn—when that great assize takes place, in whose shoes would it be best to stand, in the place of the judge or the felon of to-day?” A domestic entered—“A lad craves a moment’s speech.” “Who is he?” “I know him not, but he has been weeping bitterly, as one may see by his face.” The sheriff hesitated, but he was in a merciful mood; he suspected the object of the visitor, and it was a good sign for the success of the suppliant that he permitted the visit. “Well, my lad,” said he, as Cuthbert entered, “what is the matter now?” “I have a boon to crave, your worship; you will not refuse it me?” “Let me first hear what it is.” “The Abbot has been my adopted father, my best friend from childhood; let me see him once more, let me receive his parting blessing, ere wicked hands slay him.” “Wicked hands, my lad, you forget yourself, and where you are.” “Pardon me, I meant no offence; I know it is no fault of your worship.” “It is but a slight boon, after all,” said the sheriff, “and one which may be conceded;” and as he spoke he wrote a few lines on a slip of
  • 66. parchment. “They will give you admission for half-an-hour, if you show them this at the gateway.” “May I not stay longer?” “It would not be kind to those who are to die; they need their time to make their peace with God.” “That is already made, your worship.” “I trust so,” said the sheriff, with a sad faint smile at the boy’s earnestness. “Who art thou, my lad?” he said. “The Abbot’s adopted son.” “But who were your real parents?” “I know not.” “What name do they call you?” “Cuthbert, I have none other.” “Poor lad,” said the sheriff, as the boy departed, “it seems almost like a familiar face, yet I have never met him before; some accidental likeness, I suppose.” FOOTNOTES [17] Lingard v. 19. [18] This terrible sentence is copied from the form in actual use until the present century.
  • 67. CHAPTER VII. GLASTONBURY TOR. dead silence reigned around the precincts of the once mighty Abbey, many of the monks had fled, fearing lest they should share the fate which had befallen their superiors, and having no decided predilection for martyrdom; but many still shuddered in their cells, or wandered aimlessly about the doomed cloisters, so soon to be a refuge for bats and owls. Only a few lights burned here and there in the darkness of that November night, but one shone steadily from the window of the strong room over the gatehouse, where the three fated monks awaited their doom. Scantily furnished was that chamber; three wooden chairs with high backs grotesquely carved, a massive table in the centre, a huge hearth decorated with the Abbey arms, upon which smouldered two or three logs, for fuel was cheap, and the night was cold and damp. Against the wall hung a crucifix, and there, with their faces towards the memorial of the martyrdom which redeemed a world, knelt the three. We cannot follow their mental struggles, which found relief in prayer—in intense prayer, in burning words of supplication, which
  • 68. wafted their spirits on high, and gave them strength to say “not my will but Thine be done.” A step on the stairs, but they rose not from their knees; they felt that one had entered and was kneeling behind them, and at length they heard sobs escape from their visitor, which he could not repress. They rose slowly from their devotions, and the Abbot grasped Cuthbert’s hands and raised him from the floor. “My child,” he said, “dost thou grieve for me?” A sob was the only answer. “Listen, my child, which is best, heaven or earth, Paradise or Glastonbury?” Still no answer. “And they but rob us of a few brief years, which to aged men like us must be years of suffering; they separate us from the ranks of the Church Militant, but not from those of the Church Triumphant, that is beyond their power; they may kill the body, but after that they have no more that they can do.” “But the shame, the disgrace!” “Is it greater than the Son of God bore on Calvary? Nay, my son, let us not grieve that it has pleased Him, of Whom are all things, to ordain this painful road, which He Himself has trodden before us; nay, sob not, nor sorrow as those without hope, but live so that thou mayest rejoin us in the regions of Paradise.” Cuthbert gazed upon the calm majestic face of the old man, and it seemed to him irradiated by a light from above. He repressed his grief, and listened to the last words of his friend. “It is written that in the last days perilous times shall come, and we have fallen upon them; happy then that God removes us to His secret chambers, where He shall hide us until the iniquity of a world be overpast, and His redeemed come with triumph to Zion. Before
  • 69. us now is the via Dolorosa of a brief hour, but from the gibbet we shall scale the skies. For thee, my son, is the life-time of trial and temptation, wherefore I pray for thee, and will pray for thee when thou shall see my face no more. Remember, dear child, he that endureth to the end, the same shall be saved, and let neither men nor devils rob thee of thy crown.” “By God’s help I will endure.” “I believe that thou wilt strive, yea, and prevail. But one more thought to earthly things, and I resign the world for ever. Thou rememberest the secret chamber?” “I do, Father.” “And the ring which is now on the finger of him who shall claim thy promise?” “Well, my Father.” “Await him, my son, in Glastonbury, not in the Abbey, that will be destroyed by wicked hands, but in the house of thy foster father, Giles Hodge, whose name thou must take, and be content to pass as his foster son till the time comes, and thy services are claimed. He who bears the ring will provide for thy future.” “Oh, think not of that.” “I have thought of it, and now, my child, thou mayest again join us in prayer.” “The half-hour has passed,” said a rough voice at the door. “Thy blessing, Father.” “It is thine, my child: Benedicat et custodiat te Deus omnipotens, Pater, Filius, et Spiritus Sanctus, nunc et in sæcula sæculorum.”
  • 70. Upon the summit of the hill men are working all through the storms of the night, erecting a huge gibbet, from the cross-beam of which three ropes are now dependent; beneath is a huge block, like a butcher’s block, and a ghastly cleaver and saw rest upon it; hard by stands a caldron of pitch, which but awaits the kindling match to boil and bubble. Through the dark shadows of the clouds, or in the bright light of the moon when the winds open a path for her rays, ghostly figures flit about. It is well that they should work in darkness,—it were better that such work were not done at all. Thus they execute the will of the ruthless Tudor, the Nero of English history; well, he and his victims have long since met before a more awful bar. The winds blow ceaselessly all through the night, but in the morn the clouds are breaking; in the east a faint roseate light appears, and soon brighter streaks of crimson fringe the clouds, which hang over the dawn; anon the monarch of day arises in his strength, the shadows flee away, and from the summit of the hill a vast extent of sea and land is beheld, rejoicing in his beams. A crowd gathers around the gatehouse, some few royal parasites to jeer, men at arms to guard the prisoners, and prevent any attempt at rescue, more sad and tearful faces of women, or sternly indignant visages of bearded men. “Here they come.” The trampling of horse, a train of strong wooden hurdles, each drawn by a single horse, appears; hard carriages these on which to take the ride to eternity, but many an innocent victim has fared no better. The doors are opened, and the Abbot appears first: a blush overspreads his aged cheeks, as the indignity thus palpably presents itself, but uttering, “And this, too, I offer to Thee,” he lies down upon the hurdle, and they bind his hands and feet to the crossbars, carefully, that they may not touch the ground, for those in charge of
  • 71. the execution would not willingly offer additional pain—some of them are sick at heart as they fulfil the will of the tyrant Tudor. The Prior and Sub-Prior submit to the same painful restraint, and the via Dolorosa is entered. All through the streets of the town, where the Abbot has often ridden in triumphant processions, the highest in dignity of all far and wide, the hurdles jolt along: the aged frames of the sufferers are fearfully shaken by the rude joltings, but they remember that via Dolorosa which led to Calvary, and accept the pain for the sake of the Divine Sufferer, in Whom our sufferings are sanctified. There are those present who are paid to raise hisses and hootings, and to revile the passing victims, but they are awed by the attitude of the spectators in general, and forfeit their wages. Up the hill with labouring steps the horses tread: at length the rounded summit appears, and the gibbet looms in sight. The sufferers see it not, owing to their prostrate condition, until they are beneath it. “It is easier to bear than the cross, brethren,” says Abbot Richard. The victims are unbound from the hurdles, and one after the other resigns himself to the rude hands of the executioners; for now, under this reign of terror and bloodshed, ecclesiastics are led forth in their habits to die without being first stripped of their robes, and degraded. There is a meaning in this, it is not of mercy.[19] The Abbot yields himself first, calmly reciting the words of the 31st Psalm, “In manus tuas, Domine, commendo Spiritum meum.” The two pray for him until their own turn comes. “Go forth, O Christian soul, from this world, in the Name of God the Father Who created thee, of God the Son, Who redeemed thee, of God the Holy Ghost Who hath sanctified thee; may thy place be this day in peace, and thine abode in Mount Sion.” Their faces did not grow pale, neither did their voices tremble— they declared as they died that they were true subjects of the king
  • 72. in all things lawful, and obedient children of Holy Church. So one after the other they suffered—we spare the reader the sickening details, which Englishmen could look on in those days, and which innocent men were called upon to suffer, but which we shudder even to read. But we will conclude with a letter written by Lord Russell to Cromwell on the 16th of November, being the day following the tragedy.
  • 73. “My Lorde—thies shal be to asserteyne, that on Thursday the xiii. daye of this present moneth, the Abbot was arrayned, and the next daye putt to execution, with ii. other of his monkes, for the robbyng of Glastonburye Churche; on the Torre Hill, the seyde Abbottes body beyng devyded in fower partes, and his heedd stryken off, whereof oone quarter stondyth at Welles, another at Bathe, and at Ylchester and Brigewater the rest, and his hedd upon the abbey gate at Glaston.”[20] As the traveller, in modern times, passes swiftly along the Great Western line between Weston and Bridgewater, he may see, on his left, a round conical hill, rising abruptly from the flat plain, a plain which was once a sea, a hill which was once an island. This is Glastonbury Tor. Fair and beautiful it looks in the summer sunlight, but it was once the scene of the foul judicial murder which we have endeavoured to describe.[21] FOOTNOTES [19] “While he was waiting for the hangman, he was questioned again by Pollard as to the concealment of plate, but he had nothing more to say, and would accuse neither himself nor others, but thereupon took his death very patiently.”—Blunt. [20] This letter is authentic, spelling and all. [21] See Note G. Death of Abbot Whiting.
  • 74. CHAPTER VIII. ON THE TRACK. “We grieve not o’er our abbey lands, e’en pass they as they may, But we grieve because the tyrant found a richer spoil than they; He cast aside, as a thing defiled, the remembrance of the just, And the bones of saints and martyrs he scattered to the dust.” Neale. t was in vain that Bishop Latimer besought the tyrant, mad after the spoils which a venal parliament had given him, to let at least some of the monasteries remain as the houses of learning. Few countries could boast of such shrines as those which adorned like jewels the shires of England—but all were ruthlessly sacrificed, from the fane which rose over the mighty dead at Battle, to the humblest cell which but sheltered half-a-dozen poor brethren or sisters. Such was the value of the noble library at Glastonbury that Leland, an old English antiquarian, tells us, when first he beheld it, “The sight of its vast treasures of antiquity so struck me with awe, that I hesitated to enter.” Yet we learn from Bale, that such noble collections were sold to grocers for waste paper, and that he knew a man who had bought for that purpose two large monastic libraries at the dissolution, and added that he had been using their contents for ten years, and had hardly got through half his store.
  • 75. So strongly built were many of the Abbeys, that they had to be blown up with gunpowder, after they were stripped of all that could be sold; the lands were given to greedy favourites, Cromwell himself is said to have secured thirty Abbeys, and the ready money was spent at court in gambling and dissolute living. So, in a few years, all the wealth which flowed into the hands of the crown was dissipated, and instead of the remission of taxation, by the hope of which many had been bribed to assent to the fall of the monasteries, the burdens laid upon the people were heavier than before. Four months had passed away since the tragical events recorded in our last chapter, and the blustering month of March was in mid- career; the winds swept over the ruined Abbey, now in great part roofless, and dismantled, the abode of bats and owls; they swept over the bare and rounded summit of Glastonbury Tor, stained so lately by a foul deed of blood. Many a violent storm of rain had beaten upon that blood-stained summit, and the traces of the butchery had long since vanished; but the peasants yet gazed up to the hill top with awe and wonder. But the storm which had desolated the proud Abbey had left the humble cottage of Giles Hodge untouched: there the old man and his wife lived in peace, like their neighbours, and went through their daily round, their trivial task— Each morning saw some work begun Each evening saw its close. Their foster son was often present to their remembrances, but he had not been with them in person since the martyrdom. They had wisely judged it best to remove him from the immediate neighbourhood of such harrowing recollections, and as old Giles had
  • 76. a brother who lived at Lyme Regis, a seafaring man, thither he had sent Cuthbert to spend the winter. The change of scene had wrought good. The poor boy had gone there broken-hearted, and suffering from the nervous excitement which he had passed through; the shock had been very great, but youth is elastic, and soon recovers from such a strain. The sea and its wonders, the romantic scenery around, all contributed to the beneficial change. Sometimes Cuthbert would go out fishing with his uncle, as he had learned to call the brother of his foster father; the fishing awakened all his interest: on the deep all the night, watching the moonbeams on the waves, the gradual breaking of the dawn, the “many dimpled smile of ocean:” all this was new to the land- bred youth, and exercised a most happy effect upon his health and spirits. But it must not be supposed that he forgot the Abbot, or that he was unmindful of the secret entrusted to him; he had told his foster father that he expected some communication from the friends of the late Abbot, and old Hodge had promised that if anyone arrived, and presented the ring which was to serve as a token, he would send for Cuthbert without any delay. And at last the message came, just when Cuthbert returned home with his “uncle,” after a most successful night at sea, bringing the scaly spoils of the deep in their boats. A rustic messenger had ridden across the country from Glastonbury, through Langport, Ilminster, Chard, and Axminster, a distance of from thirty to forty miles. Old Giles could not write, he only sent word by his envoy, “Come home, I have seen the ring, he expects thee to-morrow.” We have not hitherto explained fully the social position of Giles Hodge. Well, he was a yeoman, having no lands of his own; only he had a farm of three or four pounds a year,[22] and hereupon he tilled
  • 77. as much as kept five or six men. He had walk for a hundred sheep, and his wife milked thirty kine. He was able and bound to provide one man and horse, with “harness” for both, when the king had need of him; for this species of feudal tenure yet lingered, and supplied the want of a standing army. In short, he was an English yeoman, “all of the olden time.” The fire was burning brightly on the hearth in old Giles’ cottage, which looked as pleasant as in days of yore; he and his old dame occupied their chairs on either side, for the day’s work was over, and they were resting after its fatigues, whilst they anxiously awaited the arrival of their foster son, their Cuthbert. It was only just dark, not yet seven o’clock; the evening meal was already prepared, and set forth with many a tempting dish upon a comely white cloth, to tempt the appetite of the darling of their old age. A knock at the door—the hearts of the old couple beat with anticipation—yet the knock! Would Cuthbert stop to knock? “Come in,” they cried. The latch lifted, and their parish priest entered, Doctor Adam Tonstal. “Good even to you, my worthy friends; I have come for a chat with you about a matter of importance.” “Nothing amiss about Cuthbert, I hope,” said the old dame, anxiously. “No, there is naught amiss, yet still my errand is about him. Are you not expecting him home?” “Yes, thank God, this very night; we thought when you knocked that it was he.” “Well, I know you will be glad to see him again, for he is a worthy lad, and there are few who have not a good word for him, but it will be just as well not to let anyone know of his arrival, and to get him away again as soon as possible. My object was to warn you against
  • 78. allowing him to return, and also to advise you not to tell anyone where he may be found.” “But why,” inquired Giles, aghast, as soon as he could get a word in; “what harm hath the poor lad done?” “Harm, forsooth!” then lowering his voice, “what harm had Richard Whiting done?” “But Cuthbert is too young to be answerable for such weighty matters.” “I know that, but not too young to be an object of interest just now. You see it is reported that he was deep in the Abbot’s secrets.” “They would indeed be weighty secrets, which the Abbot would entrust to a mere boy.” “Ordinarily your remarks would be just, but the case is peculiar. The Abbot was suspected to be in possession of lists of names, of papers, nay of treasure, in connection with the rising in the north, which had been entrusted to him after the disastrous collapse of the Pilgrimage of Grace: we are all friends here,” added the priest, fearing lest he might have committed himself, for had such an expression as “disastrous,” applied to the royal triumph, been reported to Cromwell, it might have been his death-warrant.[23] “We are alone, my wife and I, and we be no tale-bearers.” “Well then, it is said that there must be a secret chamber, somewhere in the Abbey, not yet discovered, in spite of all the search made for it by Sir John Redfyrne, the administrator of the property of the Abbey for the king; who is also an ally of Cromwell, that arch-heretic, and oppressor of the Church. You are sure there is no one in the house save yourselves?” “Quite sure, don’t fear; but what has this to do with Cuthbert?” “Only that a lad named Nicholas Grabber offers to make oath that he heard the Abbot reveal the secret to Cuthbert, when the two were in his private chamber, and bid him await the arrival of some
  • 79. mysterious person, with a ring: Grabber’s account is very defective, but he says the Abbot discovered his presence, and ordered him roughly away.” “As I live,”—said Giles. “Of course you know nothing,” said the priest, interrupting, “but I have learned through friends that a warrant is about to be issued against the lad: now if he is taken——” “But they can lay no crime to his charge, to know a secret is no crime.” “But they may, and probably will consider that secret of sufficient importance to the State to insist upon its disclosure, and if the poor boy, as will very likely be the case, refuse to tell, they will see what the thumb-screw, or failing that, even the rack, may effect.” “Good heavens! Saint Joseph forbid.” “Amen; but the best way is to keep Cuthbert out of the way.” “Too late; for here he is!” The door opened and our hero entered, all flushed with travel, and with the delight of meeting his old friends, whom he embraced warmly; after which he saluted the priest with a lowly reverence. “How well he is looking, poor lad,” said the dame: for his face was flushed with pleasure, or she might still have seen some traces of his recent trial. A more thoughtful expression sat on his features, such a period as he had gone through had done the work of years in sobering his boyish spirits, and bringing on, prematurely, the thoughts and cares of manhood. “Now, Cuthbert,” said the good priest, “I will take a turn on the green, while you tell all your news to your kind friends, and satisfy your hunger, and after that I will return for a little talk with you;” and he went out, but only to pace up and down the green, keeping the cottage still in sight.
  • 80. And we too will leave the good souls within to their endearments for the same space of time; they will soon know the extent of the danger in which their foster boy is placed. But the priest knows it, and he walks up and down, peering sometimes into the darkness beyond the green, in the direction of the town, scrutinizing the faces of the passers-by, until curfew rings from the tower of his own church. Then he re-enters the cottage. Cuthbert, hunger satisfied, is seated in the chimney-corner; the logs sparkle in the draughts of wind, which find their entrance through every cranny; the aged couple are seated as before. “Father, we have told Cuthbert that you think he ought not to stay here, but he says he is bound to remain over the morrow; that will not hurt, will it?” “Not if he is unseen, and the news of his coming has not got abroad.” “Did anyone see thee, child, as thou enteredst the town?” “Alas, I fear one did; Nicholas Grabber was hanging about the gate on the common.” “Nicholas Grabber; then, my boy, thou must not tarry an hour; it is he who hast already betrayed thee.” “Betrayed me! how?” said Cuthbert, alarmed. Then the priest told Cuthbert all that our readers have already learned from his lips, and the lad at once recognized his danger, for he remembered how Nicholas had lurked about the Abbot’s chamber that eventful night, when the secret was revealed to him. “You are right, Father,” he said, “I must go.” “Too late!” said the priest, “too late!” For at that moment the tramp of many feet was heard without, followed by a violent knocking at the door, which the priest fortunately had barred when he entered.
  • 81. “Hide him,” said the good man; “I will keep them at bay for a few minutes.” And the old people hurried Cuthbert out of the room. “The back door,” said the boy. “Nay, that is watched too; I hear them whispering without.” “Then I am lost.” “No! no! my boy,” said the old woman, “come up stairs, and get into the loft.” They went hastily up the stairs, into the old people’s bedroom. There was no ceiling, but that which plain boards overhead, separating them from the attic beneath the roof, afforded; knocking one of these aside with his staff, the old man bade Cuthbert mount on his shoulders, and get into the loft. The lad did so easily, for the roof of the room was low, and then replaced the boards, so that no one could see that there had been any disturbance thereof. The loft was often used for the storage of fruit, corn, flax, and the like, and there was a quantity of the latter material stored therein; on this Cuthbert lay. Meanwhile the priest below fulfilled his task. “Who are ye, disturbing an honest family after curfew?” “Officers of the law, constables; open, in the name of the law.” “There be many who avail themselves of that name, with very little title; robbers be about, and I must have surer warrant ere I admit you.” “Open, or we will break down the door.” “Nay, and thou come to that game, there be those within, good at the game of quarter staff; meanwhile we will blow the horn and rouse the watch.”
  • 82. “Thou old fool, we will break thy bones, as well as the door; we tell thee we are the constables—the watch.” “’Tisn’t old Hodge’s voice,” said another; “ask the fellow who he is.” “Who art thou, fool?” “That is for wise men like thee to find out.” “Well, then, here are Roger Hancock, John Sprygs, James Griggs, Denis Howlet, the four constables, and Laurence Craveall, a body servant of Sir John Redfyrne.” “I fear me, friend, thou art taking the names of better men in vain; more to the token, thou showest thyself a liar: for well do I know that neither Jack Sprygs nor Jim Griggs ever leave the ale-tap after curfew, until it is time to tumble, drunk, into their sinful beds.” “Break open the doors,” cried the two impugned worthies, in a rage. “I will loose the mastiff upon you.” But in spite of this direful threat, which it would have been difficult to fulfil, as no mastiff was in the house, the men commenced breaking down the door. At that instant old Hodge appeared, and signifying by a sign all was right, cried aloud— “What are you doing at my door?” “Breaking it down, with a search warrant for our justification.” “Thou mayst save thyself the trouble; I have nought here to hide;” and the old man withdrew the bars. Four ill-looking men, Jacks in office, entered, and behind them two faces appeared, whose owners preferred to stay without; the one was the valet of Sir John Redfyrne, the other Nicholas Grabber. The two constables whom he had so grievously aspersed fixed their eyes upon the priest.
  • 83. “So it was thou, was it, who kept us waiting?” “Your pardon, if I mistook you; doubtless you have good cause for your untimely errand.” “We have pulled down monks, and your turn may come next,” said the surly John Sprygs, “and then you may not have the chance of taking sober folks’ reputation away; but enough of this, where is that young rascal, Cuthbert Hodge, if that is his name, we have a warrant for his apprehension?” “Why, he has been away ever since November.” “But came home to-night; here is the witness. Nick Grabber, when didst thou last see Cuthbert Hodge?” “This evening, riding with another lad through the common gate, on the Langport Road.” “And does thy worshipful father permit thee, now thy school days are over, to spend thy time in Glastonbury as a spy?” said old Hodge. “My worshipful father has given me to the care of Sir John Redfyrne, as a page, old man, so thou hadst better keep a civil tongue in thine head, and it will be better for thy young bastard’s bones; he shall pay for it.” “I think, my son,” said the priest very quietly, “that when thou wast coupled between two hounds, as a truant, thou must have learnt from them to bite and snarl.” “We have no time for all this nonsense,” said the head constable, “where is this youngster?” “Since you say he is here, you had better find him.” “He has not gone out by the back door,” said Grabber. “Or you would have grabbed him.” “Even so, with right good will.” They proceeded to search the house, but all in vain, and they were at length about to conclude that the boy had left the place
  • 84. before their entrance, when Grabber remarked to one of the constables, that he might be above the boards of the bedroom. “When we were schoolfellows,” he said, “I have often heard him say that very good apples were kept there.” “The boy has got the right sow by the ear,” says James Griggs, and followed by the others, he went upstairs again, whereupon the old lady began to cry. “Ah,” said Nicholas, “the scent is hot, the old lady gives tongue.” A board was withdrawn, chests piled beneath, and John Sprygs cried out, “Now, young Nick, you go and grab him.” “After you,” said Nicholas, who remembered the weight of his young opponent’s fist that night in the woods. John Sprygs mounted, and was no sooner in the loft than he cried,— “The place is as dark as pitch, pass me up the torch.” “Nay! nay!” cried Giles Hodge, “the place is full of flax.” “We will take care of that; thou dost not want thy precious brat found.” Up went the torch which the men had brought with them, a flaring pine torch, to assist in the operations; in very wantonness Nick Grabber tossed it into the fellow’s hand, crying “Catch.” He missed it, and it fell into a heap of flax. The man started back to avoid the blaze which instantly sprang up, and so put the fire between him and the moveable planks—the only moveable ones—which served as a trap-door. “Come down, come down,” called out the appalled voices below. But the wretch could not face that sea of flame, until, maddened by desperation, he took a header as boys might say, at the opening through the fire, and falling head foremost on the bedroom floor, split his skull and died on the spot. The others could do nothing for him, the loft was one mass of flame, and shouting “Fire! Fire!” they
  • 85. ran to get water, in a vain attempt to save the cottage. But of this there was little hope; the roof was of thatch, and the building mainly of timber, so they saw in a few minutes that there was nothing for it but to help the aged couple to save their furniture. But what of Cuthbert? they had forgotten him, for the time, then they said,— “The boy couldn’t have been there, nor in the house, or he would be driven from his hiding-place now. See how unconcerned the old man looks; he wouldn’t look so if his precious boy were in danger.” FOOTNOTES [22] Multiply by twelve for the modern equivalent. See Note H. [23] A priest of Chichester, named Christopherson, suffered death for saying that the king would be damned for the destruction of the monasteries.
  • 86. CHAPTER IX. IN THE RUINS OF THE ABBEY. o, Cuthbert was not burnt, as the reader has already conjectured, or our tale would come to an untimely close, untimely as the death of our hero, and we will now explain the manner of his escape. Once in the loft, he remembered that in the innocent confidence of his boyhood, he had prated of its treasures to Grabber, who he doubted not was with his pursuers, and he felt that there was scant safety in his hiding place. But there was yet an avenue of escape: a little opening at the end of the loft, which the ill-fated constable had overlooked, like a dormer window, admitted light and air to the loft; if he could force himself through that, and it was only a very small opening, he would emerge on the roof, and in the darkness might descend and escape unseen. He tried and succeeded, and sliding down the long sloping roof, as he had often done when a small boy, alighted at the back of the house, while all the officers were within, those who had kept guard without, having joined the rest, when they judged by the uproar, that the lad was found. But one yet watched there,—the priest who rejoiced to see him. He had left the house when Grabber told the secret, from reluctance to witness the capture of the harmless boy. “Thank God, my boy,” he said, “thou hast outwitted them; go and hide in the Abbey ruins, I shall be there at midnight, I have business there, in the desecrated church; I will tell thy friends thou art safe; go at once.” The boy darted away for the Abbey, but soon he heard loud shouts of “Fire!” “Fire!” and saw the reflection of the flames in objects around. Full of anxiety for his foster parents, he could not
  • 87. help turning back, and would again have run into danger, for the officers, anticipating such a result, were looking everywhere amongst the crowd, and would surely have seen him, had not his wise friend, the good parish priest, also anticipated the same, and met him. “Nay, nay, my lad, thou canst do no good, and wilt only add to their troubles; go into the Abbey church and wait there till midnight; thou art not afraid?” “No,” said Cuthbert, “only take care of them,” and he retraced his steps to the Abbey.
  • 88. “The Boy darted away for the Abbey.” Page 92. The moon had arisen, and illuminated the scene, when through a gap in the boundary wall Cuthbert entered the once sacred precincts; his heart was very heavy as he gazed upon the mutilated cloisters, doors torn from their hinges, windows dashed out, roofless chambers from which the lead had been torn,—gazed as well as a
  • 89. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com