100% found this document useful (1 vote)
12 views

JavaScript for Sound Artists; Learn to Code with the Web Audio API William Turner & Steve Leonard - Quickly download the ebook to never miss important content

The document promotes the ebook 'JavaScript for Sound Artists: Learn to Code with the Web Audio API' by William Turner and Steve Leonard, which teaches programming through audio applications. It highlights the book's unique approach to learning JavaScript for the creative audio community and includes downloadable code examples. Additionally, it lists various other ebooks available for instant download on the same platform.

Uploaded by

lakuatmen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
12 views

JavaScript for Sound Artists; Learn to Code with the Web Audio API William Turner & Steve Leonard - Quickly download the ebook to never miss important content

The document promotes the ebook 'JavaScript for Sound Artists: Learn to Code with the Web Audio API' by William Turner and Steve Leonard, which teaches programming through audio applications. It highlights the book's unique approach to learning JavaScript for the creative audio community and includes downloadable code examples. Additionally, it lists various other ebooks available for instant download on the same platform.

Uploaded by

lakuatmen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

Read Anytime Anywhere Easy Ebook Downloads at ebookmeta.

com

JavaScript for Sound Artists; Learn to Code with


the Web Audio API William Turner & Steve Leonard

https://ebookmeta.com/product/javascript-for-sound-artists-
learn-to-code-with-the-web-audio-api-william-turner-steve-
leonard/

OR CLICK HERE

DOWLOAD EBOOK

Visit and Get More Ebook Downloads Instantly at https://ebookmeta.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Modern Web Development with Deno Develop Modern JavaScript


and TypeScript Code with Svelte React and GraphQL 1st
Edition Mayur Borse
https://ebookmeta.com/product/modern-web-development-with-deno-
develop-modern-javascript-and-typescript-code-with-svelte-react-and-
graphql-1st-edition-mayur-borse/
ebookmeta.com

Imagine A Vision for Christians in the Arts Steve Turner

https://ebookmeta.com/product/imagine-a-vision-for-christians-in-the-
arts-steve-turner/

ebookmeta.com

Web API Development for the Absolute Beginner 1st Edition


Irina Dominte

https://ebookmeta.com/product/web-api-development-for-the-absolute-
beginner-1st-edition-irina-dominte/

ebookmeta.com

Black Swan 1st Edition Kel Carpenter Aurelia Jane

https://ebookmeta.com/product/black-swan-1st-edition-kel-carpenter-
aurelia-jane/

ebookmeta.com
Pricing A Guide to Pricing Decisions Ragnhild Silkoset

https://ebookmeta.com/product/pricing-a-guide-to-pricing-decisions-
ragnhild-silkoset/

ebookmeta.com

Why Budgets Matter Budget Policy and American Politics


Revised and Updated Edition Dennis S. Ippolito

https://ebookmeta.com/product/why-budgets-matter-budget-policy-and-
american-politics-revised-and-updated-edition-dennis-s-ippolito-2/

ebookmeta.com

The Latte Factor Why You Don t Have to Be Rich to Live


Rich Bach David Mann John David

https://ebookmeta.com/product/the-latte-factor-why-you-don-t-have-to-
be-rich-to-live-rich-bach-david-mann-john-david/

ebookmeta.com

The Complete Guide to Blender Graphics: Computer Modeling


and Animation: Volume1 9th Edition John M. Blain

https://ebookmeta.com/product/the-complete-guide-to-blender-graphics-
computer-modeling-and-animation-volume1-9th-edition-john-m-blain/

ebookmeta.com

Data Science Careers Training and Hiring A Comprehensive


Guide to the Data Ecosystem How to Build a Successful Data
Science Career Program or Unit Renata Rawlings-Goss
https://ebookmeta.com/product/data-science-careers-training-and-
hiring-a-comprehensive-guide-to-the-data-ecosystem-how-to-build-a-
successful-data-science-career-program-or-unit-renata-rawlings-goss/
ebookmeta.com
Four Corners Level 3 Student s Book with Online Self Study
2nd Edition Jack C. Richards

https://ebookmeta.com/product/four-corners-level-3-student-s-book-
with-online-self-study-2nd-edition-jack-c-richards/

ebookmeta.com
JavaScript for
Sound Artists
Learn how to program JavaScript while creating interactive audio applications with
JavaScript for Sound Artists: Learn to Code with the Web Audio API! William Turner and
Steve Leonard showcase the basics of JavaScript language programming so that read-
ers can learn how to build browser-based audio ­applications such as music synthesiz-
ers and drum machines. The companion website offers further opportunity for growth.
Web Audio API instruction includes oscillators, audio file loading and playback, basic
audio manipulation, panning, and time. This book encompasses all of the basic features
of JavaScript with aspects of the Web Audio API to heighten the capability of any browser.

Key Features

◾◾ Uses the readers’ existing knowledge of audio technology to facilitate learning


how to program using JavaScript. The teaching will be done through a series of
annotated examples and explanations.

◾◾ Downloadable code examples and links to additional reference material included


on the book’s companion website.

◾◾ This book makes learning programming more approachable to nonprofessional


programmers.

The context of teaching JavaScript for the creative audio community in this manner does not
exist anywhere else in the market and uses example-based teaching.
William Turner is a technical trainer with over 13 years of experience. He currently oper-
ates a boutique web development and training company at helpknow.com.
Steve Leonard is a technical writer for Juniper Networks and developed some of the ini-
tial documentation for the Cisco Nexus 7000 Series of switches among other products.
He now writes the internal programmer guide for developers of Juniper’s next-generation
operating system and is responsible for the network management documentation for end
users of that new OS.
JavaScript for
Sound Artists
Learn to Code with the Web Audio API
2nd Edition

Authored by: William Turner


Edited by: Steve Leonard
Second Edition published 2023
by CRC Press
6000 Broken Sound Parkway NW, Suite 300, Boca Raton, FL 33487-2742

and by CRC Press


4 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN

CRC Press is an imprint of Taylor & Francis Group, LLC

© 2023 Taylor & Francis Group, LLC


First Edition published by CRC Press 2017

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, access www.copyright.
com or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA
01923, 978-750-8400. For works that are not available on CCC please contact mpkbookspermis-
[email protected]

Trademark notice: Product or corporate names may be trademarks or registered trademarks and are
used only for identification and explanation without intent to infringe.

ISBN: 978-1-032-06273-0 (hbk)


ISBN: 978-1-032-06272-3 (pbk)
ISBN: 978-1-003-20149-6 (ebk)

DOI: 10.1201/9781003201496

Typeset in MinionPro
by codeMantra

Access the Support Material: https://www.routledge.com/9781032062723


This book is dedicated to the loving memory
of my mother, Bonnie Turner.

I want to thank the Littlejohn/Craft family. Maureen, you’ve


been like a second mother and I don’t know what I’d do
without you. Gabe, you’re going to be a great father!

I also want to thank Earl Jenkins, Steve Leonard,


and Meilin Obinata for caring enough to listen
when I needed someone to talk to. I love you all!

William Turner
Contents

Preface xvii

What Is a Program? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1
What Is JavaScript? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1
HTML, CSS, and JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2
What Is a Web Application? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3
What Is the Web Audio API? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3
Setting Up Your Work Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4
How to View in Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6
How to Create Code Snippets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6
Accessing the Developer Tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7
Troubleshooting Problems and Getting Help . . . . . . . . . . . . . . . . . . . . . . . . . .7

Hello Sound Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9


Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11
Null. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14

vii
Documenting Your Code with Comments . . . . . . . . . . . . . . . . . . . . . . . . . . .14
Exploring Variables with an Oscillator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14
console.log() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15
String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .16
Built in String Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17
The Length Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19
Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19
How to Determine the Data Type of a Variable?. . . . . . . . . . . . . . . . . . . . . . .20
Examples of Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20
Number to String Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .22
BigInt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23
Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .25

What Are Operators?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .27


Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28
Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28
Addition Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28
Subtraction Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29
Multiplication Assignment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29
Division Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29
Modulo Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29
The Boolean Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .30
Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .30
Equality Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .30
Strict Equality Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .31
Greater Than and Less Than Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .31
Greater Than or Equal To Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .31
Less Than or Equal To Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .32
Not Equal To Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .32
Strict Not Equal To Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .32
Logical Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .32
The Logical AND Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .33
The Logical OR Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .33
The NOT Operator. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .33
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .34

Conditional Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .35


The If Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .36
The Switch Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .37
Ternary Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .38
Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .39

viii Contents
For Loops. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .39
Using For Loops with Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .40
While Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .41
When to Use for Loops and When to Use While Loops . . . . . . . . . . . . . . . .42
Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .42
Block Scoped Variables Using Let and Const . . . . . . . . . . . . . . . . . . . . . . . . .42
Non-Block Scoped Variables Using Var . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .43
Local and Higher Scope Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .43
Hoisting and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .44
Hoisting with Let and Const . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .45
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .45

Functions—A Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .47


Parts of a Function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .48
Function Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49
Abstracting Oscillator Playback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .50
A Working Effects Box Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .50
Default Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .51
The Arguments Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .51
Rest Parameter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .52
Function Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .52
Why You Should Always Declare Your Variables . . . . . . . . . . . . . . . . . . . . .54
Hoisting and Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .54
Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .55
Closures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .56
What Is a Closure? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .56
Callback Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .59
Working with JavaScript’s Built-In Callback Functions . . . . . . . . . . . . . . . .60
filter() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .60
map() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .61
Function Arrow Syntax. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .61
Recursion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .63
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .63

JavaScript Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .65


Looping through Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .67
When to Use Objects Rather than Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . .68
How to Check If an Object Has Access to a Particular Property or
Method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .68
Cloning Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .69
Prototypal Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .70
Object.creates Nested Object Gotcha . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .70

Contents ix
The “this” Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .72
The bind Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .72
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

The AudioContext() Method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .75


Node Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .76
Oscillators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .76
The stop Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .77
The onended Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .77
How to Stop Oscillators and Restart Them . . . . . . . . . . . . . . . . . . . . . . . . . . .77
The type Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .78
The frequency Property. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .79
The detune Property. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .79
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .80

What Is a User Interface? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .81


HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .81
Explanation of the HTML Template. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .82
Understanding HTML Elements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .83
Form and Input Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .86
CSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .87
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .90
Element Selectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .90
Grouping Selectors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .90
Descendent Selectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .90
Child Selectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .91
class and id . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .91
Modifying the App Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .91
Margin, Border, and Padding. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .95
Removing List Element Bullet Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .96
Font Size, Style (Type), and Color . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .97
Centering Block-Level Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .98
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .102

How Does JavaScript Communicate with the DOM? . . . . . . . . . . . . . . . . .103


HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .103
JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .104
Building the Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .105
How to Trigger an Oscillator by Clicking a Button . . . . . . . . . . . . . . . . . . .105
Toggling the Start/Stop Text. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .106

x Contents
Programming the Frequency Slider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .108
Changing the Frequency in Real Time. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .109
Changing Waveform Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Completed Code with Waveform Selection. . . . . . . . . . . . . . . . . . . . . . . . . .112
Giving an Outline to the Selected Waveform Type . . . . . . . . . . . . . . . . . . .113
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114

What is JQuery? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .115


JQuery Setup. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .115
Referencing JQuery Directly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Using JQuery from a CDN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
How to Use JQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Selecting HTML Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Storing DOM Selectors as Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Using Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
JQuery/JavaScript to Change a Single Property. . . . . . . . . . . . . . . . . . . . 118
JQuery/JavaScript to Change Multiple Properties. . . . . . . . . . . . . . . . . . 118
Method Chaining. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119
HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119
CSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119
JQuery/JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119
HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119
JQuery/JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120
The this Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120
HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120
JQuery/JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120
Refactoring the Oscillator Player to Use JQuery. . . . . . . . . . . . . . . . . . . . . .120
Without JQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .121
With JQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .121
Setting Up the Event Listener for the User-Selected List Element . . . . . . .122
Event Listener without JQuery. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .122
Event Listener with JQuery. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .123
Modifying the Code in setInterval . . . . . . . . . . . . . . . . . . . . . . . . . . . .123
setInterval Method without JQuery. . . . . . . . . . . . . . . . . . . . . . . . . . . .123
setInterval Method with JQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .124
onOff Method without JQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .124
$onOff Selector with JQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .125
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .125

Contents xi
The Two Steps to Loading an Audio File . . . . . . . . . . . . . . . . . . . . . . . . . . . .128
Loading an Audio File with the XMLHttpRequest Object . . . . . . . . . . . . .128
get Requests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .130
A Word on Audio File Type Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . .130
Synchronous versus Asynchronous Code Execution. . . . . . . . . . . . . . . . . .130
Playing the Audio Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .132
Processing the Audio Buffer with the Node Graph . . . . . . . . . . . . . . . . . . .132
Loading Audio Files Using the Fetch API . . . . . . . . . . . . . . . . . . . . . . . . . . .133
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .134

xii Contents
Some Effects Require Development Work . . . . . . . . . . . . . . . . . . . . . . . . . . .159
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .160

Contents xiii
xiv Contents
CSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .221
Adding Interactivity to the Grid Elements . . . . . . . . . . . . . . . . . . . . . . . . . .223
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .225

Index 251

Contents xv
Preface

Learning to program can be daunting, and we want to be the first to congratu-


late 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 program-
ming books directed toward artists to help them build websites, mobile applica-
tions, 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

xvii
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 connec-
tions 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 con-
nections; 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.

xviii Preface
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

Preface xix
1 Overview
and Setup

What Is a Program?
A program is any set of instructions that are created or followed. In this book, we
focus on writing computer programs, which are lists of instructions that a com-
puter 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 analogue 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 intro-
duced 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.

DOI: 10.1201/9781003201496-1 1
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 exam-
ple, with CSS you could modify an HTML element and give it an orange back-
ground, change its font size, place it vertically or horizontally, or perform any
number of creative visual changes.

2 1. Overview and Setup


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 interac-
tive 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 appli-
cation 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 applica-
tions 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 appli-
cation 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 accom-
plish 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

What Is the Web Audio API? 3


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 instru-
ment. 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 trou-
bleshoot with. In real-world environments, you would use a test suite to trou-
bleshoot among different browsers and platforms. In this book, we are going to
keep things simple and only use the Brave Browser. Brave is built on the same
technology as Google Chrome but unlike Chrome, Brave makes user privacy a
first class feature. 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.

3. Create a folder on your desktop or in a directory and call it web audio


template.

4 1. Overview and Setup


<!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>

In your computer’s operating system set Brave as the default browser to


open HTML documents.
If you are using Linux right click the index.html document and go
to properties/open with/ and choose Brave and click Set as Default.
If you are using Windows right click the index.html document and
choose Open with and select Brave.
If you are using Mac right click the index.html document and choose
Get Info and Open with. Select Brave
Setting Brave as the default browser is done for convenience as it will
be useful when running web programs from Sublime text.

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.

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.

Setting Up Your Work Environment 5


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.

How to View in Browser


It is useful to know how to open HTML files into your web browser directly from
within SublimeText. To do this, drag an html file into SublimeText, right click the
contents on the page, and click “Open in Browser”. Your web browser will open
the selected HTML file.

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.

6 1. Overview and Setup


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>.

Accessing the Developer Tools


The Brave Browser has a built-in suite of troubleshooting tools called the
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 program-
mers 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://stackover-
flow.com/questions/tagged/web-audio.

Troubleshooting Problems and Getting Help 7


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. Open the Sublime text editor and drag the
hello_sound folder to it.
Type the code below into the app.js file that is present within the hello_sound
folder and save it.
const audioContext = new AudioContext();
let osc = audioContext.createOscillator();
osc.type = "sine";
osc.connect(audioContext.destination);
osc.start(audioContext.currentTime);

In Sublime go to tools/Sublime Server/ and select Start Sublime Server. This


will start a web server. In your web browser go to http://localhost:8080 and select
the folder titled hello_sound. You will hear an oscillator.

DOI: 10.1201/9781003201496-2 9
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 oscil-
lator. 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.
If you were to run the previous code on a public web server (as opposed to
privately on your local web server), it will not play unless the user enables the
web audio API via a gesture such as a mouse click or other action. For this, we
will need to write additional code. To see a warning about this problem, refresh
the browser and open the developer tools. A warning stating “The AudioContext
was not allowed to start. It must be resumed (or created) after a user gesture on
the page” is presented.

The code to fix the error is presented below. Remove the previous code and
replace it with the following code.
const audioContext = new AudioContext();
document.addEventListener("mousedown", function() {
let osc = audioContext.createOscillator();
osc.type = "sine";
osc.connect(audioContext.destination);
osc.start(audioContext.currentTime);

});

When you launch the web server and click the webpage an oscillator will play.
The code used to trigger the oscillator when the page is clicked is called an event
listener. The event listener is the portion of code that looks like this:
document.addEventListener("mousedown", function() {

In the example below, all web audio code except the AudioContext is placed
inside the event listener.
const audioContext = new AudioContext();
document.addEventListener("mousedown", function() {
let osc = audioContext.createOscillator();
osc.type = "sine";

10 2. JavaScript and the Web Audio API


osc.connect(audioContext.destination);
osc.start(audioContext.currentTime);

});

A more sophisticated version of the above code is written below. The following
code lets you toggle the oscillator on and off when the page is clicked:
const audioContext = new AudioContext(); //___Initializes web audio
api
let osc;
function playOsc(oscType, freq) {
if(osc){
osc.stop(audioContext.currentTime);
console.log("Stopped");
osc = undefined;
}else{
osc = audioContext.createOscillator();
osc.type = oscType;
osc.frequency.value = freq;
osc.connect(audioContext.destination);
osc.start(audioContext.currentTime);
console.log("Start")
}
}
document.addEventListener("mousedown", function() {
playOsc("sine", 330);
});

Don’t worry about knowing how the code works just yet; we are going to 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:
let waveformType = "sawtooth";

The variable here is named waveformType. This is preceded by the let keyword.
The let keyword is a variable declaration keyword. You always specify the vari-
able declaration keyword prior to declaring the variable. Declaring a variable
means you are creating a new variable. JavaScript has three different variable
declaration keywords and they are const, let, and var. In this chapter, we go over
the let and const declaration and in later chapters you learn about var. After typ-
ing the declaration keyword you type a space and give a name to your variable.
Variable names are typically a reflection of the thing they represent. In this case,
the variable is being used to describe a type of oscillator waveform, 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

Variables 11
names cannot contain white space to separate them. If you rewrote the variable
in the following manner, you get an error:
let waveform type = "sawtooth"; //____returns an error

Type the above code into the app.js file of your hello_sound template. Launch
the browser and open the developer tools by right clicking on the page and
selecting “inspect” or using the key command (Windows: Ctrl+Shift+I or Mac:
Command+Option+I). Inside the console tab you should see an error similar to
the one in the following image.

The text in red is the actual error and is identified as a syntax error. Directly 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:
let 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 lan-
guages have different data types. JavaScript has eight 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 declaration keyword

◾ The variable name

12 2. JavaScript and the Web Audio API


◾ The assignment operator

◾ The data you wish to assign to the variable

◾ The closing semi colon

You can assign multiple variables at once using the following syntax:
let osc1 = 1200,
osc2 = 1300,
osc3 = 100;

When using the let keyword to declare variables you can reassign them as in this
example.
let osc = 500;
console.log(osc) // 500
osc = 1000;
console.log(osc) // 1000

Declaring variables with let more than once in the same scope will create an
error. You will learn more about scope in later chapters.
let osc = 500;
let osc = 1000; // error, variable already declared.

The const declaration behaves differently than let. Const is used with variables
that the developer intends to remain unchanged after being declared. If you
declare a variable with const and assign it a primitive data type such as a number
or string you will get an error if you change it.
const osc = 1000;
osc = 1000 // reassignment gives an error

In some cases, you might want to declare a variable and not assign data to it, as
in the following example:
let waveformType;

If you do this using let, JavaScript automatically assigns undefined to it.


You can also assign undefined explicitly like this:
let 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.
If you declare a variable using const and do not explicitly assign a value to it,
the interpreter will return an error.
const osc; // SyntaxError: Missing initializer in const declaration

Variables 13
Null
The primitive value null is similar to the primitive value undefined. Both can act
as a placeholder for empty variables. When the type of 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, I suggest 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 or multi-line comments into 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 on our code like this:


let waveformType = "sawtooth"; // oscillator value

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:
const audioContext = new AudioContext();
let waveformType = "sawtooth"; //___added variable
let 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:
const audioContext = new AudioContext();
let waveformType = "sawtooth"; //___added variable
let osc = audioContext.createOscillator();
osc.type = waveformType; //__Assigned it to our oscillator type
osc.connect(audioContext.destination);
osc.start(audioContext.currentTime);

14 2. JavaScript and the Web Audio API


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.
const audioContext = new AudioContext();
//___ 4 variables that represent oscillator waveforms
let saw = "sawtooth";
let sine = "sine";
let tri = "triangle";
let square = "square";
//___ A variable intended to contain one of these waveforms
let currentWaveform = undefined;
currentWaveform = square;
//_____________________________Start of oscillator
let 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 vari-
ables 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 variables assignment. You then place the vari-
able name inside the parenthesis. You can also add a message to console.log() by
placing a comma after the variable and writing a message in quotes.
To see what the currentWaveform variable has as its assignment, you do this:
const audioContext = new AudioContext();
//_____________Added 4 variables that represent oscillator
waveforms
let saw = "sawtooth";
let sine = "sine";
let tri = "triangle";
let square = "square";

console.log() 15
let currentWaveform = undefined;
currentWaveform = square;
console.log(currentWaveform, “The waveform type”); //___ square
//____________________________________Start of oscillator
let osc = audioContext.createOscillator();
osc.type = currentWaveform; // Assigned it to our oscillator type
osc.connect(audioContext.destination);
osc.start(audioContext.currentTime);

If you launch Brave, 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() immedi-
ately 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
let currentWaveform = undefined;
console.log(currentWaveform); //______results in "undefined"
currentWaveform = square;

So far we’ve mentioned three of the seven 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:
let 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:
let oscillator = "saw" + "tooth";
console.log(oscillator); // sawtooth

Here is another example of concatenating two variables and storing them in a


new variable.
let phrase = "This sound is an ";
let soundType = "oscillator";
let sentence = phrase + soundType;
console.log(sentence); // "This sound is an oscillator".

Another way to combine strings is with string interpolation using template literals.
A template literal uses the “${}” syntax. For template literals, back ticks are used to
create a string and variables are placed in the curly braces after a dollar sign.

16 2. JavaScript and the Web Audio API


let phrase = "This sound is an ";
let soundType = "oscillator";
let sentence = `${phrase}${soundType}. Ocillators sound cool!`;
console.log(sentence); // "This sound is an oscillator.Ocillators
sound cool!".

Notice that strings can contain white space.


This is a perfectly valid string even though it contains a lot of white-space
characters:
let 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 toUp-
perCase() and toLowerCase() methods.

toUpperCase()
This method changes all the characters in a string to uppercase.
let oscillator = "sawtooth";
oscillator.toUpperCase(); // SAWTOOTH

toLowerCase()
This method changes all the characters in a string to lowercase.
let 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 string methods
works, but it is a good idea to know about them. This way, when you do need to
implement any of the functionality they provide, you know which tool to reach

Built in String Methods 17


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 exam-
ple, 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:
let sound = "oscillator";
console.log(sound.charAt(1)); // "s"

Now you might be wondering why charAt(1) would give us back “s” and not “o”.
The reason is that the count begins at zero. So if we wanted the first letter we
would 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:
let myFavoriteSynthCompany = "My favorite synth company is Moog.
Moog is great!";
let 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.
let myFavoriteSynthCompany = "My favorite synth company is Moog.
Moog is great!";
let 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 wanted the
string replacement to be case-sensitive you would simply 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.

18 2. JavaScript and the Web Audio API


slice()
This method extracts part of a string.
let oscillator = "sawtooth";
let 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 0. 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 non-inclusive. 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
parenthesis and does not require arguments to return a value. The character
count of the length property starts at one and not zero.
let 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 while charAt() begins count-
ing at zero. Therefore, you subtract one from the length property to compensate
for the offset.
let sound = "oscillator-1";
let oscNumber = sound.charAt(sound.length − 1);
console.log(oscNumber); // 1

Numbers
In JavaScript, numbers are a distinct data type. Below is a variable named fre-
quencyValue and it is assigned a number of 200. It is then assigned to the oscil-
lators 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 oscilla-
tor play at different pitches.
const audioContext = new AudioContext();
let frequencyValue = 200; //___Create variable frequencyValue
let waveform = "sawtooth";

Numbers 19
Discovering Diverse Content Through
Random Scribd Documents
No perdonaba ni una mota. Aun con la familia estaba el buen señor
muy enojado: economizaba con avaricia las palabras; ponía defectos
á la comida diaria; quejábase de inexactitudes en los servicios de su
hermana; á cualquier descuido, como un botón por pegar ó un
cuello mal planchado, daba importancia extrema. Se paseaba
silencioso de un ángulo á otro de su cuarto, y Felipe se asustaba
oyéndole dar unos suspiros tan grandes, que eran como si por el
resuello quisiera descargarse de un pesadísimo tormento interior.
Únicamente salía de sus labios la frase rutinaria «voy á dar una
vuelta» en el momento de ponerse la capa.
Tal estado de misantropía se iba desvaneciendo, y el personaje,
cual pieza forjada que se enfría y recobra su temple y dureza, volvía
lentamente á su carácter normal: pacífico y tierno con la familia,
afable y cariñoso con todos menos con los alumnos.
Cuando don Pedro se iba á dar la famosa vuelta, doña Claudia,
que cenaba sola y más tarde que su hijo, se comía el salpicón ó la
ensalada con el cortadillo de vino, y luego se daba á la endiablada
tarea de combinar sus números y recorrer las listas pasadas para
hacer un cálculo de probabilidades que no entenderían los
matemáticos de más tino. El sueño la cogía de súbito en estos
afanes, y se dormía sobre sus laureles aritméticos. Después de dar
mil cabezadas íbase á la cama, arrastrándose, y poco después sus
ronquidos daban fe de la tranquilidad de su conciencia.
Marcelina y Felipe se quedaban en vela esperando á don Pedro,
junto á la lámpara del comedor, ella ocupada en costura ó laborcilla
de crochet, él estudiando las lecciones del día siguiente. Muy á
menudo el Doctor inclinaba la cabeza sobre la Gramática y se
quedaba dormido, como esos Niños Jesús á quienes pintan
durmiendo sobre el libro de los Evangelios. La fea de las feas tenía la
bondad de respetar á veces aquel descanso, y no lo interrumpía en
media hora. Cuando el chico estaba despierto, la señora le
sermoneaba, echándole en cara su poco amor al estudio, sus
descuidos en el servicio, y principalmente su pícara afición á
vagabundear por las calles y á detenerse las horas muertas en los
recados. Bien conocía Centeno la justicia de estas observaciones;
pero en cuanto á su gusto de callejear, se sentía cobarde para
reprimirlo, porque la amistad de Juanito del Socorro, que le contaba
cosas tan interesantes de política y revoluciones, era el único
bálsamo de su vida miserable.
Triste era para él la casa; triste su habitación; tristísima la
escuela, el pasante y los libros; más tristes aún doña Claudia, la
cocinera y la cocina. La calle y Juanito eran todo lo contrario de
aquel marco sombrío y de aquellas figuras regañonas y lúgubres; lo
contrario de los coscorrones, de las bofetadas, de los gritos, del
estirar de orejas, de la Gramática (¡el impío y bárbaro estudio!), de
la bestial Maritornes, de aquel rudo trabajo sin recompensa moral ni
estímulo. Sin un poquito de calle cada día; luz de su obscuridad,
lenitivo de su pena y descanso de su entumecido físico y moral, la
vida le habría sido imposible.
—Lee, hombre, lee—le decía por las noches Marcelina, sin quitar
los ojos de su obra, cuando á Felipe sorprendía jugando con sus
propios dedos ó atendiendo á los ruidos de la calle.—Eres malo de
veras. No aprenderás nunca palotada. Mi hermano dice que él ha
conocido muchos brutos, pero ninguno como tú... ¿No te da
vergüenza, hombre, de ver á otros niños tan aplicaditos...?
Reconociendo el Doctor que la señora hablaba como la misma
sabiduría, no le hacía gran caso, y con el alma, más que con los
ojos, miraba á la calle, oyendo los silbidos con que le llamara el del
Socorro. ¡Inmenso dolor!... ¡No poder acudir á tan dulce reclamo!
Sin duda tenía que contarle aquella noche cosas muy buenas: por
ejemplo, que los regimientos se iban á echar á la calle, que la cosa
estaba en un tris, y los curas con el alma en un hilo... No había más
remedio que tener paciencia y entretener de cualquier modo las
pesadas horas, ya mirando los movimientos que con sus dedos hacía
Marcelina metiendo y sacando el gancho, ya contando los hoyos que
aquella excelente señora tenía en la nariz, ó los erizados pelos de su
verruga... porque pensar que él había de leer en la fementida
Gramática, era pensar en lo imposible.
Un sistema de distracción encontró Centeno, á fuerza de
aburrirse, y era observar los distintos ruidos que hacían las puertas
mohosas de la casa cuando las abría y cerraba la cocinera, la cual
andaba trasteando, hasta más de las diez, de la cocina á la despensa
y de la despensa al comedor. Las puertas, como toda la casa, tenían
dos siglos de fecha, y en tan largo tiempo nadie se había tomado el
trabajo de acariciar con aceite sus gastados, secos y polvorientos
goznes. Así es que daban unos gemidos que parecían de seres
vivientes, y su lamentar producía los más extraños efectos
musicales. En la soledad y hastío de su espíritu, Felipe no hallaba
mejor entretenimiento que observar la diversa tesitura y acento de
cada uno de aquellos ruidos. Tal puerta imitaba el mugido de un
buey; tal otra el llanto de un niño; alguna sonaba como voz gangosa
que pronunciara el principio del Padre nuestro; la de más allá
parecía la matraca de Viernes Santo, y otra decía siempre: mira que
te cojo. Amenizaba estas sonatas el lejano roncar de doña Claudia,
que á ratos era silbido tenue, á ratos fabordón que decía con toda
claridad: Sursum Cooor...da.
Cuando las puertas callaban, cual si se durmieran, Felipe buscaba
impresiones del mismo orden en las vidrieras. Eran éstas, como las
ventanas, grandísimas, desvencijadas. Se componían de vidrios
pequeños, verdosos, que retasaban la luz y eran como aduaneros de
ella, pues no la permitían pasar sin cogerse una parte. La madera
estaba pintada de azul, al temple, según el uso antiguo; el plomo
era negro, y de puro viejo apenas sujetaba los vidrios. Estos,
siempre que los pesados bastidores se abrían, bailaban en sus
endebles junturas, cual si quisieran saltar y echarse fuera. Cuando
pasaba un coche por la mal empedrada calle, era tanto el temblor y
tanta la chillería de los vidrios, que las personas tenían que dar
fuertes gritos para hacerse oir.
Tal era la ocupación del Doctor: atender al paso de los coches.
Desde que sentía su rodar lejano, ponía alerta el oído para observar
cómo lentamente empezaba el retintín de los vidrios; cómo iba en
rápido crescendo, hasta ser algarabía estruendosa. Antojábasele
comparar la casa con un cuerpo humano al que se hacían cosquillas,
y con las cosquillas se disparaba en convulsivas risotadas.
De todo esto era preciso tomar nota, y con su pedacito de lápiz
iba marcando disimuladamente con rayas, en el margen del libro, los
coches que pasaban. Pero algunas veces era vencedor de la atención
el fastidio. Felipe hacía almohada de la Gramática y se cuajaba
dulcemente como un ángel. Viéraisle despertar pavorido á la entrada
de don Pedro, que, por tener llavín, no llamaba nunca. Á veces, una
mano vigorosa le extraía, suspendido de la oreja, de aquel seno
placentero de su sueño, y oía una voz de trompeta del Juicio Final,
diciendo: «Á acostarse.»
Andaba dormido, tropezando, los sentidos abotagados, sin
enterarse de lo que charlaban el amo y su hermana antes de
recogerse. Á tientas subía por fin á sus elevados aposentos, y... Á
media noche todo dormía en la casa: personas, goznes y vidrios.
Sólo don Pedro, algunas veces, tenía el sueño tan difícil, que el alba
y aun el claro día le encontraban como un lince; y gracias que
pudiera aletargarse y dar breve descanso á sus potencias cerebrales
á hora inoportuna, cuando ya el esquilón monjil le avisaba que era
llegada la de la misa.
IX
En la calle de la Libertad, más allá de la esquina de la casa donde
la redacción estaba, había un solar vacío, separado de la calle por
una cerca de desiguales y viejas tablas. Dentro sólo se veían
montones de escombros, media docena de escobas y otras tantas
carretillas que dejaban allí los encargados de la limpieza urbana.
Tenía la tal valla una puerta que estaba cerrada casi siempre; pero
Juanito del Socorro y otros chicos de la vecindad, asistentes á la
escuela de don Pedro, habían hallado medio de colarse dentro,
arrancando una tabla y apartando otra; y posesionados del terreno,
lo dedicaron á plaza para hacer en él sus corridas.
Habiendo sido admitido un día Felipe á esta diversión infantil,
halló tanto gusto en ella, que se hubiera estado todo el santo día en
la plaza, sin acordarse para nada de sus deberes escolares y
domésticos, ni de don Pedro, ni del santo de su nombre. Mientras
más el juego se repetía, más afición le cobraba, y los domingos por
la tarde, si sus amos le permitían salir, entregábase con frenesí á las
alegrías del toreo. Saltar, correr, montarse sobre otro; ser
alternativamente picador, caballo, banderillero, mula, toro y diestro,
era la delicia de las delicias, exigencia del cuerpo y del alma, prurito
que declaraba perentorias necesidades de la naturaleza. Días
enteros pasaba pensando en el ratito que podía dedicar á la función,
ó representándose los entretenidos episodios y pasos de ella. Y
tanto repitieron los chicos aquel juego, que llegaron á organizarlo en
regla, para lo cual tenía especial tino el gran Juanito del Socorro,
sujeto de mucho tacto y autoridad. Era empresario y presidente,
acomodador y naranjero. Dirigía las suertes y á cada cual asignaba
su papel, reservando para sí el de primer espada. Á Felipe le tocaba
siempre ser toro.
Quisieron proporcionarse una de esas cabezotas de mimbres que
adornan las puertas de las cesterías; pero no lograron pasar del
deseo al hecho, porque no había ningún rico en la cuadrilla, ni
aunque se juntaran los capitales de todos podrían llegar á la suma
necesaria. Se servían de una banasta, donde Felipe metía la cabeza.
¡Con qué furor salía él del toril, bramando, repartiendo testarazos,
muertes y exterminio por donde quiera que pasaba! Á éste
derribaba, al otro le metía el cuerno por la barriga, al de más allá
levantaba en vilo. Víctimas de su arrojo, muchos caían por el suelo,
hasta que Juanito del Socorro, alias Redator, lo remataba gallarda y
valerosamente, dejándole tendido con media lengua fuera de la
boca.
Cada cual contribuía con sus recursos y con su inventiva á dar
todo el esplendor y propiedad posibles á la hermosa fiesta. No había
detalle que no tuvieran presente, ni oportunidad que no
aprovecharan aquellas imaginaciones llenas de viveza y lozanía. Blas
Torres, hijo de un prendero, se proporcionó una capa de seda con
galoncillos de plata. Algunos llevaban capa de percal, y otros se
equipaban con un pedazo de cualquier tela. Perico Sáez, hijo del
carnicero, presentó á la cuadrilla una adquisición admirable y de
grandísimo precio: un rabo de buey, que Felipe se ataba en
semejante parte para imitar la trasera del feroz animal. Con aquello
y la banasta en la cabeza, y los bramidos que daba, parecía
acabadito de venir de la ganadería. Fuenmayor llevaba las
banderillas de papel, y Gázquez, hijo del estanquero, llevaba una
cosa muy necesaria en juego tan peligroso, á saber: tiras de papel
engomado de los sellos para aplicarlo á las heridas, rozaduras y
contusiones. El chico de la prestamista se había proporcionado una
corneta para hacer las señales, y algunos cascabeles para las mulas;
y Alonso Pasarón, el de la tienda de ultramarinos, que era artista,
pintor y tenía su caja de colores para hacer láminas, llevaba los
carteles con una suerte pintada en verde y rojo, grandes letras y
garabatos en que no faltaba palabra, ni fecha, ni detalle de los que
en tales rótulos se usan. Pero de cuanto aquellos benditos
inventaron para imitar al vivo las corridas, nada tan ingenioso como
lo que se le ocurrió á Nicomedes, hijo del dueño de una tienda de
sedas de la calle de Hortaleza. Este condenado reunió en su casa
muchas varas de cinta encarnada: con ellas hacía un revuelto lío; se
lo metía en la camisa junto á la barriga, y cuando en lo mejor de la
lidia desempeñaba con admirable verdad, vendado un ojo, el papel
de caballo, y venía el toro y le daba el tremendo topetazo en el
cuerpo, empezaba á soltar cinta y más cinta y á cojear y dar
relinchos y á hacer piruetas de dolor, con tal arte, que parecía que
se le salían las tripas y que se las pisaba, como suele suceder á los
caballos de verdad en la sangrienta arena de la plaza. Para que nada
les faltara, también se habían adjudicado unos á otros sus alias en
sustitución de los nombres verdaderos. Á Nicomedes se le llamaba
Lengüita, sin duda por lo mucho que hablaba. Blas Torres, ilustre
hijo de una prendera, tenía por mote Trapillos. Felipe respondía por
el Iscuelero, y Juanito del Socorro tenía un apodo á la vez popular y
respetuoso, nombre peregrino, que declaraba en cierto modo su
origen literario. Se le llamaba Redator.
En lo mejor de la pelea se presentaba un individuo de policía ó el
guarda del solar, y les echaba á la calle... Porque, verdaderamente,
¿qué cosa más contraria á la dignidad de una población que esta
batahola de chicos en un solar cerrado, en día festivo, y cuando los
mayores se entregan con delirio á las ardientes emociones del toreo
verdadero? Los guindillas ó polizontes municipales demostraban un
celo digno de todo encomio en la corrección de estos abusos
infantiles, y el guarda, enojadísimo porque profanaban la virginidad
de su solar, la emprendía á escobazos con los lidiadores y... Dios nos
libre de que alguno se le rebelara... Por la calle adelante salía
corriendo la partida, perseguida activamente por la fuerza pública, y
al fin se disolvía, sin más consecuencias y sin ninguna desgracia
personal.
Por lo mismo que Felipe no podía disfrutar de este juego sino en
breves y angustiosos momentos, robados á cualquier obligación, sus
goces eran grandísimos, inefables, y no los trocaría por la gloria
eterna. Los sofiones que se llevó por su tardanza en un recado ó por
sus escapatorias cuando el deber le llamaba á la casa, no son para
contados. Pero llegó á familiarizarse de tal modo con el sermoneo y
los golpes, que ya no le hacían efecto. Estaba al fin como curtido, y
su cuerpo se le figuraba forrado de duras conchas como las del
galápago. Moralmente, su atrofia corría parejas con la insensibilidad
dérmica, y el convencimiento de que era malo, incorregible, llevábale
á sentir altivo desprecio de los mandamientos de todos los Polos
nacidos y por nacer.
Cuando se retiraba de noche á su madriguera, renovaba en su
mente con claridad y frescura las gratas sensaciones de la última
corrida, y á la memoria traía los puyazos que le dieron, los jinetes
que echó á rodar por el suelo, los caballos que destripó y los diestros
que hizo pedazos. Oía la bélica trompeta y los gritos de la multitud.
Hasta el recuerdo del despejo final, hecho á escobazos por el
guarda, y aquel desalado correr por la calle, insultando desde la
esquina al mismo guarda, tenía dejos gratísimos en su memoria.
¡Oh! divinas horas, ¿por qué pasáis?
Pronto le ganaba el sueño, y se dormía profundamente, rendido
de cansancio. No le permitían usar luz por temor á que prendiera
fuego á los trastos almacenados en el desván, y cuando no había
luna que le iluminara el paso por aquel tenebroso y fantástico
recinto, á tientas buscaba su rincón, y ya se trompicaba en el cáliz
de la Fe, ya iba á parar á los brazos de una Virgen, ó rodaba entre
las columnas del monumento.
Si por acaso despertaba á media noche ó de madrugada, y era
tiempo de luna, le entraba miedo de verse entre tantos señores de
cartón. los unos en pie, los otros arrumbados, casi todos muy
barbudos y con luengos trajes blancos ó negros. Por allí salía un
brazo con dorada custodia; por aquí la cabeza melenuda de un león;
por allá judíos feroces con los brazos en alto y las manos armadas
de disciplinas; caras lívidas y afligidas, y lienzos negros con calaveras
pintadas y canillas en cruz. Las primeras noches pasó Felipe
momentos de agonía, y los escalofríos y congojas no le dejaban
dormir. El terror le apretaba los párpados, y la curiosidad se los
abría... Abría un poquito, y luego al punto cerraba prontamente para
no ver más. Poco á poco se fué acostumbrando á ver sin miedo las
figuras que poblaban su vivienda, y de tal modo se connaturalizó con
ellas, que llegaron á parecerle individuos de la familia, algo como
parientes mudos ó callados amigos. No obstante, le desagradaba
despertar á media noche en tiempo de luna, porque, ó él era tonto y
veía visiones, ó la Fe soltaba el cáliz y se quitaba la venda de los
ojos para mirarle á él, á Felipe, que no osaba moverse ni el espacio
de un dedo.
También le puso al principio en gran zozobra un ruido que sentía
tras las paredes, así como roce y vibración de una soga, rumor
seguido de lejanos tañidos de campana. No tardó en comprender
que un tabique le separaba de la parte alta del convento, y que por
allí pendía la cuerda con que las señoras monjas tocaban á maitines
á desusadas horas de la noche. Sentía también Felipe ruido de
pasos. Eran las esposas de Jesucristo que bajaban al coro. Una de
ellas debía de ser coja, porque claramente se sentía el acompasado
toqueteo de dos muletas.
Tempranito despertaba nuestro Doctor. Generalmente no era
preciso llamarle; pero á veces, si su cansancio le emperezaba un
poco, subía la criada, y tirándole del cabello le ponía más
despabilado que una ardilla. Se levantaba mi hombre renegando de
las criadas madrugadoras, y antes de bajar se daba un paseo por
entre sus inmóviles compañeros de domicilio, observando las
variaciones que el tiempo y el olvido ponían en la catadura de cada
cual. Á una santa le habían comido los ratones media cabeza. Las
telarañas que abrigaban como toquilla el vendado rostro de la Fe,
crecían atrozmente, y rostros que fueron lampiños echaban barbas
de polvo; rodaban por el suelo torneados brazos, alas de ángeles,
manos de judíos que, aun desprendidas, no habían soltado el látigo.
Había rostros apolillados que de tristes habíanse vuelto cómicos y
alegres.
Pero lo más interesante para el gran Felipe era un San Lucas,
tamaño como dos hombres bien conservados, y que estaba, no
enteramente á plomo, sino algo arrumbado sobre San Marcos, el
cual, oprimido del peso de su compañero, tenía muy ajadas las
ropas. Á los pies del primero había un magnífico toro, del cual no se
veían más que los cuartos delanteros y la cabeza, tan grande y
hermosa como la de los que salen en la plaza. El escultor que lo hizo
había sabido imitar á la Naturaleza con tan exquisito arte, que al
animal no le faltaba más que mugir. Tenía los cuernos relucientes,
corvos y agudísimos; los ojos negros y vivos; la piel obscura... en
fin, daba gozo el verle.
De cuanto en el desván había, esta cabeza taurina era lo que
principalmente merecía la admiración, mejor dicho, los amores de
Felipe. La quería con toda su alma. Todos los días le quitaba el
polvo, y por fin la limpió con agua, dejándola tan reluciente, que era
una maravilla de aseo. Un día, mientras la limpiaba, notó en el cuello
del animal una grande y profunda hendidura. Sí: la cabeza estaba
casi separada del tronco, y bastaba tirar un poco para desprenderla
completamente. ¿Se atrevería?... Sí: Felipe tiró cuidadosamente y
con cierto respeto, y el apolillado cartón se rasgó como un papel.
La cabeza era hueca, cual muchas de carne y hueso puestas
sobre humanos hombros. En la mente de Felipe nació una idea...
¡qué idea! Pronto fué luz y norte de su alma... ¡Qué soberbia pieza
para jugar al toro! El Doctor metió su cabeza dentro de la del
animal, y vió que le venía como el mejor de los sombreros... Pero no
veía nada. Los ojos no tenían agujeros... Tanto le dominó y subyugó
su idea, que aquel mismo día hubo de subir con disimulo el cuchillo
de la cocina, y le sacó los ojos al toro. Hizo dos agujeros, con los
cuales la cabeza quedó convertida en admirable careta. ¡Bien, muy
bien!
¡Si él se atreviera...! pero no, no se atrevería. Pues si se atreviera,
¡qué golpe!... ¡Si cuando estuviesen los chicos en lo mejor de la
corrida se presentara él de repente con su cabeza puesta...! De fijo
creerían que había entrado en la plaza un toro de verdad... ¡Qué
sensación, qué efecto, qué delirio! ¡Con qué envidia le mirarían!...
Porque él primero se dejaría desollar que ceder su cabeza á nadie...
Pero no se atrevía, no...
Gran batalla surgió en su alma, turbándola espantosamente.
Aquella idea tenía poder bastante para interrumpir su pesado sueño
infantil. Á media noche despertaba creyendo estar en la plaza,
haciendo lo que por el día había pensado. De día, y dando la lección,
soñaba lo mismo, y no se volvía su espíritu á ninguna parte sin llevar
consigo la idea tentadora, gozo y tormento de su existencia. Ya, en
los breves ratos sustraídos á su obligación, no salía á la calle en
busca de Juanito del Socorro (Redator), sino que en dos trancazos
se encaramaba en el desván, y poniéndose la cabeza, arremetía al
mismo San Lucas, á la Fe, á los rotos telones, y en todo ello, con las
repetidas cornadas, abrió mil agujeros y desgarraduras. Por el
boquete que el santo Evangelista tenía en su vientre, se le verían las
entrañas si algunas hubiera.
Cuando se cansaba de este ejercicio, se divertía de otro modo.
Tenía el desván un ventanillo alto que daba á los tejados y
buhardillones de la vecindad. Con ayuda de un banco, Felipe subía
hasta alcanzar con su cabeza el hueco, se ponía la del toro y se
asomaba para ofrecer inusitado espectáculo á los chicos y á las
mujeres de la buharda frontera. Él se reía lo increíble, viendo por los
agujeros, que eran los ojos del animal, el estupor y miedo de los
espectadores; y para dar más carácter á la broma, lanzaba desde el
interior de su máscara un prolongado y terrorífico muú... imitando el
bramar de la fiera. Los chicos de la vecindad que tal veían se
alborotaban; las vecinas se asomaban también, y todo era
curiosidad, cuchicheos, asombro y dudas... De pronto desaparecía el
toro... Expectación. Presentábase de nuevo, llenando el marco del
ventanucho; y como no se viera rastro de persona, ni se tenía
noticia de que allí habitase nadie, crecía la sorpresa de aquella gente
y la felicidad del Iscuelero.
Si se atreviera, ¡ay!... ¿pero cómo atreverse? Don Pedro le
mataría.
X
En éstas y otras cosas pasaba el verano, época dichosa para
algunos de los alumnos del capellán; mas no para Felipe y las demás
víctimas, porque don José Ido siguió funcionando durante la canícula
y don Pedro administrando coscorrones. Á tantas diversidades de
tormentos uníase la asfixia, porque el infierno de Polo tenía
exposición meridional, y si por una ventana salían lamentos, por otra
entraban llamaradas. Se podía decir que en aquel caldeado altar de
la instrucción se ofrecían á la bárbara diosa entendimientos
cochifritos... Pero esto se queda aquí, pues lo que nos importa ahora
es hablar de la solemnísima fiesta religiosa que celebraron las
monjas, no se sabe bien si el 15 de Agosto ó el 8 de Septiembre, por
haber cierta obscuridad en los documentos que de esto tratan. Mas
como la fecha no es cosa esencial, y ambas festividades de la Virgen
son igualmente grandes, queda libre este punto para que cada cual
lo interprete ó aplique á su gusto.
Consta, sin género alguno de duda, que ofició el obispo de
Caupolicán, prelado de excelsa virtud y humildad, y que dijo el
panegírico nuestro buen don Pedro Polo, el cual supo salir muy
airoso de su empeño, que consideraba el más arriesgado de su vida
por ser alto y sutil el asunto, la función muy aparatosa, el auditorio
escogidísimo. Su varonil presencia en la cátedra, así como su
hermosa voz, le aseguraban las tres cuartas partes del éxito. Gustó
mucho el sermón, y de uno á otro confín de la iglesia, cuando don
Pedro bajaba del púlpito, se oían esos murmullos de aprobación que
equivalen á los aplausos que en otros sitios manifiestan el contento
del público. Doña Claudia y Marcelina habían mojado entre las dos,
de tanto llorar, una docena de pañuelos. No faltaba ninguno de los
amigos de la casa: Morales y su esposa, don José Ido, el fotógrafo y
el empleado de Hacienda con sus señoras respectivas, y Sánchez
Emperador con sus dos guapas niñas, Amparo y Refugio.
Felipe y Juanito del Socorro se habían subido al coro para ver
mejor y estar al lado de la música y oirla de cerca. Pegados al que
tocaba el contrabajo, estorbaban sus gallardos movimientos en tal
manera, que el buen músico, un anciano de mucha paciencia y
cortesía, les dijo alguna vez, apartándoles:
—Si me hicieran ustedes el favor...
Felipe estaba lelo, mirando cómo vibraban las cuerdas de aquel
formidable instrumento; luego observaba embelesado cómo abrían
la boca los cantores; y él y Juanito agradecían mucho que se les
mandara tener algún papel de música ó traer un vaso de agua al
señor director, el cual era un hombre con mucha hormiguilla en el
cuerpo, según se movía y dislocaba para conducir la orquesta y toda
la balumba de voces.
Durante el panegírico, ambos, aburridísimos, se fueron á la calle y
se metieron en la redacción, que estaba desierta por ser día festivo.
Revolvieron los pupitres de los redactores, comieron obleas rojas,
cortaron pedazos de periódico, escribieron en las cuartillas. En un
momento de entusiasmo, Juanito se subió sobre la mesa, y empezó
á repetir frases que antes oyera y que se habían grabado en su
memoria. El condenado imitaba la voz y gesto de alguno de los
periodistas ausentes, diciendo:
—Señores, esto se va... los dioses se van... esto matará á aquello.
Después subieron al campanario del convento. Juanito, siempre
fatuo y vanidoso, contaba á Felipe las grandezas de su casa. ¡Qué
cosas le dijo! Su madre tenía una silla dorada, y su padre era amigo
de un Marqués. Él iba á estudiar para redator, y su padre no
esperaba sino que llegara la jarana para ponerse su uniforme de
capitán de la milicia. Como en estas conversaciones siempre sacaba
á relucir el del Socorro los términos que oía, habló á Felipe del
pueblo soberano, de la revolución próxima, de los curas, de la tropa
y de ahorcar mucha y diversa gente. Esto, dicho en las alturas del
campanario y bajo los ardientes rayos del sol, le puso á mi Felipe la
cabeza toda exaltada y como en ebullición, llena de ideas sediciosas
y disolventes. Cuando bajaban á saltos por la angosta escalera, le
dijo Socorro:
—Aquel obispote que está en el altar mayor, es el capitán general
de los curas... ¡Vaya un peje!... ¡Cuando se arme...!
Concluída la función, hubo refresco en casa de don Pedro. Las
monjas enviaron dulces y bartolillos, y el predicador laureado sacó
de un misterioso armario de su cuarto botellas de vino añejo que le
había regalado el padre de uno de sus alumnos. Brindó el fotógrafo
por el primero de nuestros oradores sagrados, cuyo elogio recibió
don Pedro con carcajadas de modestia. El oficial de Hacienda,
frotándose las manos, no cesaba de decir:
—Bien, señor de Polo, muy bien.
Doña Claudia se reía como si no tuviera bien sentado el juicio, y
el majestuosísimo don Florencio Mora...les y Temprado daba fuertes
palmadas en el hombro del héroe del día, promulgando estas
observaciones que merecen ser entregadas á la posteridad:
—Vas á dejar atrás al célebre Troncoso y á ese que llaman
Bordalúo... Estuviste muy propio. Así da gusto oir predicar. Esto es
religión, porque francamente y entre paréntesis, querido, cuando
suben á la cátedra del Espíritu Santo, ó pongamos el caso, á la
tribuna de un Congreso, algunos que...
Amparo y Refugio miraban á Polo con cierta veneración. Refugio,
que era un tanto desenvuelta, sin menoscabo de su inocencia y
purísimas costumbres, dijo así con risa y donaire:
—Don Pedro, estaba usted muy guapo en el púlpito.
Amparo, que era muy callada, tendiendo siempre á la melancolía,
no decía nada.
Obsequiaba Polo á sus amigos con exquisita urbanidad. Vestía, no
sin elegancia, su negra sotana limpia, y más que rancio y descuidado
cura español, parecía uno de esos italianos de la Nunciatura, hechos
al roce del mundo y al trato de gentes cortesanas. Cuando se suscitó
aquella cuestión de si estaba más ó menos guapo en el púlpito,
echóse á reir y dijo con mucha sorna:
—Pero, Refugio, si tú no me has visto... Yo te ví, y me parece que
te dormías.
—¡Don Pedro!
—¿No es verdad, Amparo? Ésta lo dirá. ¿Es cierto ó no que
Refugio estaba dando cabezadas?
—¡Quien las daba era ella!—exclamó Refugio señalando á su
hermana.
—¿Yo?... ¡Si no quitaba los ojos de don Pedro...! Que lo diga él.
—Bien, bien. ¿Esas tenemos? ¡Don Pedro!... ¡Amparo!—exclamó
el fotógrafo, riendo y envolviéndose una mano en otra, pues era
hombre que no sabía decir sus bromas sin amasarse las manos con
tanta fuerza cual si de las dos quisiera hacer una sola.
—¿Y cuándo predicamos en Palacio?—preguntó en tono de
excelsitud el señor de Morales, ávido de cortar, con una proposición
seria, aquel tema tan baladí.
Don Pedro dió media vuelta para contestar á Sánchez Emperador,
que le daba su parecer sobre el vino que bebían. Este señor y el
empleado de Hacienda no gastaban cumplidos para aceptar copa
tras copa, y se reían de Morales, considerándole el estómago lleno
de ranas, sapos, anguilas y otras diversas alimañas acuáticas. Pero
él, sin darse por vencido, antes bien orgulloso de su pasión por las
aguas, gritaba cogiendo el vaso, lleno hasta los bordes del licor del
Lozoya:
—Estas son mis bodegas. Vaya una cosa rica... No me harto
nunca.
Felipe bajaba á cada instante al torno de las monjas, para traer
cestas llenas y llevarlas vacías.
Bizcochos, mojicones, bartolillos, pasteles, mazapanes y otras
menudencias ocupaban toda la mesa, pasando fugaces desde las
bandejas á las tragaderas del fotógrafo, de Sánchez Emperador y del
hacendista, que eran los principales consumidores. Bienaventuradas
bocas, ¡para eso os cría Dios! En poco tiempo descubrióse el fondo
de las bandejas. Había, entre los felicitantes, ropas polvoreadas,
dedos untados de pegajoso caramelo y barbas con canela.
Doña Claudia, que estaba en todo, dijo á Felipe:
—Vete corriendo al locutorio y dí á las señoras monjas que no se
olviden de mandarnos el pebre para la salsa del cabrito.
Volviendo luego á la hermosa Amparo, que á su lado estaba, le
dijo:
—Es el pebre picante de que hablábamos ayer, fuertecito como á
tí te gusta. ¡Verás qué cosa tan rica!
Don Pedro, que no cesaba de mirar á todos lados repartiendo por
igual sus finezas y ofrecimientos, alcanzó á ver, allá junto á la
puerta, lejos del animado grupo, ¿á quién? al propio don José Ido,
humilde y modestísimo en todas las ocasiones, y más en aquélla,
pues tanta era su timidez, que habiendo entrado de los primeros,
hacía media hora que estaba allí sin que nadie reparase en él, y ni
avanzar quería ni retirarse por miedo á llamar la atención. Estaba el
pobre sin saber qué hacer, inmóvil y pestañeando, parado y atónito,
cual sí le estuvieran dando una mala noticia. Don Pedro, con aquella
generosidad rumbosa que era la flor tardía, pero lozana, de un
honrado carácter, llegóse al pasante, le trajo por el brazo al círculo
de amigos y con cariñoso modo le dijo:
—No tenga usted miedo, Ido. Tomará usted una copita.
Ido refunfuñó no se sabe qué excusas; pero negarse á recibir la
copa y tomarla, todo fué uno.
—Un bollito, don José.
—Gracias... si acabo de comer...
Para aquel bendito, haber comido en Julio era acabar de comer.
En un solo instante rechazaba el bollo y se lo engullía. El fotógrafo,
qué quieras que no, le hizo tomar otra copa; y después de beber,
don José sacó un pañuelo para limpiarse la boca y enjugarse las
lágrimas, pues aquel hombre, más que hombre, era una sensitiva.
Cualquier incidente común le producía emoción vivísima, y cualquier
emoción abría la exclusa de sus lágrimas. Balbuciendo gratitudes y
dando un cordial apretón de manos á don Pedro, se marchó veloz,
bajando la escalera como si le fueran á prender.
—Este señor—dijo el fotógrafo,—es más blando que la manteca.
Entre tanto, se oía ruido de almireces que alegraría el corazón
menos sensible á los halagos de un buen comer. La cocina repicaba
á convite con más ruido que la iglesia repicando á procesión. Allí
estaba doña Saturna, afanada con tanto tráfago. La cocinera y
Marcelina la ayudaban. Grandes palmadas y bravos resonaron en la
sala, cuando Refugito, la del diente menos, se presentó, poniéndose
un delantal y diciendo:
—Voy á ayudar también.
—¡Bien, bravo! ¡Viva la cocinera de la sal!
—¿Qué nos va usted á hacer?
—La salsa picona.
—Haga usted la olla gorda.
—¿Y usted, Amparito?—preguntó con urbanidad el empleado de
Hacienda.
—Ésta no puede ir á la cocina—dijo don Pedro.—Le dan vahídos.
—Y se pone las manos perdidas,—añadió doña Claudia, haciendo
observar y admirar á todos los presentes las hermosas, blancas y
finísimas manos de la joven.
—Que nos las sirvan estofadas,—indicó el fotógrafo, riendo él su
propia gracia antes de que la rieran los demás.
Don Pedro, que no olvidaba nada y sabía, en ocasiones como
aquélla, hacer caer sobre todos, grandes y pequeños, el rocío de su
liberalidad, llamó á Felipe, que entraba y salía inquietísimo arrojando
sobre las bandejas más miradas que echó Scipión sobre Cartago, y
le dió dos bartolillos de los mayores, uno para él y otro para Juanito
del Socorro, que estaba en el portal.
Cuando los dos amigos se sentaron en el primer peldaño de la
escalera á comerse los pasteles, el Doctor, lleno de orgullo por los
triunfos oratorios de su amo y por los plácemes que le daban los
amigos, empezó á enumerar las elevadas personas que había en la
casa.
—Está ese que saca los retratos, ¿oyes? que no hace más que
verte y te pone clavado. Está ese otro señor gordo, del gabán color
de barquillo, que cuando entra da voces y respira como un fuelle.
Doña Claudia dice que le hizo la boca un fraile, por lo mucho que
come. Está también aquella señora guapa, ¿oyes? aquella que
parece una reina y que mira como las imágenes... Si la ves y te dice
algo, te caes redondo. Una tarde me pasó la mano por la cara,
¿oyes? y por poco me desmayo de gusto. Una noche estaba en la
sala con don Pedro: entré yo, y oí que don Pedro le decía que había
bajado del cielo... ella, ella... Yo la llamo La Emperadora: la otra
noche soñé que estaba yo en la iglesia, y ella bajando de un altar
con una estrella en la frente y muchas flores por aquí y por allí... Sus
dedos son azucenas.
—Hijí... no digas bobadas.
—Cuando viene acá, y come en casa, me quedo un rato como lelo
mirándola.
Juanito, que era la misma soberbia, no consentía que delante de
él se hablase de las grandezas de otras casas sin sacar á relucir al
instante las de la suya y las visitas que recibía su madre el día de su
santo. En aquella ocasión solemne su madre se sentaba en la silla
dorada, y empezaba á recibir gente. Iba un alabardero con su
sombrero atravesado, un alférez, muchos señores de sombrero de
copa, y uno que va á caballo al lado de la Reina cuando ésta sale de
paseo.
—Tiene mi madre dos amigas tan guapas, tan guapas, pero tan
guapas—indicó para concluir,—que cuando las ves te entra un frío...
¿estás? Son señoras de unos grandes pejes, y llevan vestidos de
seda verde con mucho arrumaco. Una de ellas tiene los pechos así...
Y hacía Juanito con los brazos un grande y bien arqueado círculo
delante de su pecho para dar idea, siquiera fuese aproximada, de la
delantera de aquella señora desconocida.
—¡Pues lo que es ésta...!—murmuró Felipe.
Agria y destemplada voz, gritando desde lo alto de la escalera
pillo, tunante, llamó al Doctor á su obligación. Subió y entró en la
sala á recoger copas y vasos y bandejas. Cuando los señores
fumaban, doña Claudia entró con varios papelitos en la mano,
diciendo:
—En el 5.505 lleva dos reales Enriqueta. Señor de Lomo,
guárdese usted el apuntito. ¡Qué número! Es el mío. Lo soñé hace
dos años, y le tengo una ley... Ya me lleva ganados más de mil
reales. El que va á salir ahora es el de los tres patitos: el 222. En
éste te he puesto la peseta, Amparo. Toma la papeleta. Mira que si
la pierdes, no pago. Hace cuarenta y tres extracciones que este
número no sale. Ahora, ahora... Á la cuarenta y cuatro le toca, es
decir, al doble de dos de sus tres números. Esto es claro como el
agua.
Don Pedro, el fotógrafo y Morales convinieron en que era preciso
dar un buen paseo para hacer ganas de comer, y salieron llevando
consigo á Amparo. Los demás se fueron poco más tarde, dejando
concertada la hora en que se habían de reunir por la noche para
comer. Ninguno faltó á la cita; celebróse el festín; lucióse doña
Saturnina; dijo muchas agudezas algo libres el fotógrafo, y
oportunidades sin número, llenas de donaire y finura, el insigne don
Pedro; rieron mucho Amparo y Refugio; se le fué el santo al cielo al
empleado de Hacienda; también á Sánchez Emperador, y aun hay
ciertos indicios de que doña Claudia no conservó en toda la comida
la plenitud y claridad de su juicioso entendimiento. Por último, don
Florencio se puso como una cuba, y no de vino, hasta el punto de
que, al decir del fotógrafo, podía navegar una fragata dentro de su
estómago.
Por la noche, Felipe estuvo indigesto; don Pedro ¡ay! muy triste.
XI
Algunos días después de aquél por tantos conceptos memorable,
doña Claudia notaba con asombro y pena que su hijo había perdido
el apetito. Era cosa de llamar al médico; pero don Pedro, con
malísimo talante, se opuso á tan descabellada idea, diciendo: «Si las
ganas de comer están ahora de menos, váyase por cuando han
estado de sobra.» Por las noches, no obstante su inapetencia, daba
prisa para que le sirvieran la cena; despachábala en un santiamén,
picando con el tenedor en éste y el otro plato, probando más bien
que comiendo, y parecía que le faltaba tiempo para echarse á la
calle.
—Estoy abotagado—decía,—y necesito mucho, mucho ejercicio.
Más que pictórico, estaba nuestro capellán desmedrado y
flatulento, como quien padece desgana ó insomnios. Y era verdad
que dormía poco, no cuidándose él ciertamente de halagar el sueño,
sino más bien espantándolo con sus lecturas á deshora, las cuales á
veces duraban hasta el amanecer. Habíase impuesto con rigor de
anacoreta la prohibición de leer historias de guerras y conquistas,
novelas, viajes y demás cosas incitativas de su espíritu activo;
ayunaba de aquel pasto heróico, y para dominarse y flagelarse y
someterse, apechugaba valeroso con los alimentos más desabridos
de la literatura eclesiástica. Por desgracia suya, pronto le faltaron las
fuerzas para esta cruelísima penitencia. Ni La Rosa mística
desplegada, ni el Imán de la gracia, ni el Mes de San José, ni otras
obras insípidas que tenía en su biblioteca, sin saber bien cómo
habían ido á ella, privaron por mucho tiempo en su espíritu.
Hastiadísimo, las confinó á un hueco de su estante, donde
probablemente estarían intactas hasta la consumación de los siglos.
Los grandes místicos se acordaban mal con su viril
temperamento, hostigado de inclinaciones humanas. No los
comprendía bien. Las sutilezas admirables de que tales libros están
llenos no le cabían á él en su tosco cacumen, molde de resueltas
acciones más bien que alambicados pensamientos; ni tampoco tenía
gusto literario bastante fino para poder saborear el gallardo y
elegante estilo de aquellos buenos señores. Los poetas sagrados se
le sentaban en el estómago (pase esta frase vulgar que él usaba con
frecuencia), y los versos de monjas le daban náuseas. No hallando á
dónde volver los ojos en el terreno de las lecturas, se amparó de la
Biblia. El Antiguo Testamento, sobre ser cosa muy santa, es poema,
historia, geografía, novela, poesía, drama, y la riquísima serie de sus
relatos enciende la imaginación, aviva el entusiasmo, embelesa,
suspende y anonada. Para llenar aquellos tristes vacíos de sus
insomnios. Polo cogía el Génesis, el Éxodo, los Números, los Jueces,
y se deleitaba con lo mucho que allí hay de trágico y sublime, con
las guerras, las intrigas, las conspiraciones, las conquistas, las
batallas, los grandes sacrificios, las violencias, los hechos inmensos,
los colosales crímenes y virtudes que allí se cuentan. Aquel estilo
sobrio, en que la frase parece producto inmediato del hecho que la
motiva, estaba en armonía preciosa con el genio esencialmente
activo de Polo. Porque él tenía en su espíritu el germen de los
hechos, lo que podríamos llamar impulso histórico; impulso y
germen que, aunque comprimidos por las contingencias de tiempo y
lugar, tenían cierta vida sofocada y dolorosa en el fondo de su alma.
Refiere Felipe Centeno que uno de aquellos días, hallándose en el
comedor limpiando cubiertos, doña Marcelina contaba con misterio á
la señora del fotógrafo una cosa estupenda y un si es no es
horripilante. Á media noche, la señora había sentido la voz de su
hermano, que gritaba con palabras descompuestas. Creyó al
principio que hablaba dormido; mas como sintiera los pasos de él,
sospechando que estaba enfermo, se levantó. Despavorido, cual si
se viera rodeado de fantasmas, salió el mísero capellán del cuarto,
los ojos inyectados, el habla torpe, los brazos trémulos, inseguro y
vacilante el pie. La vista de su hermana le serenó un tanto,
volviendo al cauce normal su razón desbordada; dejóse conducir al
lecho, y al sentarse sobre él, después de un breve espasmo, durante
el cual pareció resolverse la crisis, dió un suspiro, se pasó la mano
por la frente, y entre fosco y risueño dijo estas palabras: «El león
dormido cayó en la ratonera; despierta, y al desperezarse rompe su
cárcel de alambre.» Marcelina contaba á su amiga estos disparates,
vacilando entre reírlos como ocurrencias, ó lamentarlos como
señales de extravío mental. La digna esposa del fotógrafo, que tenía
sus puntas y recortes de médica, tranquilizó á Marcelina con estas
sesudas palabras:
—Eso no vale nada. Pero conviene prevenir... Créeme: tu
hermano debe sangrarse.
Precisamente en la mañana que siguió á la noche de referencia,
fué cuando el Doctor se espantó de ver á su amo: ¡tan desfigurado
estaba! Era su rostro verde, como oxidado bronce. Sus ojos, que
tenían matices amarillos y ráfagas rojas, recordaban á Centeno la
bandera española, y sus labios eran del color de la tela con que se
visten los obispos. Tuvo tanto miedo Felipe, que no se atrevió á
ponérsele delante. Aquella mañana don Pedro no quiso celebrar la
misa. Mandó un recado á las monjas diciendo que estaba malo, y
malo debía de estar, pues no probó bocado en todo el día,
desairando las fruslerías selectas que para engolosinarle inventó
doña Claudia.
Pero, no obstante su enfermedad, si alguna había, bajó á la clase
y fué más cruel y exigente que nunca. ¡Día de luto, día de ira! Las
lágrimas que corrieron fueron tantas, que con ellas se podrían haber
llenado todos los tinteros, si alguien intentara escribir con llanto la
historia de la desventurada escuela. Hasta los ojos de don José Ido
contribuyeron con algo al crecimiento de aquel caudal tristísimo. Los
chichones que se levantaban en ésta y la otra cabeza fueron tantos,
que era una erupción de cráneos. Las orejas crecían por pulgadas, y
poco faltó para que hubiera piernas rotas y espinas dorsales
quebradas por la mitad. Don Pedro, aquel constructor de jorobas
intelectuales, quería desfigurar también los cuerpos. Tenía como un
furor de odio y venganza. Creeríase que los muchachos le habían
jugado una mala pasada teniéndole por maestro. Doce ó catorce se
quedaron sin comer. Felipe estuvo aterradísimo todo el día, y evitaba
el mirar á su amo y maestro. También él se quedó en ayunas, y en
su mísero cuerpo no hubiera sido posible poner un cardenal más:
tan bien ocupado y distribuido estaba todo.
Por la noche, cuando se acostó, después de haber jugado un
poco al toro, dando testarazos á las imágenes, soñó diversas cosas
terroríficas. Primero, que don Pedro era el león de San Marcos y se
paseaba por la clase fiero, ardiente, melenudo, echando la zarpa á
los niños y comiéndoselos crudos, con ropa, libros y todo; segundo,
que don Pedro, no ya león, sino hombre, iba al convento y castigaba
á las monjas, cual hacía diariamente con los alumnos, dándoles
palmetazos, pellizcos, nalgadas, sopapos, bofetones y porrazos,
poniéndoles la coroza y arrastrándolas de rodillas.
Otra mañana, cuando limpiaba el cuarto del señor, vió en el suelo
pedacillos de papel. Sin duda don Pedro había pasado la noche
escribiendo cartas. Alguna le salió mal, y la había roto; pero los
trozos eran tan chiquirrititos, que apenas contenían un par de
sílabas. La vela estaba apurada, señal de haber pasado el señor
capellán la noche de claro en claro... Para que todo fuera extraño,
llegó también un día en que don Pedro estuvo tolerante y hasta
benignísimo con los muchachos. No solamente dejó de pegar y tuvo
en paz las manos en aquel venturoso día, sino que á cada momento
amenizaba las lecciones con chuscadas y agudezas. ¡Qué risas!
Nunca fueron humanas gracias más aplaudidas, ni con mayor
plenitud de corazón celebradas. Aún no había abierto la boca el
maestro, y ya estaban todos muertos de risa. Humanizada la fiera,
perdonaba las faltas, alentaba con vocablos festivos á los más
torpes, y los aplicados recibían de él sinceros plácemes. Hasta don
José Ido se permitió unir su delgada voz al coro de los chistes,
diciendo algunos que no carecían de oportunidad.
Para que en todo fuera dichosa aquella fecha, don Pedro comió
vorazmente; pero estaba tan distraído en la mesa, que no
contestaba con acierto á nada de lo que su madre y su hermana le
decían. Cuando se levantó para fumar, puso bondadoso la mano
sobre la despeinada cabeza de Felipe, y dijo estas palabras, que el
Doctor oyó con arrobamiento:
—Es preciso hacer á Felipe algo de ropa blanca.
Centeno, que mejor que nadie sabía cuán grande era su
necesidad en ramo tan importante del vestir, no tuvo palabras para
dar las gracias. ¡La gratitud le volvía mudo!
—¡Se le hará, se le hará!—afirmó doña Claudia, mirando
embobada á su hijo, pues desde que empezaron aquellos
desórdenes orgánicos, la madre no cesaba de leer atentamente á
todas horas en la fisonomía del capellán, buscando la cifra de sus
misteriosos males.
—Es preciso que te sangres, Pedro,—dijo Marcelina, mirándole
también con perspicaz cariño.
—Sí, hijo: sángrate, sángrate.
XII
De cuantos recados hacía Felipe, ninguno para él tan grato como
ir á la Cava Baja á recoger los encargos que traía para doña Claudia
el ordinario de Trujillo. Esto se verificaba dos veces cada trimestre, y
apenas la señora recibía la carta en que se le anunciaba la remesa
de chacina, ya estaba mi Doctor pensando en los deliciosos paseos
que tenía que dar. Porque doña Claudia era muy impaciente y le
mandaba cuando aún no había llegado el ordinario; con lo que la
caminata se repetía dos y hasta tres veces. Díjole, pues, una
mañana: «Esta noche, después de cenar, te vas corriendito á la Cava
Baja, ya sabes. Cuidado cómo tardas.»
Lo de tardar sería lo que Dios quisiera. Pues á fe que la tal calle
estaba á la vuelta de la esquina. Ya tenía Felipe para dos ó tres
horitas, porque la detención se justificaba con la enorme distancia y
con una mentirilla que parecía la propia verdad, á saber: que el
ordinario de Trujillo estaba en la taberna; que tuvo que ir á buscarle,
y volver y esperar...
Las nueve serían cuando partió, acompañado de Juanito del
Socorro, que fiel le esperaba en la puerta. En la redacción le habían
mandado á entregar unas pruebas en la calle de la Farmacia, recado
urgentísimo que él se apresuraba á desempeñar dando antes la
vuelta grande á Madrid. Lo que gozaban ambos en sus nocturnos
paseos no es para referido. Empezaron aquella noche por pasar
revista á los escaparates de la calle de la Montera, haciendo atinadas
observaciones sobre cada objeto que veían. Mirando las joyerías,
Felipe, cuyo espíritu generoso se inclinaba siempre al optimismo,
sostenía que todo era de ley. Mas para Juanito (alias Redator) que,
cual hombre de mundo, se había contaminado del moderno
pesimismo, todo era falso.
Esta diferencia de criterio revelábase á cada instante. Pasaban
junto á un coche descubierto que llevaba hermosas señoras, y el
Doctor, pasmado y respetuoso, decía:
—¡Buenas personas!... ¡gente grande!
—Pillos, hijí... Tú no tienes mundo... Esa es gentecilla. ¿Crees que
porque van bien vestidos...? Mamá, allí donde la ves, tiene vestidos
muy majos, y no se los pone nunca para que no la tomen por esas...
Cuando va á pasar el verano á las haciendas, se pone uno azul,
¿estás?...
Siguieron por la calle del Arenal adelante, despacito para ver bien
todo, estorbando el paso á las señoras y quitando la acera á todo
transeunte. El descarado Juanito no se privaba, cuando había
oportunidad para ello, de echar un piropo á cualquier mujer hermosa
que encontrase, ya fuera de clase humilde, ya de la más elevada.
—Hombre, que te van á pegar,—le decía el Doctor.
—Déjame á mí, hijí... que yo soy muy largo—contestaba el otro.—
¡Yo he corrido más!... tú no entiendes... ¡Si vieras á papá! Es un
buen peje para mujeres... En casa no hay criada que dure, porque
les dice cosas y les hace el amor... Mi madre se pone volada y las
despide. Cuando mi padre y mi madre riñen, sale aquello de que
papá quiso á la señá marquesa. Porque cuando era soltero... tú no
sabes... todas las marquesas se volvían locas por papá y por su
hermano, que era torero, y lo mataron en una revolución. Mi tío era
un gran hombre, un peje gordo... y se echó á la calle á matar tropa
por la libertad; pero le vendieron, y ese pillo de O’Donnell le mató á
él... Papá tiene su retrato en la sala, pintado de tamaño de las
personas, y á tantos días de tal mes, que es el universario, ¿estás,
hijí...? le pone dos velas encendidas y un letrero que dice: Imitaz á
este mártir.
Absorto oía Felipe estas maravillosas historias, no sin reirse
interiormente de la fatuidad de su amigo. En cuanto al legendario tío
de Juanito, torero, miliciano y mártir de la libertad, constábale ser
cierto lo del retrato de tamaño de las personas, porque lo había visto
con el mencionado letrero... En estos dimes y diretes, pasaban junto
al Palacio Real. Mudos contemplaron los dos un instante su mole
obscura y misteriosa, tanto balcón cerrado, tanta pilastra robusta,
las ingentes paredes, aquel aspecto de tallada montaña con la triple
expresión de majestad, grandeza y pesadumbre. Felipe miraba el
edificio en el imponente reposo de la noche, y como la primera
observación que hace el espíritu humano en presencia de estos
materiales símbolos del poder es siempre la observación egoísta, no
desmintió él este fenómeno, y dijo con toda su alma:
—Juanito, ¡si esto fuera mío!...
El otro, siempre tocado de un escepticismo postizo, le contestó
con desdén:
—Pues yo... para nada lo quería... Como no me lo dieran lleno de
dinero...
—¡Lleno de dinero!
Felipe se mareaba.
—¿Pues qué crees tú? Los sótanos están llenos de sacos de oro y
de barricas de billetes.
—¿Lo has visto tú?
—Lo ha visto papá...—afirmó el del Socorro, después de vacilar un
rato.—Papá conoce al... ¿cómo se llama? al entendiente, y algunos
días viene á ayudarle á hacer cuentas.
—Yo quisiera ver esto por dentro, ¿oyes? Será bonito.
—Hijí... no tienes más que decírmelo el día que quieras. Mamá
conoce á la gran zafata... ¿estás? la que gobierna todo, y cuida de la
ropa blanca y tiene las llaves. ¡Yo he venido más veces...! ¿Que si es
bonito dices?... Así, así... de todo hay... Tiene un salón más grande
que Madrid, con alfombras doradas, de tela como las de las casullas,
¿estás? El coche de la Reina sube hasta la propia alcoba... yo lo he
visto. Aquí todo está lleno de resortes. Calcula tú: tocas un resorte,
y sale la mesa puesta; tocas otro, y salen el altar y el cura que dice
la misa á la Reina... tocas otro...
Felipe, riendo, daba á entender que si tocaba más resortes, las
mentiras de su amigo no tendrían término. Pero acobardado Redator
por la incredulidad de Centeno, dejó correr sin tasa la inagotable
vena de sus embustes. Pasando calles, llegaron por fin á la Cava
Baja, donde Felipe no pudo cumplir su encargo, porque el ordinario
de Trujillo no había parecido aún. Bien: ya tenía para otra noche. Era
ya tan tarde, que los amigos sintieron un poquito de recogimiento y
estrechura en las respectivas conciencias, aunque la de Juanito del
Socorro era más ancha que la puerta de Alcalá, y por ella cabían las
más grandes faltas sin doblarse ni romperse. Emplear dos horas en
un recado urgentísimo, para el cual le habían señalado veinte
minutos, era cosa muy adecuada á un carácter tan entero como el
suyo. Ya sabía que cada minuto de más le valía igual número de
golpes de su papá; pero tenía la piel curtida y el espíritu fortificado
por las contrariedades.
—Vamos, vamos—dijo Felipe inquieto.—Es muy tarde.
Apresuradamente corrieron hacia los barrios del Norte, y aunque
Juanito quería detenerse á oir los cantos de Perico el ciego, el Doctor
tiraba de él y á prisa le llevaba. Llegaron por fin á la calle de la
Farmacia, donde Redator debía entregar su encargo, y mientras éste
subía al piso tercero del núm. 6, vivienda del infelicísimo escritor que
desde las nueve estaba esperando sus pruebas, Felipe se paseó en
la acera de enfrente, entre la Escuela y la esquina de San Antón.
Como en todo se fijaba, observó que junto á una de las rejas bajas
del edificio había un bulto, un hombre con las solapas del gabán
negro de verano levantadas... Al pasar, Felipe notó un cuchicheo;
miró... Aunque la noche estaba obscura... ¡sí, sí, era él!... Felipe se
estremeció, embargado de grandísima sensación de pavor y
vergüenza. Sintió el ardor de la sangre en su cara hasta la raíz del
cabello... ¡Era, era don Pedro!
Siguió adelante, y pronto hubo de unírsele Juanito, á quien
comunicó sus impresiones. Su amigo le dijo:
—Vamos á pasar otra vez.
Lleno de terror, Felipe se agarró al brazo de su amigo para
detenerle, y le decía:
—¡No, no, no; pasar no!
Pero más pudo la maliciosa sugestión del pícaro que el miedo del
Doctor, y pasaron otra vez. En el momento mismo, el bulto se apartó
de la reja. Felipe y él se encontraron frente á frente, y se vieron...
¡Era, era!
La vacilación de don Pedro fué instantánea. Siguió su camino.
Tras él, á mucha distancia, iban Felipe y su amigo: aquél tan
turbado, que no sabía por dónde caminaba; éste haciendo
comentarios sobre lo que habían visto.

You might also like