0% found this document useful (0 votes)
12 views88 pages

Basicsynth 1st Edition Daniel R Mitchell Instant Download

BasicSynth, authored by Daniel R. Mitchell, is a comprehensive guide to creating a music synthesizer in software, covering various synthesis techniques and programming methods. The book includes practical examples and code implementations, aimed at helping readers understand sound generation and processing. It emphasizes the importance of both technical knowledge and musical creativity in synthesizer design and usage.

Uploaded by

buratothein35
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views88 pages

Basicsynth 1st Edition Daniel R Mitchell Instant Download

BasicSynth, authored by Daniel R. Mitchell, is a comprehensive guide to creating a music synthesizer in software, covering various synthesis techniques and programming methods. The book includes practical examples and code implementations, aimed at helping readers understand sound generation and processing. It emphasizes the importance of both technical knowledge and musical creativity in synthesizer design and usage.

Uploaded by

buratothein35
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

Basicsynth 1st Edition Daniel R Mitchell

download

https://ebookbell.com/product/basicsynth-1st-edition-daniel-r-
mitchell-22714722

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Basicsynth 1st Edition Daniel R Mitchell

https://ebookbell.com/product/basicsynth-1st-edition-daniel-r-
mitchell-22714722
BasicSynth
Creating a Music Synthesizer in Software

Daniel R. Mitchell
BasicSynth: Creating a Music Synthesizer in Software
by Daniel R. Mitchell

© 2008 Daniel R. Mitchell

All Rights Reserved

ISBN: 978-0-557-02212-0

First Edition

http://basicsynth.com
Table of Contents

Preface ..............................................................................................5
Synthesis Overview..........................................................................8
Sound in Software ..........................................................................16
From Equation to Code ..................................................................22
Output File Format .........................................................................32
Signal Generator.............................................................................37
Envelope Generators ......................................................................43
Complex Waveforms......................................................................64
Wavetable Oscillators ....................................................................80
Mixing and Panning .......................................................................95
Digital Filters................................................................................102
Delay Lines ..................................................................................118
Reverb ..........................................................................................129
Flanging and Chorus ....................................................................136
Synthesis System Architecture.....................................................139
Sequencer .....................................................................................142
MIDI Sequencer ...........................................................................155
Immediate Sound Output .............................................................172
Instrument Design ........................................................................181
Additive Synthesis Instrument .....................................................197
Subtractive Synthesis Instrument .................................................202
FM Synthesis Instrument .............................................................205
Wavefile Playback Instrument .....................................................214
Eight Tone Matrix Instrument......................................................220
Notelist .........................................................................................229
Notelist Interpreter Implementation .............................................262
BSynth ..........................................................................................271
BasicSynth Library.......................................................................275
Further Development....................................................................282
References ....................................................................................284

3
Dedication

I have had many good teachers over the years, each one adding
something to my understanding. But there was one teacher in
particular that shaped my understanding of music more than any
other. From January 1980 until his death in the summer of 1981, I
studied composition and electronic music with Merrill Ellis. It was
one of those rare occurrences where teacher and student “clicked” and
my abilities as a composer increased rapidly during that relatively
short period. Merrill Ellis was a first-rate composer, an exceptional
teacher, and a true pioneer in the field of electronic music. More
important to me personally, it was Merrill Ellis that encouraged me to
hear with the inner ear that is the heart and soul of a musician, and
helped me develop the confidence I needed to write what I heard.
This book is filled with technical details out of necessity. Without
them we could not implement a working synthesizer. Unfortunately,
the technical nature of electronic and computer music can be
dangerous to a composer. We can get caught up in the equations,
algorithms and clever programming techniques to the point we forget
what it is all about. When reading this book, it is good to remember
what Mr. Ellis taught me shortly before he passed away:

When making music, it doesn’t matter what you do or how you do


it…as long as it sounds good.
Preface

My first exposure to synthesized sounds was through the Switched on


Bach recordings by Walter Carlos. Those recordings opened up a
whole new world of sounds for me. My fascination with synthesized
sounds eventually led me to build my own synthesizer from a PAIA
kit. It wasn’t much of a synthesizer. I had one VCO, one VCA, one
VCF, AR envelope generator, LFO and keyboard, and soon
discovered that without a multi-track recorder there wasn’t much I
could do except make interesting sound effects. Nevertheless, that
little synthesizer allowed me to gain an understanding of how
synthesizers make sounds. A few years later I enrolled for graduate
study at the University of North Texas and was able to work with two
powerful synthesizers, a Moog analog synthesizer and a Synclavier II
digital synthesizer.
Later, after I had left school and begun work as a computer
programmer, I began to purchase my own synthesizers. A bonus
check from my job was spent as a down payment on a Yamaha DX7,
a remarkable synthesizer for its time. Hooked up to my Commodore
C64 computer through a home-built MIDI interface, it gave me a way
to continue to use computers and synthesizers to make music. Not
having any commercial music software available, I wrote a simple
sequencing program named Notelist. Notelist didn’t do much more
than convert text into MIDI events, but it became the foundation and
starting point for the score language described later in this book.
Eventually the keyboards were set aside in favor of software
synthesis using Barry Vercoe’s CSound, a direct descendant of the
original software synthesis system, MUSIC by Max Matthews. As
flexible and powerful as a program like CSound is, I always missed
the interactive creation of sound through a keyboard like the DX7.
Being able to hear how the tweaks affect the sound is very useful. I
eventually decided to create some synthesis software routines so that I

5
6 Preface

could get a more immediate result. The software in this book is a


direct outgrowth of that endeavor. Just as I discovered when building
my own synthesizer as a teenager, I found that having to program the
synthesis system myself improved my understanding of the
underlying equations and algorithms that are used to create sound on
a computer. Hopefully, documenting how I went from simple sound
generators to complex instruments will help others gain a better
understanding as well.
A variety of software synthesis systems with large libraries of
patches and almost unlimited sequencing are now available for a
home computer. These systems are inexpensive, produce high quality
sound, and can make music synthesis relatively easy even for those
with limited knowledge of computer programming or digital signal
processing. With all of that capability readily available it may seem
that creating a synthesizer of your own is a lot of unnecessary work.
However, just because you have a thousand patches in your sound
library doesn’t mean you have the sound available that you hear in
your head. If the synthesis system won’t allow you to easily change
patches, or you don’t understand how tweaking the controls will
change the sound, you can get stuck. The more you know about how
the synthesizer works, the better chance you have of realizing what
you hear in your mind. But, even if you know how you want to
produce the sound, the software may not provide a convenient way
for you to do so. Having your own synthesis software available
allows you to extend and adapt it to fit your particular needs.
Sound generation software can also be used to enhance a wide
variety of computer applications. For example, an interactive music
tutorial needs to produce sounds beyond playback of recordings.
Computer game programming is another application that can benefit
by having the ability to generate sound directly. There are potentially
many such applications for sound generation, if you have the right
software libraries available to you as a programmer. A commercial
software synthesizer, or an existing library, may not be in a form you
can easily adapt to your application. For that you need your own
sound generation library.
If you are not an experienced programmer, developing your own
synthesizer in software may seem like an unrealistic goal. Although
both sound generation and sound modification are well described by
the mathematics of digital signal processing (DSP), if you browse
BasicSynth 7

through a book on DSP your first impression is likely to be, “it’s


incomprehensible.” Fortunately, it turns out that most of what we
need to know to generate sound on a computer is very easy to
understand.
It is not the purpose of this book to describe signal processing
theory or synthesis techniques in detail. In the case of signal
processing, we can take it for granted that the mathematicians and
engineers got it right, and use the derived equations. Likewise, this
book does not explore any new or original methods of sound
synthesis. The examples shown in this book are the way most
synthesis software is implemented and has been implemented since
the 1960s. Instead, the primary purpose of this book is to understand
and address the practical problems of programming the sound
generation routines and combining them in a way to produce an
efficient working synthesizer.
Each chapter begins with an introduction to the necessary theory
and then proceeds to develop actual programs to implement the
theory. The first chapters concentrate on sound generation and
processing functions. Later chapters use the sound generation and
processing code to develop instruments that implement various
synthesis methods. An example score language is then described and
combined with the synthesis instruments to create a complete
synthesizer.
In order to use the information in this book you will need to
understand basic algebra and trigonometry and some basic computer
programming techniques. Significant features of the software are
discussed, but for the most part it is assumed that you can read the
example code and understand it. The examples in the book are shown
in C++ but can be adapted to most computer programming languages.
In addition, the examples are fragments of code with variable
declarations, data type conversions, and error checking left out. The
complete source code is available on-line and should be downloaded
and studied along with each chapter. The example source code is
available at http://sourceforge.net/projects/basicsynth for download.
The latest information on the source code is available at
http://basicsynth.com.
Chapter 1
Synthesis Overview

The sounds we hear are the result of a mechanical vibration that


creates pressure waves in the air. Sound synthesis refers to the
creation of sounds by some electronic means, either electronic circuits
that directly generate electrical signals, or a computer that calculates
the amplitude values for the signals. When the electronic signals are
sent to a loudspeaker, they are converted into a mechanical vibration
that produces sound.
When we say that something is synthetic, we mean that it is a
replacement for a natural substance or process. Likewise, many
musicians consider a synthesizer to be substitute for traditional
musical instruments or other physical devices that make sound.
However, we can also think of a synthesizer as a musical instrument
in its own right with the goal of producing sounds that could not
otherwise be heard. Both views are valid, and a well designed
synthesizer can be used for both purposes. Fortunately, the software
routines used to imitate natural sounds are the same as those used to
produce completely new sounds.
We can think of a synthesizer as either a performance instrument
or as a compositional tool. When used for performance, the focus of
the instrument is on real-time response to the musician and we want
sounds to occur immediately when we press a key on a keyboard,
vary a control, or strike an input pad. Because it requires immediate
response, a synthesizer used for live performance will usually have a
limited range of sounds available at any moment and also be limited
in the number of simultaneous sounds it can produce. When used as a
compositional tool, the synthesizer does not have to respond in real-
time, and can therefore be used to generate almost any sound the
musician can imagine. In addition, the synthesizer can generate

8
BasicSynth 9

complex polyphonic textures that would be next to impossible for


human players to perform. The compositional tool approach requires
some kind of automated sequencer that controls the selection of
instruments and their performance. In effect, the synthesizer becomes
an “orchestra in a box” with a computer acting as both conductor and
performer. However, the synthesizer does not have to be limited to
one or the other use. A synthesizer designed mainly for live
performance may also include a sequencer for automated playback.
A synthesizer can be designed to have a fixed number of easy to
use preset sounds, or can be designed for maximum flexibility in
sound generation. Preset synthesizers are usually intended for live
performance, but are sometimes useful for quick composition as well.
With a large library of preset sounds, the composer can spend more
time on arranging the sounds as opposed to creating new sounds.
Synthesizers with maximum variability in sound generation require
the musician to set numerous parameters of each instrument and are
usually intended as composition or research tools.
We can also consider a synthesizer to be replacement for a
traditional musical instrument. This is often the case when a
composer wants to preview a composition that is intended for
performance by human players on traditional musical instruments. It
can also be the case when the synthesizer is used to reduce the cost of
commercial music production. In contrast, the synthesizer can be
viewed as an instrument in its own right, and may be used stand-alone
or combined with traditional musical instruments to create an
ensemble.
Combining the various features listed above, we can produce a
diagram showing potential synthesizer applications. Where we locate
the synthesizer application on this diagram will determine the set of
features that are most important in the design of the synthesizer (See
Figure 1 below).
At the top of the circle, we have a combination of features suited
to an instrument that can switch quickly between a limited number of
emulated sounds. Such an instrument may be performed live, or set
up with sequences much like an electronic player piano, but is mainly
used for the purpose of duplicating several instruments in one. An
electronic piano that can also switch to an organ or harpsichord sound
is one example. Along the right side are applications such as
commercial film and video production where the musician needs to
10 Synthesis Overview

produce sound effects, reproduce traditional musical instrument


sounds at low cost, and also be able to closely synchronize the music
with images. The left side area fits well with small ensemble and
recording studio applications where the range of sound varies from
traditional to new, but is typically performed live. Along the bottom
of the circle we have a combination aimed more towards composition
of purely electronic music and research into new synthesis
techniques.

Natural Sound
Emulation
Traditional
Instrument
Preset Replacement

Performed Sequenced

New Instrument
“Synth gratia Configurable
Synthesis”
Sound Creation

Figure 1 - Synthesizer Applications

An advantage of a software synthesis system, as opposed to a


hardware synthesizer, is that it can potentially sit right in the middle
of the circle. Such a system would be quite large and require
considerable forethought, but is not beyond the capabilities of a
typical personal computer. More commonly, the programmer will
have in mind a specific application and design the synthesis system
around those specific needs.

Synthesis Methods

Over the years many sound synthesis techniques have been


developed, each with unique advantages and disadvantages. In many
BasicSynth 11

cases, the synthesis technique grew directly from the technology


available at the time. Although this book is not intended as a tutorial
on synthesis techniques, it is useful to review the most basic
techniques in terms of possible software implementation so that we
have a starting point for development of the synthesizer.
Additive synthesis creates complex sounds by adding together
more than one signal. Usually, although not always, each signal is a
simple sinusoid waveform with each sinusoid defined by relative
frequency, amplitude and phase. When the signal amplitudes are
relatively close to each other we hear a combination of tones.
However, when the relative amplitudes of the higher frequencies are
small compared to the lowest frequency, the signals blend together
and we hear a single complex tone. The frequencies and amplitudes
of the signals used for additive synthesis are often determined by
analysis of recorded sounds with the goal of reproducing those sounds
as exactly as possible. Additive synthesis can also be done “by ear”
by interactively adjusting the frequency and amplitude values of each
sinusoid until the desired sound is heard. Additive synthesis is the
most straight-forward synthesis method, but requires a large number
of signal generators to be usable. In the past, this requirement
prevented additive synthesis from being widely used. However, with
the ability to generate signals in software, we can implement additive
synthesis methods very easily by running the same signal generator
routine multiple times. The only additional cost for each signal is the
time it takes to execute the signal generator software.
Subtractive synthesis is the inverse of additive synthesis. Where
additive synthesis builds up a complex waveform one signal at a time,
subtractive synthesis starts with a complex waveform and then
attenuates frequencies by filtering the waveform. Subtractive
synthesis requires only a few signal generators and filters to produce
sounds similar to an additive synthesis system requiring many signal
generators. For that reason it was the preferred method in early
synthesizer design. A software synthesis system can easily produce
complex waveforms and filters for use in subtractive synthesis.
However, it is difficult to exactly reproduce a natural sound by
filtering alone. Consequently, subtractive synthesis is more
commonly used to generate unique electronic sounds.
FM and AM synthesis, distortion synthesis and non-linear
synthesis are all variations of the same basic technique. Modulation
12 Synthesis Overview

involves continuous variation of one signal (the carrier) by another


signal (the modulator). When both the carrier and modulator are in
the audio frequency range, the two signals combine to produce sum
and difference tones that sound similar to a sum of sinusoids. The
spectrum that results from modulation can be as complex as a sum of
dozens of individual sinusoid signals. Changing the amplitude and
frequency relationship of the signals produces nearly unlimited
variety of sounds. Because this technique requires so few signal
generators, and produces such a wide range of sounds, it has been
widely used in both analog and digital synthesizers. However, the
complex interaction of the modulator and carrier creates a frequency
spectrum that is difficult to control precisely and traditional signal
synthesis based on spectrum analysis does not easily translate into a
set of carriers and modulators. The relationship of the carrier,
modulator and resulting spectrum is anything but intuitive.
Consequently, simulating natural sounds with modulation is usually
done by tweaking the modulator and carrier until an acceptable sound
is heard. However, the ability to create very unnatural sounds makes
non-linear synthesis especially appropriate for creating new and
unusual sounds.
Wavetable synthesis is a technique that sits somewhere between
additive and non-linear synthesis. Like additive synthesis, the
wavetables combine to produce complex sounds. However, the
transition from one waveform to another is a result of modulating
multiple wavetables with a non-periodic function. Put another way,
wavetable synthesis “morphs” the waveform between several sounds.
Wavetable synthesis can use pre-recorded sounds to fill the
wavetables. However, this introduces the same difficulties as a
sampling system (see below). The main advantage of wavetable
synthesis is that it allows a dynamic spectrum with only one signal
generator constructed from a set of phase integrators. That advantage
is less important when the signal generator exists only in computer
memory. Nevertheless, wavetable synthesis can be implemented
fairly easily in software, and is a good addition to a software synthesis
system.
Granular synthesis is a unique, and specialized, synthesis
technique. It produces a varying sound by stringing together very
short sounds, often only a few milliseconds in length. The effect can
be anything from a “bubbling” sound to a sound that slowly shifts in
BasicSynth 13

timbre over time. Granular synthesis was developed originally by


physically splicing together small segments of sound recordings. The
same technique can be performed very easily in software by
concatenating recorded sounds, but can also be extended to use grains
directly created with software signal generators.
A sampler synthesis system uses recorded sounds instead of
internally generated waveforms. Such a system can get very close to
exact reproduction of natural sounds. However, there are some limits
that complicate a sampler system. If we only need to generate a sound
effect, such as a buzzer or bell, the program is very simple. However,
to reproduce musical instruments, the pitch, duration and timbre of
the sound need to be variable. This introduces several potential
problems. First, we need to know the fundamental frequency of the
signal and analyzing an arbitrary signal to determine the actual pitch
can be difficult. Second, changing the pitch by playing the recording
at different rates introduces changes in envelope and spectrum of the
signal. In addition, a sampler must be able to loop over the sustained
portion of the sound without producing discontinuities in the
waveform. Consequently, different recordings are used for different
ranges of the instrument’s sound, and the attack and decay portions of
the sound are handled separately from the sustain portion. In short, a
complete sampler requires many sound files and very careful
preparation of the files in order to be usable. Implementing playback
of the recorded sounds is easy, but creating a good set of sounds is
very difficult.
A newer and potentially very powerful synthesis technique is
known as physical modeling and waveguide synthesis. Rather than
trying to analyze and then reproduce the spectrum of a sound,
physical modeling creates a model of the sound as a combination of
impulses, resonators and filters. In theory, any sound that can be
produced by initiating a vibration in some physical object can be
modeled in this manner. The basic software functions needed to
model the sound are surprisingly simple. This is a method that has a
great deal of potential, but one that also requires a significant amount
of analysis of the sound and its controlling parameters.
Any or all of these common synthesis techniques can be used for
any application described above. However, some synthesis techniques
are more appropriate to each category than others. For example,
additive synthesis usually requires the greatest number of calculations
14 Synthesis Overview

and is thus more appropriate for creating sound files for playback than
live performance. In contrast, FM synthesis can produce a wide
variety of sounds with a relatively small number of calculations and
works well for both pre-recorded sound and live performance.
Subtractive synthesis, along with wavetable distortion, granular
synthesis and related techniques, are good for producing very
distinctive artificial sounds, and, although they can simulate natural
sounds, are better suited to new-sound categories than emulation of
natural sounds. Sampled systems, physical modeling and waveguide
synthesis are focused on efficient simulation of natural sounds, but
can also be used to create arbitrary and artificial sounds if appropriate
adjustable parameters are provided.

Expressive Music Synthesis Systems

The discussion above, like most writings on music synthesis,


concentrates on methods for producing sounds. This is understandable
since the unique feature of a synthesizer is its ability to produce a
wide range of sounds from one instrument. Unfortunately, there is
another important feature of a music synthesizer that often gets
ignored.
Music is more than interesting sounds. Interesting music has an
almost mystical quality that we call expressive. Sounds performed on
traditional instruments are not static, but vary from note to note and
over the duration of a single note as the performer varies the sounds
during performance and from one performance to another. To get the
same musical expression, a musician using a computer synthesis
system needs more than a large catalog of interesting sounds. He must
also have a way to control the expressive aspects of the composition.
In traditional music notation, this can be done with a few short
instructions to the performer, such as dynamics, tempo changes,
accents, etc. We need something analogous for our computer music
system if we want to create expressive music with it.
This is the area where synthesis systems most often fall short. The
synthesizer is capable of producing a vast range of interesting sounds,
but the musician or composer cannot easily introduce all the subtle
variations to the sound that make the music expressive. Keyboard
synthesizers have improved considerably in this area through the use
of velocity and touch sensitive keyboards. However, trying to
BasicSynth 15

simulate all of the subtle variations of performance in software


requires considerable effort and can be tedious. As a result, many
software synthesis systems rely heavily on input from keyboards or
other devices rather than providing a pure software solution.
Furthermore, it is not intuitively obvious how changing a parameter,
such as the value that controls the attack rate of an envelope
generator, will affect the musical expressiveness. When we construct
a synthesizer in software, with the computer acting as performer, we
have to be aware of the need to be able to parameterize these subtle
interactions between musician and sound in such a way that they are
both available and meaningful for musical expression.
Whatever the application or synthesis technique, all synthesis
systems rely on a common set of sound generation and processing
functions that can be combined in various ways. The first section of
this book steps through the process of understanding and creating
those basic sound generation and processing functions. Later, we will
look at designing instruments and automatic sequencing of the music
with the goal of producing a synthesizer suited to expressive music
composition. The additional features needed for simulation of
traditional sounds and live performance are not covered in detail.
However, the synthesis system described in this book can be extended
to include those features.
Chapter 2
Sound in Software

We can represent any audio signal as a set of discrete values if we


make each value a sample of the amplitude of the signal at a discrete
time and make the time between samples a constant interval. This
process, called quantization, is shown in the following figures. Figure
2 shows an input signal, in this case a sine wave.
Amplitude

Time

Figure 2 - Continuous signal

We can sample the amplitude of the signal at a regular interval to


obtain the instantaneous amplitude values shown in Figure 3, and
store those values in a computer file.
Amplitude

Time

Figure 3 - Sampled waveform

16
BasicSynth 17

The recorded samples can later be sent through a digital to analog


converter (DAC) to produce a varying voltage that will drive an audio
amplifier and loudspeaker. The output from the DAC is a series of
steps as shown in Figure 4. When the stepped output is passed
through a smoothing filter, the final output is a continuous signal, as
was the original input signal.
Amplitude

Time

Figure 4 - Sample Output

The representation of a signal by a set of samples equally spaced


in time is the foundation of digital audio systems, including both CD
audio and digital sound synthesizers. Since the sound is represented
by a set of numbers, a computer can also calculate the sample values
directly rather than by sampling an analog input signal. Simply put, a
digital sound synthesizer produces sound by generating a series of
samples representing the instantaneous amplitude of the signal at a
constant time interval. Samples can be directly calculated, taken from
a recorded sound, or any mixture of the two. In addition, samples can
be processed with filters and other sound effects by direct calculations
on the samples. Thus a digital synthesis system can produce a wide
variety of sounds, both natural and artificial, limited only by capacity
of the computer system and the imagination of the musician.

Time and Amplitude

Before proceeding to develop sound generation software, we need to


select the time interval between samples and the representation of
amplitude.
Frequency (what musicians call pitch) is specified in cycles per
second, abbreviated Hz. If we have a signal at 100Hz, the cycle
repeats 100 times per second. Thus the time of one cycle (or period)
is the inverse of the frequency, 1/100 sec. Consequently, we can
18 Sound in Software

express frequency as either f or 1/t, where f is the frequency and t the


time of one period. Given a time interval between samples, or sample
time, the frequency of the samples, the sample rate, is the reciprocal:
1
ts  (2.1)
fs
1
fs  (2.2)
ts
The sample rate will ultimately determine the range of frequencies
we can produce. In order to represent a periodic signal, we need at
minimum one value above and one value below the zero level of
amplitude for each cycle. In other words, we need at least two
samples per cycle:
1 1 f
f max    s (2.3)
tmax 2t s 2
The frequency at one-half the sampling rate is called the Nyquist
frequency, or limit. For the sample rate, we must choose a value at
least twice the highest frequency we want to reproduce. The accepted
upper limit for audible sound is around 20,000Hz. In fact, most adults
can’t hear much above 12,000Hz, but the 20,000Hz upper limit is
typical for audio equipment specifications and makes a reasonably
good maximum. Any sampling rate over 40,000Hz will be able to
represent the audio frequency range.
Sampling rates higher than the minimum do have some benefit,
however. If we resample a digital sound file, we can change the
frequency of the sound. But changing the frequency in that way
means that we have to interpolate or discard some samples. If the
sound is recorded at a minimum sampling rate, we can end up with
distortion, noise, and a poor representation of higher frequencies. The
same is true for signals that we generate internally. It might be a
benefit, therefore, to have a higher internal sampling rate and also to
be able to generate and read sound files at higher rates. Nevertheless,
an equally important consideration is compatibility with existing
audio equipment and software. The sample rate of 44,100Hz is
currently the standard for both CD audio and computer sound files.
That is the sample rate we will want to produce at the output of the
BasicSynth 19

program. If we are careful in our program design, we can change the


sample rate at any time, or use a higher rate internally and only
convert to the standard rate when we write out samples.
Almost all of our time values are non-integer values and we need
to choose a data type to represent time that can represent both
fractions of a second and the multiple-seconds duration of music.
Normally this means using a floating point representation for
duration, but a fixed point representation can also be used.
The number of samples we generate for a given sound is the
duration in seconds multiplied by the sample rate. Internally, we need
to convert time into a sample number. The sample number is the time
in seconds multiplied by the number of samples per second.
S  T  fs (2.4)

Since we cannot generate a fraction of a sample, we can use an


integer value to represent sample numbers. If we use a 32-bit signed
integer, we can represent up to 231-1 samples. At a rate of 44,100
samples per second, that would be enough to represent a duration of
48,695 seconds, or about 13.5 hours. A 64-bit integer or a double
precision floating point data type could represent durations much
longer than that if needed, but in most cases a 32-bit value is
sufficient.
To choose a representation for amplitude, we have to think in
terms of the precision needed to accurately represent the dynamic
range of audio signals. The nominal range for the data type is not
critical since we can always normalize the values and treat the
maximum value as 1 and the minimum value as -1. In fact,
normalization to the range of [-1,+1] is typical for many of the
equations used to represent periodic signals. Trigonometric functions,
for example, are defined in terms of a unit circle. However, the
number of bits we use to represent amplitude significantly affects the
accuracy of our amplitude values. Given n bits in our computer data
type, we can only represent 2n different values. If we need to
represent signed values, our absolute value is limited to 2n-1.1 For

1 Rigorously defined, the range is [-2n,+2n-1] due to the anomaly of “minus


zero” sitting in the middle of a twos-complement representation.
Programmers generally ignore that slight discrepancy, however, and think in
terms of the positive magnitude as the limit for both positive and negative
20 Sound in Software

example, if a 16-bit word is used, the sample value can represent


65,536 different amplitudes. Since the amplitude is both positive and
negative, the amplitude is limited to ±32,767 steps. Any amplitude
values that fall in between those steps will be slightly inaccurate. An
inaccuracy in the amplitude value is known as quantization error and
is the digital equivalent of noise and/or distortion in the signal. The
more bits we use, the more accurately we can represent the amplitude,
and the less noise we will introduce into the signal. We need to be
sure we choose a word size that will be practical, yet limit noise to an
acceptable level.
A good way to analyze the requirement for amplitude values is to
consider the dynamic range of hearing. We want to have a dynamic
range that can represent what we can hear, and, if the range is large
enough, the noise level will be small enough that it won’t have a
significant effect on the audio quality. The range of hearing is quite
large, a ratio of about 1012 to 1. Fortunately, the number of discrete
steps in amplitude we can detect is considerably smaller. For this
reason, amplitude is represented using a logarithmic scale known as
the decibel scale. The decibel scale uses 1dB to represent the average
smallest change in amplitude we can hear. A decibel is defined as:2
AdB  20 log10 ( A1 / A0 ) (2.5)

Each bit in a data word represents a power of 2 increase in range.


Thus a one bit value can represent 20 log10(2/1)  6dB. Each
additional bit adds 6dB to the dynamic range (peak-to-peak). An 8-bit
sample size would only produce 48dB dynamic range. A 16-bit value
would give us 96dB, while a 32-bit sample size would provide
192dB. Since the dynamic range of music is around 100dB, the 16-bit
value is very close to what we need. A 16-bit sample size is also the
standard for commercial digital audio at the present time. Systems
that use larger word sizes do gain a benefit by minimizing
quantization error during calculations and thus potentially have lower
noise in the signal. As with sampling rate, we can use one
representation internally and convert to the standard on output.

values.
2 There are actually two dB scales, one for power ratios and one for

amplitude ratios, but the one for amplitude ratios is what concerns us.
BasicSynth 21

When calculating samples it is necessary to add, subtract, multiply


and divide values before reaching the final output sample. If we use a
16-bit integer internally, any fractional portion of the value is lost and
it will be difficult to perform calculations without losing significant
information. Thus we should use a floating point representation
during calculations. Double precision floating point provides the
greatest precision, but takes more processor time and memory. Single
precision floating point produces nearly the same quality of samples,
but consumes considerably less memory and processor time.
Chapter 3
From Equation to Code

Both periodic signals and digital signal generation are well defined
mathematically and the necessary equations can be found in any DSP
text. What is not always well described in those texts, and may at first
seem incomprehensible, is how to convert those equations into a
useful synthesizer program. However, as you will see, the equivalent
program functions are usually short and simple. The complexity in a
synthesis system is in the combinations of the basic functions
(architecture), not the functions themselves. For sound generation
functions, a few general rules for conversion can be developed that
will work in almost all situations.
Good programming practice dictates that we write code that is
clear and obvious, test for valid memory locations before writing to
variables, and test for valid ranges of values during execution of the
program. However, if we are not careful, following these practices
can add an excessive amount of execution time to the program.
Consider a synthesizer program to be constructed as two loops, an
outer loop and an inner loop. The outer loop performs setup and
initialization for each sound, while the inner loop generates the
samples for the sound.

initialize for sound generation


for each sound
initialize values for this sound
for each sample
generate and store the next sample

At a sample rate of SR samples per second, the inner loop will be


executed SR times for each second of each sound. Suppose we want
to play N sounds with an average duration of one-half second each.

22
BasicSynth 23

The outer loop is executed N times, but the inner loop is executed
N·(SR/2) times. The inner loop is obviously more critical to the
execution speed of the program, and moving even a few instructions
from the inner loop to the outer loop can significantly improve the
program’s execution speed. In general, we should precalculate as
many values as possible and perform any range testing or other
validation before executing the inner loop.
Most algebraic equations can be directly converted into a
computer program statement. In general, we replace the variables in
the equations with program variables and convert the operators into
the program language equivalents. For some equations, especially
periodic functions and series, we must write several program
statements to implement the equation.
The first implementation step is to define the program variables
that represent the variables in the equation. By convention,
mathematicians use single letter variable names such as x and y to
represent variable quantities. Many signal processing equations use x
to represent time and and y to represent amplitude. However, when
the equations represent processing an input signal, x represents the
input and y represents the output, both of which are amplitude values.
When writing a computer program, we are applying the equation to a
specific case and can use names or abbreviations such as amplitude,
sample and duration instead of x and y. Using the longer names will
make the program easier to understand.
When defining variables we need to select an appropriate data
type. Obviously, we use floating point types (float, double) when a
calculation can produce a real value, and integer types (short, int,
long) when only integer values are needed. The built-in type names
are not always the best choice, however. When we see a variable of
type float we don’t immediately know if the variable refers to
amplitude, time, or something else. For key data types it is helpful to
define aliases for the types. For example, we could use PhaseValue
for a signal phase and AmpValue for a sample amplitude rather than
declaring the variables as float. Using aliases for types makes it easier
to change from one internal representation to another. For example, if
we later decide to use double precision instead of single precision
floating point types for amplitude values, we only need to change the
code where the alias is defined. Not all programming languages allow
24 From Equation to Code

aliases for data types, but the C++ language used for the examples in
the book provides several ways to do this.
We can replace the arithmentic operators for addition, subtraction,
multiplication and division with the programming language
equivalent (+ - * /). Some operators used in the equations may not be
defined by the programming language, but are usually available as a
library function. For example, exponentiation of the form y=an is
implemented in C++ as y=pow(a,n). Likewise, trigonometric
functions and logarithms convert into library function calls.
The equal sign (=) in an equation represents equality, but in C++
the ‘=’ operator represents assignment, while the ‘==’ is used for
comparison. Not all equal signs in the equation represent assignment,
and the appropriate C++ operator must be selected. When ‘=’ is used
in an equation to show that a value is the result of a function or
calculation, we use the assignment operator in C++.
Some symbols used in mathematics don’t have a direct equivalent
in C++ and we must write a series of statements to implement them.
Equations using summation are very common in signal processing.
100
y   f ( n) (3.1)
n0

Summation is implemented by a loop that repeatedly calls the


function f with the limits used to set the values for the loop condition.

for (n = 0; n <= 100; n++)


y = f(n);

We will sometimes see a limit in an equation expressed as N-1. In


that case we can use the less-than operator and compare against N
rather than perform the subtraction of 1 from N on every iteration.
We also implement a series using a program loop. For example,
consider a simple arithmetic series.
y  n  x, n  0...m (3.2)
This equation can be implemented as a program loop that
repeatedly multiplies the value of x.

for (n = 0; n <= m; n++)


y = n*x;
BasicSynth 25

When possible, we should convert a series to the equivalent


recursive form. The recursive form will almost always produce a
more efficient program. Conversion to the recursive form is done by
expanding the series, regrouping the terms, and substituting a group
with a prior value.
y0  0
y1  x
y2  x  x
y3  x  x  x
y3  x  ( x  x)  x  y2
yn  x  yn 1 (3.3)

We can now implement the series using the faster add operator in
place of multiplication.

y=0;
for (n = 1; n <= m; n++)
y += x

An exponential series is implemented in a similar manner using


exponentiation in a loop.
y  x n , n  0...m (3.4)

In C++, we use the pow function for exponentiation.

for (n = 0; n <= m; n++)


y = pow(x,n);

An exponential series can also be converted to a recursive form.


y0  1
y1  x
26 From Equation to Code

y2  x  x
y3  x  ( x  x )  x  y 2
yn  x  yn 1 (3.5)

We can now implement the loop using multiplication in place of


the exponential function (pow).

y = 1;
for (n = 1; n <= m; n++)
y *= x;

This expansion only works if x is constant throughout the loop and


n is an integer value. By applying the rules for exponents we can
make the same expansion work for any real n as well. We can
represent any real value of n as a product of an integer value k and a
real number j such that n=k·j. For example, if n=0.5 we could use
k=10 and j=0.05. From the laws for exponents, we know that:

 
xk j  x j
k

We can substitute xj for x and k for n in equation (3.4) and the


recursive form will be valid.
In some cases we use the current value of the series immediately,
but in many cases we need to store the entire series and will declare
an array for that purpose. The subscript on the variable in the equation
becomes a subscript on the program array variable.
yn  axn  bxn 1 (3.6)

This is easily converted to a program, but we must check the


boundaries of the subscript carefully. When used in a computer
program, the subscript n-1 is only valid for n > 0 and we must treat
n=0 as a special case. Rather than testing n on each iteration of the
loop, we place code outside the loop and then begin the loop at n=1.

y[0] = a * x[0];
for (n = 1; n < m; n++)
y[n] = (a * x[n]) + (b * x[n-1]);
BasicSynth 27

The parentheses in the program are not necessary, but they are
often included to make the programmer’s intent clear. Relying on the
default order of evaluation may make for a more compact program,
but tends to lead to programming errors.
There is one significant difference between the mathematical
representation of sound and the software implementation that can
produce unexpected errors in the program output. The math assumes
an infinite precision in the representation of numbers while a
computer program is always limited to a finite number of bits to
represent a number. The limited precision of a computer data type can
result in one of three errors: overflow, underflow, and round-off.
Overflow and underflow occur when the magnitude of a value
exceeds the maximum or minimum value for the computer data type.
Using a signed 16-bit integer data type, values outside the range
±32,767 will fold over to a value inside that range. In other words,
integer calculations are always performed “modulo the word size.”
When overflow happens on a sample value, the value does not simply
clip to a limit value. Adding 2 to 32,767 (0x7fff) produces -32,767
(0x8001) and results in severe distortion of the waveform.
Round-off occurs when the fractional portion of the value cannot
be represented exactly. In the case of an integer data type, we cannot
represent the fractional portion at all. Thus 10/3 produces a value of
3, not 3.33333… A naïve programmer will think that using a floating
point data type will solve the problem. However, floating point
representation also has a limited number of bits to store the fractional
value, and at some point the value must be truncated.
Round-off can result in an incorrect value when we use iteration to
calculate a sum or product. If the increment value cannot be precisely
represented, it will either be rounded to the nearest available value, or
simply truncated. In either case, the iterative operation may not end
on the final value. In other words, repeatedly summing the increment
may not produce the same value as multiplying the increment by a
count. Usually the error is so small that it can be safely ignored. But
when we iterate over several thousand samples, the error may
accumulate and produce audible distortion.
Failure to consider the potential overflow, underflow, and round-
off error can result in a program that produces distorted sound or no
sound at all. This is an unavoidable issue, but there are ways to
minimize the problem, and in some cases eliminate it.
28 From Equation to Code

Often we can avoid or reduce numerical errors by rearranging the


order of operators. For example, calculating ten percent of 12345
using 16-bit integers must be done in a specific order to produce a
usable result. We cannot use 12345*(10/100) since the division will
truncate to 0. We could multiply first then divide with
(12345*10)/100 but the intermediate product (123,450) would exceed
the maximum value for a 16-bit integer. We can, however, use
(12345/100)*10 and get a result. The result will lose two digits of
precision, but at least we have a usable value (1230), perhaps even
close enough for what we need to do.
Another common method of avoiding overflow and underflow is
to normalize the values. Normalization is the process of scaling
values to a convenient range, performing the calculations, and then
rescaling them to the desired range. For example, by normalizing the
range of a variable to [-1,+1] we can multiply values together as many
times as we want without exceeding the normalized range. We still
need to be careful when adding, but multiplication is far more likely
to produce overflow than addition. Multiplying two n-bit words will
potentially require 2n bits to represent the product. Adding two n-bit
words will never require more than n+1 bits to represent the sum.
Normalization does not avoid round-off error, however.
One way to eliminate round-off error is to force the value to a
known value whenever possible. If we know that after n iterations a
calculation should end with the value 100, we can explicitly set the
value to 100 at the end of the loop. We can also rearrange the order of
operations as shown above with integers. This may require thinking
of a value as a ratio rather than a single constant. For example, a ratio
such as 2/3 represents a repeating fraction. We can multiply by
0.6667 and possibly lose precision, or, multiply by 2 and then divide
by 3 and get a more accurate result at the cost of one additional
arithmetic operation.
The additional processing time required for floating point can also
be a potential problem. As a rule, integer calculations are faster than
floating point, and with the large number of calculations that must be
made to produce sound, using integers can result in a large
performance gain. Where appropriate, or when needed for
performance reasons, we can use a fixed point representation.
Technically, all integers are fixed point representations, but here
we mean a specific use of integers to represent fractional quantities.
BasicSynth 29

Fixed point representation uses an integer data type with each value
scaled by some power of two. The most significant bits represent the
integer part and the least significant bits represent the fractional part.
We can treat the values as integers and perform integer operations so
long as we remember to shift the result by an appropriate amount. For
example, a 16 by 16 multiply produces a 32-bit result. For a 16-bit
fixed point system, we would need to produce a 32-bit product and
then extract the 16 bits containing the appropriately scaled result.
The example in Figure 5 shows adding 123.45 and 67.89 using
fixed point representation. The fixed point values are obtained by
multiplying each number by 216 and then adding them as integers.
Note that the final result has a slight error, but when rounded to two
significant digits, is the same value as the sum of the real numbers.

16 MSB (integer)
. 16 LSB (fraction)

32 bit word

0x007B
. 0x7333 (123.45)

0x0043
. 0xE3D7 (67.89)

0x0Bf
. 0x570A (191.33999)

Figure 5 - Fixed Point Addition

Fixed point multiplication is shown in Figure 6. We first multiply


each half of the number separately to avoid overflow, then sum the
results with the appropriate shift value so that the binary point is
aligned. As with addition, the result has a slight round-off error, but is
accurate to three significant digits.
Most 32-bit processors can produce a 64-bit result in a register
pair. For example, on the Intel Pentium® processor, the result of a
32-bit multiply is a 64-bit value in the AX,DX register pair. Adding
AX, shifted right by 16, with DX, shifted left by 16, produces the
30 From Equation to Code

32-bit result. Thus only one multiply, two shifts and one add, all
performed in registers, are needed to perform the fixed point multiply.

0x007B H1 . 0x7333 L1

0x0043 H2 . 0xE3D7 L2

. 0x6686 0xF8D5 (L1xL2)

0x006D
. 0x784D (H1xL2)

0x001E
. 0x2659 (H2xL1)

0x2031
. (H1xH2)

0x20BD
. 0x052C (8381.02020)

Figure 6 - Fixed Point Multiply

Although efficient, fixed point programming can be complicated


and error prone. The programmer must be aware of when the results
must be shifted and by how much, and must also be careful about
overflow during intermediate calculations. The resulting code can
become cluttered and difficult to understand. For most applications,
processor speeds are now sufficiently fast that even a floating point
representation can work in real-time. A good rule of programming is,
“FIRST make it work, THEN make it work fast.” After all, a slow
system that produces correct output is worth far more than a system
that produces errors very quickly. Thus the examples in this book will
use a floating point representation for amplitude, frequency, and
phase. If better performance is needed, we can convert the floating
point calculations to fixed point in time critical areas.
BasicSynth 31

BasicSynth Library

The defined types PhsAccum, FrqValue and AmpValue are used


whenever the code must refer to a signal phase, frequency or
amplitude, respectively. The default for these types are double, float
and float. To change the phase, frequency or amplitude
representation, only these definitions need to be altered. The
SampleValue type is defined appropriately for the size of output
samples. Constants for commonly used values such as π and 2π are
also defined.
Some values are used globally in the synthesizer system and it is
useful to put these together into a single global object for reference.
The SynthConfig class is used for this purpose. The sampleRate
member is used to hold the sample rate, default 44100. The
sampleScale value is used to convert an AmpValue to the appropriate
range for output samples (SampleValue) and is 32767.0 for signed
16-bit output. The other member variables will be described in the
appropriate chapters.
Thie SynthConfig class definition must be included in all programs
that use the BasicSynth library and a single global instance of the
class named synthParams must be defined somewhere in the
program. The library defines an instance of this class so that when the
library is linked with the main program, the necessary object is
automatically available. The object will be initialized in its
constructor to reasonable default values. It can also be initialized by
calling either the Init member function or the global InitSynthesizer
function if a different sample rate is desired.

Files:

Include/SynthDefs.h
Src/Common/Global.cpp
Chapter 4
Output File Format

Before we generate any samples, we need to determine the format for


the output file that will be produced. If we are developing the
software for personal use, we can define a private format that meets
the minimum requirements of our system. However, if we use a
standard format, the output of the program can be used by other sound
processing and playback systems. Compatibility with other systems
allows us to leverage the abilities of those systems and thus
automatically gain features for our own system without having to
write additional code.
Several standard sound file formats are widely used. The MP3
format is often used for sound files on the Internet as well as video
and audio players. However, MP3 is a compressed format that
requires additional processing, cannot be sent directly to many sound
devices, and also loses some fidelity due to compression. The WMF
format is similar to MP3. Another standard format is the WAVE file
format. This format can be used for direct playback or for production
of audio CDs, and it can also be converted to MP3, WMF and other
formats using a stand-alone utility program. Any off-the-shelf
software should be able to read WAVE files as well. Most important,
the samples are in raw form without any compression or equalization
required. We can read, process, and write the files as many times as
desired without loss of fidelity.
The WAVE file format allows specification of the sampling rate,
sample size, and number of channels. However, these values are
ultimately controlled by the sound output device and it is best to
produce WAVE files that already meet the requirements for direct
playback. For most computer sound output devices, and CD audio,
the standard sampling rate is 44,100Hz; samples are sixteen bit signed

32
BasicSynth 33

integers, with two channels (stereo). Newer computers also support


twenty-four bit samples at rates up to 192kHz. In either case, we can
use any internal format as long as the output is converted to the
standard before writing values to the output file or device.

WAVE File Format

A WAVE file is a type of RIFF file.3 The RIFF specification defines


the file as a set of nested “chunks” of data. Each chunk begins with an
8-byte chunk header. The chunk header identifies the chunk type with
a 4-character ID followed by the chunk size as a 4-byte binary value
in little-endian format. Figure 7 shows the structure of a typical
WAVE file. Each gray box represents a chunk header containing the
chunk ID along with the size of the chunk. The white boxes represent
the chunk data, which includes any nested chunks.

RIFF CHUNK
ID: ‘R’ ‘I’ ‘F’ ‘F’

RIFF DATA
‘W’ ‘A’ ‘V’ ‘E’

FMT Chunk
ID: ‘F’ ‘M’ ‘T’ ‘ ‘

FMT DATA
Sample size, rate, etc.

data Chunk
ID: ‘d’ ‘a’ ‘t’ ‘a’

Audio Sample Data

Figure 7 - WAVE File Structure

A WAVE file can contain other chunk types in addition to the two
shown here. A WAVE file can contain multiple sets of samples along
with cue information, description, etc. In addition, the chunks are not
required to be in the order shown. However, most WAVE files

3 RIFF stands for Resource Interchange File Format.


34 Output File Format

contain only two data chunks, one containing format information and
one containing sample data, and those chunks are located first in the
file. This allows us to create a simplified representation of a WAVE
file. Doing so will make the code specific to one form of file, but is
sufficient for the synthesizer we will develop, is simple to program,
and is very fast to save or load. The file is readable by other sound
processing systems without any problems.
Taking this approach, we can consider the WAVE file as a file
with a fixed length header and variable length block of samples. To
create a WAVE file, we fill in a header, write it to the file, then write
the sample data, converting to the file sample representation if
needed. Each sample is one sixteen bit word per channel. For stereo,
the sample for the left channel is written followed immediately by the
sample for the right channel. In other words, the two channels are
interlaced in the file. The following code shows a general purpose
WAVE file write function in C++. Note that this code is for a little-
endian processor. For big-endian processors, the byte order must be
swapped before writing to disk.

struct WavHDR {
uint8 riffId[4]; // 'RIFF' chunk
uint32 riffSize; // filesize - 8
uint8 waveType[4]; // 'WAVE' type of file
uint8 fmtId[4]; // 'fmt ' format chunk
uint32 fmtSize; // format chunk size (16)
uint16 fmtCode; // 1 = PCM
uint16 channels; // 1 = mono, 2 = stereo
uint32 sampleRate; // 44100
uint32 avgbps; // samplerate * align
uint16 align; // (channels*bits)/8;
uint16 bits; // bits per sample (16)
uint8 waveId[4]; // ‘data’ chunk
uint32 waveSize; // size of sample data
};

void WriteWaveFile(int16 *sampleBuffer,


uint32 sampleTotal,
int channels)
{
// two bytes per value and one value per channel
uint32 byteTotal = sampleTotal * 2 * channels;
BasicSynth 35

WavHDR wh;
wh.riffId[0] = 'R';
wh.riffId[1] = 'I';
wh.riffId[2] = 'F';
wh.riffId[3] = 'F';
wh.riffSize = byteTotal + sizeof(wh) – 8;
wh.waveType[0] = 'W';
wh.waveType[1] = 'A';
wh.waveType[2] = 'V';
wh.waveType[3] = 'E';
wh.fmtId[0] = 'f';
wh.fmtId[1] = 'm';
wh.fmtId[2] = 't';
wh.fmtId[3] = ' ';
wh.fmtSize = 16;
wh.fmtCode = 1;
wh.channels = (uint16) channels;
wh.sampleRate = 44100;
wh.bits = 16;
wh.align = (wh.channels * wh.bits) / 8;
wh.avgbps = (wh.sampleRate * wh.align);
wh.waveId[0] = 'd';
wh.waveId[1] = 'a';
wh.waveId[2] = 't';
wh.waveId[3] = 'a';
wh.waveSize = byteTotal;

FILE *f = fopen("out.wav", "wb");


fwrite(&wh, 1, sizeof(wh), f);
fwrite(sampleBuffer,2*channels,sampleTotal,f);
fclose(f);
}

The WriteWaveFile function requires the entire sample buffer to


be passed in as an argument. For a minimal program that generates
sound into a memory buffer, this will work fine. For a more general
WAVE file output function we would like to be able to pass samples
in as they are generated without having to store the entire sound file
in memory. For the BasicSynth library, the function shown above is
implemented as a class that incorporates an internal buffer and
provides methods for adding samples to that buffer.
When reading a WAVE file we read each chunk header, check the
id, type and information fields to make sure it is a file we can process,
36 Output File Format

allocate a buffer, then read the chunk data into the buffer. Reading a
WAVE file containing more than one sample data chunk, or other
types of chunks, involves reading a chunk header and then either
descending into the chunk, ascending out of the current chunk,
reading the chunk data, or stepping over the chunk as appropriate.
The code for reading wave files is shown in a later chapter.

BasicSynth Library Classes

The BasicSynth library contains classes to read and write files in


WAVE format. Three WAVE file classes are defined, one that
manages the sample buffer (WaveOutBuf), one to manage file output
(WaveOut), and one to load wave files (WaveFileIn). The file output
class inherits from the buffer class.
These classes do not use the standard C library FILE type for I/O.
Since the WaveFile class contains its own internal buffer, the
buffering provided by the standard library is redundant. The
FileWriteUnBuf class will perform direct writes using the operating
system API. Likewise, the file input operations rely on the
FileReadBuf class in place of the standard file I/O functions.

Files:

Include/WaveFile.h
Include/SynthFile.h
Src/Common/WaveFile.cpp
Src/Common/SynthFile.cpp
Chapter 5
Signal Generator

The most straightforward method of sound generation in software is


to evaluate a periodic function for each sample time. A periodic
function is any function that repeats at a constant interval, called the
period. Consider the circle in the figure below. Starting at the 3:00
position and then sweeping around the circle counter-clockwise, we
make a complete cycle in 2π radians. If we plot the points on the
circumference at equally spaced time intervals we produce a
waveform as shown in Figure 8.

one period equals 2π radians and M samples

one sample equals 2π/M radians

the angle increments the radius of the


for each sample and circle is the peak
is called the phase amplitude of the
waveform

Figure 8 - Periodic Function

To generate a signal we need to know the number of samples in


one period and the phase increment for one sample time. The period
is the time it takes for the waveform to repeat and is the reciprocal of
the frequency (1/f). In other words, a frequency of 100Hz repeats
every 1/100 second. Multiplying the sample rate (fs) by the time of
one period (1/f) will give us the samples per period. The period is

37
38 Signal Generator

equal to 2π radians, thus the phase increment for one sample (φ) is 2π
divided by the number of samples in one period.
2
 (5.1)
fs f
The amplitude for any given sample is the amplitude value of the
phase at that point in time multiplied by the radius of the circle. In
other words, the amplitude is the sine of the phase angle and we can
also derive the phase increment from the sine function.
sn  An  sin  n (5.2)

The value sn is the nth sample, An the peak amplitude (volume) at


sample n, and n the phase at sample n. To calculate n for any sample
n, we must multiply the phase increment for one sample time by the
sample number.
n    n (5.3)

To calculate φ, we need to determine the radians for one sample


time at a given frequency. As there are 2 radians per period, we
multiply the frequency by 2 to get the radians per second. The time
of one sample is the reciprocal of the sample rate, thus the phase
increment for one sample time is the radians per second divided by
the sample rate.
1
t (5.4)
fs
  2f (5.5)

2f 2
   t   f (5.6)
fs fs
The calculation for ω (5.5) is used extensively in signal processing
equations. It represents the frequency of the signal as radians per
second and is called the angular frequency.
A closer examination of (5.6) can show us why the frequency f
must be less than 1/2 the sample rate (the Nyquist limit). Consider the
frequency as a fraction of the sampling rate (x):
BasicSynth 39

2 f s 2
   (5.7)
fs x x
For any value of x less than 2, the phase increment will be greater
than π. Consequently, the resulting waveform will have fewer than
two values for each period and will produce an incorrect frequency as
shown in Figure 9.

period of desired frequency

one sample time, phase increment > π

period of generated frequency

Figure 9 - Alias Frequency

The resulting frequency is less than the expected frequency and is


called an alias frequency. Because the frequency decreases rather
than increases as the phase increment increases beyond π, this
phenomenon is also called foldover.
Equation (5.1) is obviously equivalent to (5.6) and either version
can be used to produce the program. The third form of (5.6) is
generally preferred for programming purposes since the value of 2/fs
is constant during the program’s execution. We can calculate that
ratio once at initialization and avoid the calculation on each frequency
change.
Substituting for n in the original equation produces:
40 Signal Generator

2
sn  An  sin   n   An  sin(  f  n) (5.8)
fs
Equation (5.8) is easily implemented as a counted program loop:

frqRad = twoPI / sampleRate;


totalSamples = duration * sampleRate;
for (n = 0; n < totalSamples; n++)
sample[n] = volume * sin(frqRad*frequency*n);

The calculation of the phase increment (frqRad * frequency) is


loop invariant, and we can move that calculation out of the loop to
improve performance. Furthermore, the product of the phase
increment and n is a series that we can replace with repeated
summation. Finally, although the sin function will automatically fold
the phase to the range of [0,2], we should prevent the phase from
going out of range by testing after each increment. Applying these
changes produces the basic program for sound generation.

frqRad = twoPI / sampleRate;


phaseIncr = frqRad * frequency;
phase = 0;
volume = 1;
totalSamples = duration * sampleRate;

for (n = 0; n < totalSamples; n++) {


sample[n] = volume * sin(phase);
phase += phaseIncr;
if (phase >= twoPI)
phase -= twoPI;
}

To complete the implementation, we need to allocate a buffer


large enough to hold the samples and write the buffer to a WAVE file
after calculating the sample values.
The standard WAVE format uses signed 16-bit integers to
represent each sample and we need to scale the peak output amplitude
to the range of ±215-1 (±32,767). The sin function returns a value in
the range [-1,+1] and we will usually specify the volume as a value in
the range of [0,1] to keep all samples normalized to [-1,+1] during
intermediate calculations. The final sample must be scaled at some
BasicSynth 41

point to the output sample size, usually when writing the sample to
the output file buffer.
The duration value is specified in seconds and must be multiplied
by the sample rate to determine the number of samples. Duration can
alternatively be specified directly as number of samples. A music
program will need to convert rhythm values into seconds (or samples)
based on the desired tempo. For example, a quarter note at 60 beats
per minute has a duration of one second, or 44,100 samples. In the
case where duration values are the result of recording keyboard key
on/off events, the duration is already a time value, but may need to be
converted to seconds of duration in order to easily calculate the
number of samples.
The frequency variable is in Hz. Musicians express frequency as a
pitch or possibly as a number representing a key on a keyboard. For
an equal-tempered scale, the frequency can be calculated directly
from the pitch or key number. Each half-step between notes in the
musical scale represents a frequency ratio of 21/12 (~1.059). Given a
known pitch of frequency f0 and the number of half-steps between
pitches h, the frequency of any pitch is (f0·2h/12). To save processing
time, the frequency values for the standard musical scale are usually
calculated during program initialization and stored in a table. The
pitch can then be quickly converted into frequency by using the pitch
value as an index into the frequency table.
We can replace the sin function with any periodic function that
returns an amplitude for a given phase. Thus this small piece of code
can be used to produce a very wide range of sounds. Functionally it is
the software equivalent of an oscillator, the basic building block of
almost all synthesizers. In a later chapter we will develop this basic
oscillator into a C++ class that is capable of producing a variety of
waveforms.

Example Program

The Example01 directory contains a complete program that produces


one second of sound at middle C and writes the output to a wave file.
The duration and pitch can be changed by supplying command line
arguments. The example oscillator code uses the sampleRate and
frqRad members of the global parameters object to calculate phase.
These values are set automatically when the synthParams object is
42 Signal Generator

initialized. If desired, the Init method can be called directly to change


the sample rate. The synthParams object also contains a table of
frequencies for the standard musical pitches. The table is initialized
such that middle C has an index of 48. The GetFrequency method
converts a pitch number to frequency using the table. Alternate tuning
systems can be used by filling the tuning[] array with the appropriate
frequency values.

BasicSynth Library

The example program implements the oscillator code inline for


simplicity. The oscillator described in this chapter is also
implemented by the GenWave class. GenWave defines methods to set
the frequency of the oscillator, reset the oscillator phase, and retrieve
the next sample. This GenWave class is the base class for all other
oscillators described in this book. GenWave inherits from an abstract
base class named GenUnit that defines generic methods required by
all signal generators. The name is a variation of “unit generator,” the
term commonly used in software synthesis systems to indicate
anything that can produce an output signal.

Files:
Include/SynthDefs.h
Include/GenWave.h
Src/Common/Global.cpp
Chapter 6
Envelope Generators

In the example code shown above, volume is constant for the duration
of the sound. However, musical instruments make sounds that vary in
volume over the duration of the sound, and synthesized sounds do the
same. A typical sound has an initial rise time (attack), a steady state
portion (sustain), and a final segment that decays to silence (release)
as shown in Figure 10.

+1.00
+0.80
+0.60
+0.40
+0.20
+0.00
0.10 0.20 0.30 0.40 0.50 0.60 0.70 0.80 0.90 1.00

Figure 10 - Amplitude Envelope

The graph shows the peak amplitude of the signal over time. The
peak amplitude has both positive and negative values, and if we were
to graph the entire signal and connect the peak amplitude values, the
resulting line would form a border, or envelope around the sound.
Since our waveform values are both positive and negative, we only
need to calculate the positive side of the envelope and then multiply
the envelope values by the waveform values.
The final decay segment is called the release. The term release is
adopted from analog synthesizers where the envelope generator is
triggered when a key on the keyboard is pressed. When the key is

43
44 Envelope Generators

released, the final decay begins. For some sounds, there is no sustain
portion. Plucking a string, striking a metal plate or wooden bowl
produces an envelope with only attack and decay portions. The decay
begins at the end of the attack, whether or not the key has been
released. In those cases, the release segment is more appropriately
called the decay, but the term release is used generally for the final
decay section even when there is no sustain portion to the envelope.
Applying an amplitude envelope to the signal can be achieved if
we set the volume value with a series of line segments that calculate
the amplitude based on the beginning and ending values over the
duration of a segment. We can represent an envelope attack or decay
with the equation for a line.
y = a·x + b (6.1)
To implement equation (6.1) as a program, we first need to decide
what the variables represent. The obvious association is that y
represents amplitude and x represents time. The range of values for x
is [0,d] where d is the total duration of the segment in samples. The
range for y is [Astart,Aend] where A is the amplitude. The starting
amplitude is when x=0, thus:
y = a·0+b = b
In other words, b must be the starting amplitude value (Astart). If we
normalize our envelope to [0,1], then b becomes 0 and we can ignore
it. When x is equal to the duration of the segment, y must be at its end
value and thus the value of a is:
1 = a·x
a = 1/x (6.2)
If we have a starting value other than zero, or an ending value
other than 1, we could do the same thing and get:
yend = a·x + ystart
yend - ystart = a·x
a = (yend - ystart)/x (6.3)
In other words, we calculate a as the range of the segment divided
by the number of samples and then multiply the sample number by a
to get each amplitude value.
BasicSynth 45

segSamples = segDuration * sampleRate;


amp = (ampEnd – ampStart) / segSamples;

for (n = 0; n < segSamples; n++)


volume = (n * amp) + ampStart;

If we convert equation (6.1) to the recursive form we can replace


the multiplication with incremental addition.
To program the envelope generator we convert the duration of the
attack and decay times into number of equivalent samples, and then
calculate the increment value at the beginning of the respective
segments. For each sample, we multiply the amplitude by the
waveform value for the sample to produce the output value.
Combining the amplitude envelope with the oscillator from the
previous chapter produces the following program.

phaseIncr = frqRad * frequency;


phase = 0;
totalSamples = duration * sampleRate;
attackTime = attackRate * sampleRate;
decayTime = decayRate * sampleRate;
decayStart = totalSamples – decayTime;
if (attackTime > 0)
envInc = peakAmp / attackTime;
volume = 0;

for (n = 0; n < totalSamples; n++) {


if (n < attackTime || n > decayStart)
volume += envInc;
else if (n == attackTime)
volume = peakAmp;
else if (n == decayStart)
envInc = –volume / decayTime;
sample[n] = volume * sin(phase);
if ((phase += phaseIncr) >= twoPI)
phase -= twoPI;
}

This code executes quickly and can be easily extended to include


additional envelope segments. Code should be added to insure the
combined attack and decay times do not equal or exceed the total
46 Envelope Generators

duration. Otherwise, the attack time will be greater than or equal to


the decay start time and the statement that calculates the decay
segment decrement will never execute.
The increment of volume is performed before the sample is
calculated, skipping over the starting volume value. Assume we have
100 samples in the attack segment and a peakAmp value of 1. The
envInc value is 1/100=0.01. If we increment before calculating the
sample, volume will be 0.01 at n=0 and 1 at n=99. If we increment
after calculating the sample, the volume will be 0 at n=0 and 0.99 at
n=99. Since we are using a starting volume value of 0, we can skip
the start value without any noticeable difference in sound and end
precisely on the final value at the end of the attack segment.
However, it may be important to use both the initial and final values
if an envelope generator segment begins or ends with values other
than 0 and 1. To handle either case, the code explicitly sets the
volume to the peak value at the end of the attack segment to insure we
reach the peak value. Doing so also eliminates any accumulated
round-off error in the volume level at the end of the attack segment.
However, the code uses the current volume level to calculate the
decay decrement in case the peak level is not reached.
The data type used to calculate the attack and decay times sets a
limit on the duration of any segment. A 16-bit integer and 44,1000Hz
sampling rate would only allow durations up to 0.74 seconds. We
should use a 32-bit integer or a floating point data type to allow for
longer durations.
For longer durations, the step between amplitude values can be
smaller than the minimum change in amplitude. For example, at a
sampling rate of 44,100Hz and a duration of 0.77 seconds, the
increment between amplitude values would be 1/(44100*0.77) =
0.000029449. When scaled to a 16-bit output range, the resulting
amplitude change is 0.9649, less than one bit in the output sample. As
a result, for durations longer than 0.77 seconds, we are calculating the
amplitude on every sample even though the result of the calculation
makes no difference to the final amplitude. We can gain a slight
performance improvement by only calculating a new amplitude every
n samples with n chosen as the point where we have a minimum
change in output. For practical music synthesis systems, envelope
segments are often relatively short and sub-dividing the segment will
not produce a significant performance improvement. A slower
BasicSynth 47

computer system that needs to reduce the number of calculations can


take advantage of this fact and only calculate envelope values every
10 samples or so.

Curved Segments

A linear change in amplitude does not produce a linear change in


perceived loudness. In order to double the loudness of a sound, we
need to double the power of the sound, and that requires an
exponential increase in amplitude. Thus synthesis systems typically
include envelope generators that produce curved segments in place of
straight lines. Curved segments often have a more natural sound,
although the difference can be subtle and almost imperceptible when
the attack or decay times are very short. Linear segments are faster to
calculate and will work fine in many cases, but, if desired, we can
replace the line function with an exponential function to produce
curved envelope segments. The equation to produce an exponential
curve is:
yn = a·(xn)b + c (6.4)
As above, the value for y represents the amplitude, and x
represents time. We would like to normalize y to the range of [0,1]
such that (x0)b=0 and (xn)b=1. We know that 0b=0 and 1b=1 for any
value of b, and thus x should vary over the interval of [0,1]. Since x
represents time, the value of x is n·1/d where d is the duration in
samples. We can generate the exponential curve as an incremental
calculation of x which is then raised to some power b.
If we want to vary the amplitude over some other range, we
calculate the range and offset as:
a = (yend –ystart) / n (6.5)
c = ystart (6.6)
Assuming that the envelope begins and ends on 0, we can
implement the envelope as shown in the following program.
48 Envelope Generators

range = peakAmp / totalSamples;


offset = 0;
expIncr = 1 / attackTime;
expX = 0;
expB = 2;

for (n = 0; n < totalSamples; n++) {


if (n < attackTime || n > decayStart) {
volume = range * pow(expX, expB);
expX += expIncr;
} else if (n == decayStart) {
expIncr = -1 / decayTime;
expX = 1;
}
sample[n] = volume * sin(phase);
if ((phase += phaseIncr) >= twoPI)
phase -= twoPI;
}

Calculation of phase, attackTime and decayTime is the same as for


the linear segment example. Tests for zero length segments also need
to be included. This code will produce an envelope similar to that
shown in Figure 11.

+1.00
+0.80
+0.60
+0.40
+0.20
+0.00
0.10 0.20 0.30 0.40 0.50 0.60 0.70 0.80 0.90 1.00

Figure 11 - Exponential Envelope (b > 1)

The value of b controls the depth of the curve. For values greater
than 1, the curve becomes increasingly steeper. For values between 0
and 1, the curve changes to a logarithmic curve, similar to that shown
in Figure 12. A logarithmic amplitude curve produces a sharper attack
but with a smoother transition to the final value. Note that when b=1
the output is a straight line, and we could use the same code for both
linear and curved segments.
BasicSynth 49

+1.00
+0.80
+0.60
+0.40
+0.20
+0.00
0.10 0.20 0.30 0.40 0.50 0.60 0.70 0.80 0.90 1.00

Figure 12 - Logarithmic Envelope (0 < b < 1)

This implementation requires calling the exponential function on


every sample, a time consuming operation. If we limited the value of
b to small integers, such as 2 or 3, we could replace the call to the
exponential function with a multiply, but would lose considerable
flexibility by doing so. To get the best performance while retaining
the ability to vary the curve shape, we should remove the exponential
function and replace it with an iterative calculation. Unfortunately, we
cannot easily convert equation (6.4) into the recursive form.
However, we can use a different form of the exponential equation:
y = a·bn+c, n=0…k (6.7)
For now, we can set a=1 and c=0, and produce:
y = bn, n=0…k
yn = bn · yn-1
yk = bk · y0
yk / y0= bk
b = (yk / y0)1/k (6.8)
If wet set k to the number of samples to generate, we now have an
iterative solution. However, we no longer have a curve that ranges
from [0,1] since at n=0, the value of y=1. We also have a problem if
we want the minimum value y0=0 since we can’t divide by 0. We can
get around these problems if we set c to something other than 0.
y = bn+c, n=1…k
y = c, n=0
50 Envelope Generators

b = ((yk +c) / c)1/k (6.9)


If the value of y when n=0 is set equal to c, we can set c to any
value greater than 0 and then produce a volume range of [0,1] by
subtracting c from the volume value. Increasing the value of c will
change the y intercept, move the curve left along the x axis and
produce an increasing flatness to the curve, just as we did earlier by
varying the exponent. Thus we have the same capability as before, but
can now implement the generator in the recursive form.
We can now implement the exponential volume curve by
multiplying the last amplitude value with the value of b. We initialize
b for the attack segment, and at the transition to the decay segment
recalculate b to produce an inverse curve. Calculation of phase,
attackTime and decayTime is the same as in the previous examples.

expMin = 0.2; // adjust to change curvature


expMul = pow((expMin+1)/expMin, 1/attackTime);
expNow = expMin;

for (n = 0; n < totalSamples; n++) {


if (n < attackTime || n > decayStart) {
expNow *= expMul;
volume = (expNow – expMin) * peakAmp;
} else if (n == attackTime) {
volume = peakAmp;
} else if (n == decayStart) {
expNow = 1+expMin;
expMul = pow(expMin/(1+expMin),1/decayTime));
}
sample[n] = volume * sin(phase);
if ((phase += phaseIncr) >= twoPI)
phase -= twoPI;
}

For a log curve, we must invert the curves and translate the value
to a positive range. In other words, invert the exponent and subtract y
from 1.

expMin = 0.2; // adjust to change curvature


expMul = pow(expMin/(expMin+1), 1/attackTime);
expNow = expMin+1;
Exploring the Variety of Random
Documents with Different Content
fallen, and my drumbled and troubled well began to clear. He was
never a whit angry at the fever-ravings of a poor tempted sinner;
but He mercifully forgave, and came (as it well becometh Him), with
grace and new comfort, to a sinner who deserved the contrary, And
now He is content to kiss my black mouth, to put His hand into
mine, and to feed me with as many consolations as would feed ten
hungry souls. Yet I dare not say that He is a waster of comforts, for
no less would have borne me up; one grain-weight less would have
casten the balance.
Now, who is like to that royal King, crowned in Zion! Where shall I
get a seat for real Majesty to set Him on? If I could set Him as far
above the heaven as thousand thousands of heights devised by men
and angels, I should think Him but too low. I pray you, for God's
sake, my dear sister, to help me to praise. His love hath neither brim
nor bottom; His love is like Himself, it passeth all natural
understanding. I go to fathom it with my arms; but it is as if a child
would take the globe of sea and land in his two short arms. Blessed
and holy is His name! This must be His truth which I now suffer for;
for He would not laugh upon a lie, nor be witness with His comforts
to a night-dream.
I entreat for your prayers; and the prayer and blessing of a prisoner
of Christ be upon you. Grace be with you.
Yours in his sweet Lord Jesus,
S. R.
Aberdeen, March 14, 1637.
CLIV.—To Alexander Gordon of
Knockgray, near Carsphairn.
(PROSPECTIVE TRIALS.)
EAR BROTHER,—I have not leisure to write to you. Christ's
ways were known to you long before I, who am but a child,
knew anything of Him. What wrong and violence the prelates may,
by God's permission, do unto you, for your trial, I know not; but this
I know, that your ten days' tribulation will end. Contend to the last
breath for Christ. Banishment out of these kingdoms is determined
against me, as I hear; this land dow not bear me. I pray you, to
recommend my case and bonds to my brethren and sisters with you.
I intrust more of my spiritual comfort to you and them that way, my
dear brother, than to many in this kingdom besides. I hope that ye
will not be wanting to Christ's prisoner.
Fear nothing; for I assure you that Alexander Gordon of Knockgray
shall win away and get his soul for a prey. And what can he then
want that is worth the having? Your friends are cold (as ye write);
and so are those in whom I trusted much. Our Husband doth well in
breaking our idols in pieces. Dry wells send us to the fountain. "My
life is not dear to me, so being I may fulfil my course with joy." I
fear that ye must remove; your new hireling will not bear your
discountenancing of him, for the prelate is afraid that Christ get you;
and that he hath no will to.
Grace be with you.
Yours in his sweet Lord and Master,
S. R.
Aberdeen, 1637.
CLV.—To Grizzel Fullerton.
[Grizzel Fullerton was the daughter of William Fullerton, Provost
of Kirkcudbright, and Marion M'Naught. See Letter VI.]

(THE ONE THING NEEDFUL—CHRIST'S LOVE.)


EAR SISTER,—I exhort you in the Lord, to seek your one
thing, Mary's good part, that shall not be taken from you. Set
your heart and soul on the children's inheritance. This clay-idol, the
world, is but for bastards, and ye are His lawfully-begotten child.
Learn the way (as your dear mother hath done before you) to knock
at Christ's door. Many an alms of mercy hath Christ given to her, and
hath abundance behind to give to you. Ye are the seed of the
faithful, and born within the covenant; claim your right. I would not
exchange Christ Jesus for ten worlds of glory. I know now (blessed
be my Teacher!) how to shute the lock, and unbolt my Well-
beloved's door; and He maketh a poor stranger welcome when He
cometh to His house. I am swelled up and satisfied with the love of
Christ, that is better than wine. It is a fire in my soul; let hell and the
world cast water on it, they will not mend themselves. I have now
gotten the right gate of Christ. I recommend Him to you above all
things. Come and find the smell of His breath; see if His kisses be
not sweet. He desireth no better than to be much made of; be
homely with Him, and ye shall be the more welcome; ye know not
how fain Christ would have all your love. Think not this is
imagination and bairns' play, which we make din for. I would not
suffer for it, if it were so. I dare pawn my heaven for it, that it is the
way to glory. Think much of truth, and abhor these ways devised by
men in God's worship.
The grace of Christ be with you.
Yours, in his sweet Lord Jesus,
S. R.
Aberdeen, March 14, 1637.
CLVI.—To Patrick Carsen.
[This was, perhaps, the son of John Carsen, formerly noticed. See
Letter CXXVII.]

(EARLY DEVOTEDNESS TO CHRIST.)


EAR AND LOVING FRIEND,—I cannot but, upon the
opportunity of a bearer, exhort you to resign the love of your
youth to Christ; and in this day, while your sun is high and your
youth serveth you, to seek the Lord and His face. For there is
nothing out of heaven so necessary for you as Christ. And ye cannot
be ignorant but your day will end, and the night of death shall call
you from the pleasures of this life: and a doom given out in death
standeth for ever—as long as God liveth! Youth, ordinarily, is a post
and ready servant for Satan, to run errands; for it is a nest for lust,
cursing, drunkenness, blaspheming of God, lying, pride, and vanity.
Oh, that there were such an heart in you as to fear the Lord, and to
dedicate your soul and body to His service! When the time cometh
that your eye-strings shall break, and your face wax pale, and legs
and arms tremble, and your breath shall grow cold, and your poor
soul look out at your prison house of clay, to be set at liberty; then a
good conscience, and your Lord's favour, shall be worth all the
world's glory. Seek it as your garland and crown.
Grace be with you.
Yours, in his sweet Lord Jesus,
S. R.
Aberdeen, March 14, 1637.
CLVII.—To Carleton.
[Livingstone, in his Characteristics, mentions two persons of this
name: "Fullerton of Carleton, in Galloway, a grave and cheerful
Christian;" and "Cathcart of Carleton, in Carrick, an old,
experienced Christian," in much repute among the religious of
his day, for his skill in solving cases of conscience, and dealing
with persons under spiritual affliction. But it seems clear that
Rutherford's correspondent was John Fullerton of Carleton, in
the parish of Borgue. For, in Letter XV. he is spoken of as in
Galloway. In the "Minutes of Comm. of Covenanters," we find
the following estates put side by side, all of them a few miles
from Anwoth, viz. "Roberton and Carleton, Caillie and Rusco,
Carsluth and Cassincarrie." His lady's name appears prefixed to
Letter CCLVI.
This, too, was the Carleton that wrote the Acrostic on Marion
M'Naught (see note on Letter V.). He was the author of a poem
—"The Turtle Dove, under the absence and presence of her only
Choice. 1664,"—dedicated by the author to Lady Jane Campbell,
Viscountess Kenmure, with whom he was connected. He also
wrote "A Manifesto of the Kingdom of Scotland in favour of the
League and Covenant," in verse. (See "Minutes of Comm. of
Covenanters.")]

(INCREASING SENSE OF CHRIST'S LOVE—


RESIGNATION—DEADNESS TO EARTH—
TEMPTATIONS—INFIRMITIES.)
UCH HONOURED SIR,—I will not impute your not writing to
me to forgetfulness. However, I have One above who
forgetteth me not—nay, He groweth in His kindness. It hath pleased
His holy Majesty to take me from the pulpit, and teach me many
things, in my exile and prison, that were mysteries to me before.
I see His bottomless and boundless love and kindness, and my
jealousies and ravings, which, at my first entry into this furnace,
were so foolish and bold, as to say to Christ, who is truth itself, in
His face, "Thou liest." I had well nigh lost my grips. I wondered if it
was Christ or not; for the mist and smoke of my perturbed heart
made me mistake my Master, Jesus. My faith was dim, and hope
frozen and cold; and my love, which caused jealousies, had some
warmness, and heat, and smoke, but no flame at all. Yet I was
looking for some good of Christ's old claim to me, though[238] I had
forfeited all my rights. But the tempter was too much upon my
counsels, and was still blowing the coal. Alas! I knew not well before
how good skill my Intercessor and Advocate, Christ, hath of
pleading, and of pardoning me such follies. Now He is returned to
my soul with healing under His wings; and I am nothing behind with
Christ[239] now; for He hath overpaid me, by His presence, the pain I
was put to by on-waiting, and any little loss that I sustained by my
witnessing against the wrongs done to Him. I trow it was a pain to
my Lord to hide Himself any longer. In a manner, He was challenging
His own unkindness, and repented Him of His glooms. And now,
what want I on earth that Christ can give to a poor prisoner? Oh,
how sweet and lovely is He now! Alas! that I can get none to help
me to lift up my Lord Jesus upon His throne, above all the earth.
2ndly, I am now brought to some measure of submission, and I
resolve to wait till I see what my Lord Jesus will do with me. I dare
not now nickname, or speak one word against, the all-seeing and
over-watching providence of my Lord. I see that providence runneth
not on broken wheels. But I, like a fool, carved a providence for my
own ease, to die in my nest, and to sleep still till my grey hairs, and
to lie on the sunny side of the mountain, in my ministry at Anwoth.
But now I have nothing to say against a borrowed fireside, and
another man's house, nor Kedar's tents, where I live, being removed
far from my acquaintance, my lovers, and my friends. I see that God
hath the world on His wheels, and casteth it as a potter doth a
vessel on the wheel. I dare not say that there is any inordinate or
irregular motion in providence. The Lord hath done it. I will not go
to law with Christ, for I would gain nothing of that.
3rdly, I have learned some greater mortification; and not to mourn
after, or seek to suck, the world's dry breasts. Nay, my Lord hath
filled me with such dainties, that I am like to a full banqueter, who is
not for common cheer. What have I to do to fall down upon my
knees, and worship mankind's great idol, the world? I have a better
God than any claygod: nay, at present, as I am now disposed, I care
not much to give this world a discharge of my life-rent of it, for
bread and water. I know that it is not my home, nor my Father's
house; it is but His foot-stool, the outer close of His house, His out-
fields and muir-ground. Let bastards take it. I hope never to think
myself in its common, for honour or riches. Nay, now I say to
laughter, "Thou art madness."
4thly, I find it to be most true, that the greatest temptation out of
hell is to live without temptations. If my waters should stand, they
would rot. Faith is the better of the free air, and of the sharp winter
storm in its face. Grace withereth without adversity. The devil is but
God's master fencer, to teach us to handle our weapons.
5thly, I never knew how weak I was, till now when He hideth
Himself, and when I have Him to seek, seven times a day. I am a dry
and withered branch, and a piece of dead carcass, dry bones, and
not able to step over a straw. The thoughts of my old sins are as the
summons of death to me, and my late brother's case hath stricken
me to the heart. When my wounds are closing, a little ruffle[240]
causeth them to bleed afresh; so thin-skinned is my soul, that I
think it is like a tender man's skin that may touch nothing. Ye see
how short I would shoot of the prize, if His grace were not sufficient
for me.
Wo is me for the day of Scotland! Wo, wo is me for my harlot-
mother; for the decree is gone forth! Women of this land shall call
the childless and miscarrying wombs blessed. The anger of the Lord
is gone forth, and shall not return, till He perform the purpose of His
heart against Scotland. Yet He shall make Scotland a new, sharp
instrument, having teeth to thresh the mountains, and fan the hills
as chaff.
The prisoner's blessing be upon you.
Yours, in his sweet Lord Jesus,
S. R.
Aberdeen, March 14, 1637.
CLVIII.—To the Lady Busbie. [See
Letter CXXXIII.]
(CHRIST ALLWORTHY AND BEST AT OUR
LOWEST—SINFULNESS OF THE LAND—
PRAYERS.)
ISTRESS,—I know that ye are thinking sometimes what Christ
is doing in Zion, and that the haters of Zion may get the
bottom of our cup, and the burning coals of our furnace that we
have been tried in, those many years bygone. Oh, that this nation
would be awakened to cry mightily unto God, for the setting up of a
new tabernacle to Christ in Scotland. Oh, if this kingdom knew how
worthy Christ were of His room! His worth was ever above man's
estimation of Him.
And for myself I am pained at the heart, that I cannot find myself
disposed to leave myself and go wholly into Christ. Alas! that there
should be one bit of me out of Him, and that we leave too much
liberty and latitude for ourselves, and our own ease, and credit, and
pleasures, and so little room for all-love-worthy Christ. Oh, what
pains and charges it costeth Christ ere He get us! and when all is
done, we are not worth the having. It is a wonder that He should
seek the like of us. But love overlooketh blackness and fecklessness;
for if it had not been so, Christ would never have made so fair and
blessed a bargain with us as the covenant of grace is. I find that in
all our sufferings Christ is but redding marches, that every one of us
may say, "Mine, and thine;" and that men may know by their
crosses, how weak a bottom nature is to stand upon in trial; that the
end which our Lord intendeth, in all our sufferings, is to bring grace
into court and request amongst us. I should succumb and come
short of heaven, if I had no more than my own strength to support
me; and if Christ should say to me, "Either do or die," it were easy
to determine what should become of me. The choice were easy, for I
behoved to die if Christ should pass by with straitened bowels; and
who then would take us up in our straits? I know we may say that
Christ is kindest in His love, when we are at our weakest; and that if
Christ had not been to the fore, in our sad days, the waters had
gone over our soul. His mercy hath a set period, and appointed
place, how far and no farther the sea of affliction shall flow, and
where the waves thereof shall be stayed. He prescribeth how much
pain and sorrow, both for weight and measure, we must have. Ye
have, then, good cause to recall your love from all lovers, and give it
to Christ. He who is afflicted in all your afflictions, looketh not on you
in your sad hours with an insensible heart or dry eyes.
All the Lord's saints may see that it is lost love which is bestowed
upon this perishing world. Death and judgment will make men
lament that ever their miscarrying hearts carried them to lay and
lavish out their love upon false appearances and night-dreams. Alas!
that Christ should fare the worse, because of His own goodness in
making peace and the Gospel to ride together; and that we have
never yet weighed the worth of Christ in His ordinances, and that we
are like to be deprived of the well, ere we have tasted the sweetness
of the water. It may be that with watery eyes, and a wet face, and
wearied feet, we seek Christ, and shall not find Him. Oh, that this
land were humbled in time, and by prayers, cries, and humiliation,
would bring Christ in at the church-door again, now when His back is
turned towards us, and He is gone to the threshold, and His one
foot, as it were, is out of the door! I am sure that His departure is
our deserving; we have bought it with our iniquities; for even the
Lord's own children are fallen asleep, and, alas! professors are made
all of shows and fashions, and are not at pains to recover
themselves again. Every one hath his set measure of faith and
holiness, and contenteth himself with but a stinted measure of
godliness, as if that were enough to bring him to heaven. We forget
that as our gifts and light grow, so God's gain and the interest of His
talents, should grow also; and that we cannot pay God with the old
use and wont (as we use to speak) which we gave Him seven years
ago; for this were to mock the Lord, and to make price with Him as
we list. Oh, what difficulty is there in our Christian journey, and how
often come we short of many thousand things that are Christ's due!
and we consider not how far our dear Lord is behind with us.
Mistress, I cannot render you thanks, as I would, for your kindness
to my brother, an oppressed stranger; but I remember you unto the
Lord as I am able. I entreat you to think upon me, His prisoner, and
pray that the Lord would be pleased to give me room to speak to His
people in His name.
Grace, grace be with you.
Yours in his sweet Lord and Master,
S. R.
Aberdeen, 1637.
CLIX.—To John Fleming, Bailie of
Leith. [Letter LXVIII.]
(DIRECTIONS FOR CHRISTIAN CONDUCT.)
ORTHY AND DEARLY BELOVED IN THE LORD,—Grace, mercy,
and peace be unto you. I received your letter. I wish that I
could satisfy your desire in drawing up, and framing for you, a
Christian directory. But the learned have done it before me, more
judiciously than I can; especially Mr. Rogers,[241] Greenham,[242] and
Perkins.[243] Notwithstanding, I shall show you what I would have
been at myself; howbeit I came always short of my purpose.
1. That hours of the day, less or more time, for the word and prayer,
be given to God; not sparing the twelfth hour, or mid-day, howbeit it
should then be the shorter time.
2. In the midst of worldly employments, there should be some
thoughts of sin, death, judgment, and eternity, with at least a word
or two of ejaculatory prayer to God.
3. To beware of wandering of heart in private prayers.
4. Not to grudge, howbeit ye come from prayer without sense of joy.
Down-casting, sense of guiltiness, and hunger, are often best for us.
5. That the Lord's-day, from morning to night, be spent always
either in private or public worship.
6. That words be observed, wandering and idle thoughts be avoided,
sudden anger and desire of revenge, even of such as persecute the
truth, be guarded against; for we often mix our zeal with our wild-
fire.
7. That known, discovered, and revealed sins, that are against the
conscience, be eschewed, as most dangerous preparatives to
hardness of heart.
8. That in dealing with men, faith and truth in covenants and
trafficking be regarded, that we deal with all men in sincerity; that
conscience be made of idle and lying words; and that our carriage
be such, as that they who see it may speak honourably of our sweet
Master and profession.
9. I have been much challenged—1. For not referring all to God as
the last end; that I do not eat, drink, sleep, journey, speak, and
think for God. 2. That I have not benefited by good company; and
that I left not some word of conviction, even upon natural and
wicked men, as by reproving swearing in them; or because of being
a silent witness to their loose carriage; and because I intended not
in all companies to do good. 3. That the woes and calamities of the
kirk, and of particular professors, have not moved me. 4. That at the
reading of the life of David, Paul, and the like, when it humbled me,
I (coming so far short of their holiness) laboured not to imitate
them, afar off at least, according to the measure of God's grace. 5.
That unrepented sins of youth were not looked to, and lamented for.
6. That sudden stirrings of pride, lust, revenge, love of honours,
were not resisted and mourned for. 7. That my charity was cold. 8.
That the experiences I had of God's hearing me, in this and the
other particular, being gathered, yet in a new trouble I had always
(once at least) my faith to seek, as if I were to begin at A, B, C
again. 9. That I have not more boldly contradicted the enemies
speaking against the truth, either in public church meetings, or at
tables, or ordinary conference. 10. That in great troubles I have
received false reports of Christ's love, and misbelieved Him in His
chastening; whereas the event hath said, "All was in mercy." 11.
Nothing more moveth me, and weighteth my soul, than that I could
never from[244] my heart, in my prosperity, so wrestle in prayer with
God, nor be so dead to the world, so hungry and sick of love for
Christ, so heavenly-minded, as when ten stone-weight of a heavy
cross was upon me. 12. That the cross extorted vows of new
obedience, which ease hath blown away, as chaff before the wind.
13. That practice was so short and narrow, and light so long and
broad. 14. That death hath not been often meditated upon. 15. That
I have not been careful of gaining others to Christ. 16. That my
grace and gifts bring forth little or no thankfulness.
There are some things, also, whereby I have been helped, as—1. I
have been benefited by riding alone a long journey, in giving that
time to prayer. 2. By abstinence, and giving days to God. 3. By
praying for others; for by making an errand to God for them, I have
gotten something for myself. 4. I have been really confirmed, in
many particulars, that God heareth prayers; and, therefore, I used to
pray for anything, of how little importance soever. 5. He enabled me
to make no question, that this mocked way, which is nicknamed, is
the only way to heaven.
Sir, these and many more occurrences in your life, should be looked
into; and, 1. Thoughts of Atheism should be watched over, as, "If
there be a God in heaven?" which will trouble and assault the best at
some times. 2. Growth in grace should be cared for above all things;
and falling from our first love mourned for. 3. Conscience made of
praying for the enemies, who are blinded.
Sir, I thank you most kindly for the care of my brother, and of me
also. I hope it is laid up for you, and remembered in heaven.
I am still ashamed with Christ's kindness to such a sinner as I am.
He hath left a fire in my heart, that hell cannot cast water on, to
quench or extinguish it. Help me to praise, and pray for me, for ye
have a prisoner's blessing and prayers.
Remember my love to your wife. Grace be with you.
Yours in Christ Jesus,
S. R.
Aberdeen, March 15, 1637.
CLX.—To Alexander Gordon of
Earlston.
(HUNGERING AFTER CHRIST HIMSELF
RATHER THAN HIS LOVE.)
UCH HONOURED AND WORTHY SIR,—Grace, mercy, and
peace be unto you.—I long to hear from you. I have received
few letters since I came hither; I am in need of a word. A dry plant
should have some watering.
My case betwixt Christ my Lord, and me, standeth between love and
jealousy, faith and suspicion of His love; it is a marvel He keepeth
house with me. I make many pleas with Christ, but He maketh as
many agreements with me. I think His unchangeable love hath said,
"I defy thee to break Me and change Me." If Christ had such
changeable and new thoughts of my salvation as I have of it, I think
I should then be at a sad loss. He humoureth not a fool like me in
my unbelief, but rebuketh me, and fathereth kindness upon me.
Christ is more like the poor friend and needy prisoner begging love,
than I am. I cannot, for shame, get Christ said "nay" of my whole
love, for He will not want His errand for the seeking. God be thanked
that my Bridegroom tireth not of wooing. Honour to Him! He is a
wilful[245] suitor of my soul. But as love is His, pain is mine, that I
have nothing to give Him. His account-book is full of my debts of
mercy, kindness, and free love towards me. Oh that I might read
with watery eyes! Oh that He would give me the interest of interest
to pay back! Or rather, my soul's desire is, that He would comprise
my person, soul and body, love, joy, confidence, fear, sorrow, and
desire, and drive the poind, and let me be rouped, and sold to
Christ, and taken home to my creditor's house and fireside.
The Lord knoweth that, if I could, I would sell myself without
reversion to Christ. O sweet Lord Jesus, make a market, and overbid
all my buyers! I dare swear that there is a mystery in Christ which I
never saw; a mystery of love. Oh, if He would lay by the lap of the
covering that is over it, and let my greening soul see it! I would
break the door, and be in upon Him, to get a wombful of love; for I
am an hungered and famished soul. Oh, sir, if you, or any other,
would tell Him how sick my soul is, dying for want of a hearty
draught of Christ's love! Oh, if I could dote (if I may make use of
that word in this case) as much upon Himself as I do upon His love!
It is a pity that Christ Himself should not rather be my heart's
choice, than Christ's manifested love. It would satisfy me, in some
measure, if I had any bud to give for His love. Shall I offer Him my
praises? Alas! He is more than praises. I give it over to get Him
exalted according to His worth, which is above what can be known.
Yet all this time I am tempting Him, to see if there be both love and
anger in Him against me. I am plucked from His flock (dear to me!),
and from feeding His lambs; I go, therefore, in sackcloth, as one
who hath lost the wife of his youth. Grief and sorrow are suspicious,
and spew out against Him the smoke of jealousies; and I say often,
"Show me wherefore Thou contendest with me. Tell me, O Lord:
read the process against me." But I know that I cannot answer His
allegations; I shall lose the cause when it cometh to open pleading.
Oh, if I could force my heart to believe dreams to be dreams! Yet
when Christ giveth my fears the lie, and saith to me, "Thou art a
liar," then I am glad. I resolve to hope to be quiet, and to lie on the
brink on my side, till the water fall and the ford be ridable. And,
howbeit there be pain upon me, in longing for deliverance that I may
speak of Him in the great congregation, yet I think there is joy in
that pain and on-waiting; and I even rejoice that He putteth me off
for a time, and shifteth me. Oh, if I could wait on for all eternity,
howbeit I should never get my soul's desire, so being He were
glorified! I would wish my pain and my ministry could live long to
serve Him; for I know that I am a clay vessel, and made for His use.
Oh, if my very broken sherds could serve to glorify Him! I desire
Christ's grace to be willingly content, that my hell (excepting His
hatred and displeasure, which I put out of all play, for submission to
this is not called for) were a preaching of His glory to men and
angels for ever and ever! When all is done, what can I add to Him?
or what can such a clay-shadow as I do? I know that He needeth
not me. I have cause to be grieved, and to melt away in tears, if I
had grace to do it (Lord, grant it to me!), to see my Well-beloved's
fair face spitted upon by dogs, to see loons pulling the crown off my
royal King's head; to see my harlot-mother and my sweet Father
agree so ill, that they are going to skail and give up house. My Lord's
palace is now a nest of unclean birds. Oh, if harlot, harlot Scotland
would rue upon her provoked Lord, and pity her good Husband, who
is broken with her whorish heart! But these things are hid from her
eyes.
I have heard of late of your new trial by the Bishop of Galloway.[246]
Fear not clay, worms' meat. Let truth and Christ get no wrong in
your hand. It is your gain if Christ be glorified; and your glory to be
Christ's witness. I persuade you, that your sufferings are Christ's
advantage and victory; for He is pleased to reckon them so. Let me
hear from you. Christ is but winning a clean kirk out of the fire; He
will win this play. He will not be in your common for any charges ye
are at in His service. He is not poor, to sit in your debt; He will repay
an hundred-fold more, it may be, even in this life.
The prayers and blessings of Christ's prisoner be with you.
Your brother, in his sweet Lord Jesus,
S. R.
Aberdeen, 1637.
CLXI.—To John Stuart, Provost of
Ayr.
[John Stuart, Provost of Ayr, is described by Livingstone as "a
godly and zealous Christian of a long standing," and from his
earliest years. Inheriting, after the death of his father,
considerable property, he largely applied it to benevolent
purposes. Such was his disinterested love to those who were
the friends of Christ and His truth, that he called a number of
them whose straitened condition he knew, to meet with him in
Edinburgh; and after some time spent in prayer, told them he
had brought a little money to lend to each of them, which they
were not to offer to pay back till he required it, at the same
time requiring them to promise not to make this known during
his life. Not long after (the plague raging with severity in Ayr,
and trade becoming, in consequence, much depressed) he
himself fell into pecuniary difficulties, which made him at that
time remove from the country. Borrowing a little money, he
went over to France, and coming to Rochelle, loaded a ship with
salt and other commodities, which he purchased at a very cheap
rate. He then returned the nearest way to England, and thence
to Ayr, in expectation of the ship's return. After waiting long, he
was informed that it was taken by the Turks, which, considering
the loss which others in that case would sustain, much afflicted
him. But it at last arrived in the Road. It was on this occasion
that his friend John Kennedy, going out to the vessel in a small
boat, was driven away by a storm. (See notice of Kennedy,
Letter LXXV.) Stuart having sold the commodities which he
brought from France, not only was enabled by the profits to pay
all his debts, but cleared twenty thousand merks. (Fleming's
"Fulfilling of the Scriptures.") He joined with Mr. Blair, Mr.
Livingstone, and others, in their plan of emigrating to New
England, though they were forced to give it up. This good man
was much afflicted on his death-bed, so that one day he said, "I
testify, that except when I slept, or was in business, I was not
these ten years without thoughts of God, so long as I would be
in going from my own house to the cross; and yet I doubt
myself, and am in great agony, yea, at the brink of despair." But
a day or two before he died, all his doubts were dispelled; and
to Mr. Ferguson, the pious minister of Ayr, he said, referring to
his struggle with temptations at that time, "I have been fighting
and working out my salvation with fear and trembling, and now
I bless God it is perfected, sealed, confirmed, and all fears are
gone."]

(COMMERCIAL MISFORTUNES—SERVICE-
BOOK—BLESSEDNESS OF TRIAL.)
UCH HONOURED SIR,—Grace, mercy, and peace be unto you.
I long to hear from you, being now removed from my flock,
and the prisoner of Christ at Aberdeen. I would not have you to
think it strange that your journey to New England hath gotten such a
dash.[247] It indeed hath made my heart heavy; yet I know it is no
dumb providence, but a speaking one, whereby our Lord speaketh
His mind to you, though for the present ye do not well understand
what He saith. However it be, He who sitteth upon the floods hath
shown you His marvellous kindness in the great depths. I know that
your loss is great, and your hope is gone far against you; but I
entreat you, sir, expound aright our Lord's laying all hindrances in
the way. I persuade myself that your heart aimeth at the footsteps
of the flock, to feed beside the shepherds' tents, and to dwell beside
Him whom your soul loveth; and that it is your desire to remain in
the wilderness, where the Woman is kept from the Dragon. (Rev. xii.
14.) And this being your desire, remember that a poor prisoner of
Christ said it to you, that that miscarried journey is with child to you
of mercy and consolation; and shall bring forth a fair birth on which
the Lord will attend. Wait on; "He that believeth maketh not haste"
(Isa. xxviii. 16).
I hope that ye have been asking what the Lord meaneth, and what
further may be His will, in reference to your return. My dear brother,
let God make of you what He will, He will end all with consolation,
and will make glory out of your sufferings; and would you wish
better work? This water was in your way to heaven, and written in
your Lord's book; ye behoved to cross it, and, therefore, kiss His
wise and unerring providence. Let not the censures of men, who see
but the outside of things, and scarce well that, abate your courage
and rejoicing in the Lord. Howbeit your faith seeth but the black side
of providence; yet it hath a better side, and God will let you see it.
Learn to believe Christ better than His strokes, Himself and His
promises better than His glooms. Dashes and disappointments are
not canonical Scripture; fighting for the promised land seemed to cry
to God's promise, "Thou liest." If our Lord ride upon a straw, His
horse shall neither stumble nor fall. "For we know that all things
work together for good to them that love God" (Rom. viii. 28); ergo,
shipwreck, losses, etc., work together for the good of them that love
God. Hence I infer, that losses, disappointments, ill-tongues, loss of
friends, houses, or country, are God's workmen, set on work to work
out good to you, out of everything that befalleth you. Let not the
Lord's dealing seem harsh, rough, or unfatherly, because it is
unpleasant. When the Lord's blessed will bloweth across your
desires, it is best, in humility, to strike sail to Him, and to be willing
to be led any way our Lord pleaseth. It is a point of denial of
yourself, to be as if ye had not a will, but had made a free
disposition of it to God, and had sold it over to Him; and to make
use of His will for your own is both true holiness, and your ease and
peace. Ye know not what the Lord is working out of this, but ye shall
know it hereafter.
And what I write to you, I write to your wife. I compassionate her
case, but entreat her not to fear nor faint. This journey is a part of
her wilderness to heaven and the promised land, and there are
fewer miles behind. It is nearer the dawning of the day to her than
when she went out of Scotland. I should be glad to hear that ye and
she have comfort and courage in the Lord.
Now, as concerning our kirk; our Service-Book is ordained, by open
proclamation and sound of trumpet, to be read in all the kirks of the
kingdom.[248] Our prelates are to meet this month about our Canons,
[249]
and for a reconciliation betwixt us and the Lutherans. The
Professors of Aberdeen University are charged to draw up the
Articles of an uniform Confession; but reconciliation with Popery is
intended. This is the day of Jacob's visitation; the ways of Zion
mourn, our gold is become dim, the sun is gone down upon our
prophets. A dry wind, but neither to fan nor to cleanse, is coming
upon this land; and all our ill is coming from the multiplied
transgressions of this land, and from the friends and lovers of Babel
among us. "The violence done to me and to my flesh be upon thee,
Babylon, shall the inhabitant of Zion say; and, My blood upon the
inhabitants of Chaldea, shall Jerusalem say."[250]
Now for myself: I was three days before the High Commission, and
accused of treason preached against our King. (A minister being
witness, went well nigh to swear it.) God hath saved me from their
malice. 1stly, They have deprived me of my ministry; 2ndly, Silenced
me, that I exercise no part of the ministerial function within this
kingdom, under the pain of rebellion; 3rdly, Confined my person
within the town of Aberdeen, where I find the ministers working for
my confinement in Caithness or Orkney, far from them, because
some people here (willing to be edified) resort to me. At my first
entry, I had heavy challenges within me, and a court fenced (but I
hope not in Christ's name), wherein it was asserted that my Lord
would have no more of my services, and was tired of me; and, like a
fool, I summoned Christ also for unkindness. My soul fainted, and I
refused comfort, and said, "What ailed Christ at me? for I desired to
be faithful in His house." Thus, in my rovings and mistakings, my
Lord Jesus bestowed mercy on me, who am less than the least of all
saints. I lay upon the dust, and bought a plea from Satan against
Christ, and He was content to sell it. But at length Christ did show
Himself friends with me, and in mercy pardoned and passed my part
of it, and only complained that a court should be holden in His
bounds without His allowance. Now I pass from my compearance;
and, as if Christ had done the fault, He hath made the mends, and
returned to my soul; so that now His poor prisoner feedeth on the
feasts of love. My adversaries know not what a courtier I am now
with my Royal King, for whose crown I now suffer. It is but our soft
and lazy flesh that hath raised an ill report of the cross of Christ. O
sweet, sweet is His yoke! Christ's chains are of pure gold; sufferings
for Him are perfumed. I would not give my weeping for the laughing
of all the fourteen prelates; I would not exchange my sadness with
the world's joy. O lovely, lovely Jesus, how sweet must Thy kisses
be, when Thy cross smelleth so sweetly! Oh, if all the three
kingdoms had part of my love-feast, and of the comfort of a dawted
prisoner!
Dear Brother, I charge you to praise for me, and to seek help of our
acquaintance there to help me to praise. Why should I smother
Christ's honesty to me? My heart is taken up with this, that my
silence and sufferings may preach. I beseech you in the bowels of
Christ, to help me to praise. Remember my love to your wife, to Mr.
Blair, and Mr. Livingstone, and Mr. Cunningham. Let me hear from
you, for I am anxious what to do. If I saw a call for New England, I
would follow it. Grace be with you.
Yours in our Lord Jesus,
S. R.
Aberdeen, 1637.
CLXII.—To John Stuart, Provost of
Ayr.
(THE BURDEN OF A SILENCED MINISTER—
SPIRITUAL SHORTCOMINGS.)
UCH HONOURED AND DEAREST IN CHRIST,—Grace, mercy,
and peace from God our Father, and from our Lord Jesus
Christ, be upon you.
I expected the comfort of a letter to a prisoner from you, ere now. I
am here, Sir, putting off a part of my inch of time; and when I
awake first in the morning (which is always with great heaviness and
sadness), this question is brought to my mind, "Am I serving God or
not?" Not that I doubt of the truth of this honourable cause wherein
I am engaged; I dare venture into eternity, and before my Judge,
that I now suffer for the truth—because that I cannot endure that
my Master, who is a freeborn King, should pay tribute to any of the
shields or potsherds of the earth. Oh that I could hold the crown
upon my princely King's head with my sinful arm, howbeit it should
be struck from me in that service, from the shoulder-blade. But my
closed mouth, my dumb Sabbaths, the memory of my communion
with Christ, in many fair, fair days in Anwoth, whereas now my
Master getteth no service of my tongue as then, hath almost broken
my faith in two halves. Yet in my deepest apprehensions of His
anger, I see through a cloud that I am wrong; and He, in love to my
soul, hath taken up the controversy betwixt faith and apprehensions,
and a decreet is passed on Christ's side of it, and I subscribe the
decreet. The Lord is equal in His ways, but my guiltiness often
overmastereth my believing. I have not been well known: for except
as to open outbreakings, I want nothing of what Judas and Cain
had; only He hath been pleased to prevent me in mercy, and to cast
me into a fever of love for Himself, and His absence maketh my
fever most painful. And beside, He hath visited my soul and watered
it with His comforts. But yet I have not what I would. The want of
real and felt possession is my only death. I know that Christ pitieth
me in this.
The great men, my friends that did[251] for me, are dried up like
winter-brooks of water. All say, "No dealing for that man; his best
will be to be gone out of the kingdom." So I see they tire of me. But,
believe me, I am most gladly content that Christ breaketh all my
idols in pieces. It hath put a new edge upon my blunted love to
Christ; I see that He is jealous of my love, and will have all to
Himself. In a word, these six things are my burden: 1. I am not in
the vineyard as others are; it may be, because Christ thinketh me a
withered tree, not worth its room. But God forbid! 2. Woe, woe, woe
is coming upon my harlot-mother, this apostate kirk! The time is
coming when we shall wish for doves' wings to flee and hide us. Oh,
for the desolation of this land! 3. I see my dear Master Christ going
His lone (as it were), mourning in sackcloth. His fainting friends fear
that King Jesus shall lose the field. But He must carry the day. 4. My
guiltiness and the sins of youth are come up against me, and they
would come into the plea in my sufferings, as deserving causes in
God's justice; but I pray God, for Christ's sake, that he may never
give them that room. 5. Woe is me, that I cannot get my royal,
dreadful, mighty, and glorious Prince of the kings of the earth set on
high. Sir, ye may help me and pity me in this; and bow your knee,
and bless His name, and desire others to do it, that He hath been
pleased, in my sufferings, to make Atheists, Papists, and enemies
about me say, "It is like that God is with this prisoner." Let hell and
the powers of hell (I care not) be let loose against me to do their
worst, so being that Christ, and my Father, and His Father, be
magnified in my sufferings. 6. Christ's love hath pained me: for
howbeit His presence hath shamed me, and drowned me in debt,
yet He often goeth away when my love to Him is burning. He
seemeth to look like a proud wooer, who will not look upon a poor
match that is dying of love. I will not say He is lordly. But I know He
is wise in hiding Himself from a child and a fool, who maketh an idol
and a god of one of Christ's kisses, which is idolatry. I fear that I
adore His comforts more than Himself, and that I love the apples of
life better than the tree of life.
Sir, write to me. Commend me to your wife. Mercy be her portion.
Grace be with you.
Yours, in his dearest Lord Jesus,
S. R.
Aberdeen, 1637.
CLXIII.—To John Stuart, Provost of
Ayr.
(VIEW OF TRIALS PAST—HARD THOUGHTS OF
CHRIST—CROSSES—HOPE.)
ORTHY AND DEARLY BELOVED IN OUR LORD,—Grace, mercy,
and peace be to you.—I was refreshed and comforted with
your letter. What I wrote to you, for your comfort, I do not
remember; but I believe that love will prophesy homeward,[252] as it
would have it. I wish that I could help you to praise His great and
holy name who keepeth the feet of His saints, and hath numbered
all your goings. I know that our dearest Lord will pardon and pass by
our honest errors and mistakes, when we mind His honour; yet I
know that none of you have seen the other half, and the hidden
side, of your wonderful return home to us again. I am confident ye
shall yet say, that God's mercy blew your sails back to Ireland again.
Worthy and dear Sir, I cannot but give you an account of my present
estate, that ye may go an errand for me to my high and royal
Master, of whom I boast all the day. I am as proud of His love (nay, I
bless myself, and boast more of my present lot) as any poor man
can be of an earthly king's court, or of a kingdom. First, I am very
often turning both the sides of my cross, especially my dumb and
silent Sabbaths; not because I desire to find a crook or defect in my
Lord's love, but because my love is sick with fancies and fear.
Whether or not the Lord hath a process leading against my
guiltiness, that I have not yet well seen, I know not. My desire is to
ride fair, and not to spark dirt (if, with reverence to Him, I may be
permitted to make use of such a word) in the face of my only, only
Well-beloved; but fear of guiltiness is a talebearer betwixt me and
Christ, and is still whispering ill tales of my Lord, to weaken my faith.
I had rather that a cloud went over my comforts by these messages,
than that my faith should be hurt; for, if my Lord get no wrong by
me, verily I desire grace not to care what become of me. I desire to
give no faith nor credit to my sorrow, that can make a lie of my best
friend Christ. Woe, woe be to them all who speak ill of Christ! Hence
these thoughts awake with me in the morning, and go to bed with
me. Oh, what service can a dumb body do in Christ's house! Oh, I
think the word of God is imprisoned also! Oh, I am a dry tree! Alas, I
can neither plant nor water! Oh, if my Lord would make but dung of
me, to fatten and make fertile His own corn-ridges in Mount Zion!
Oh, if I might but speak to three or four herdboys[253] of my worthy
Master, I would be satisfied to be the meanest and most obscure of
all the pastors in this land, and to live in any place, in any of Christ's
basest outhouses! But He saith, "Sirrah, I will not send you; I have
no errands for you thereaway." My desire to serve Him is sick of
jealousy, lest He be unwilling to employ me. Secondly, This is
seconded by another. Oh! all that I have done in Anwoth, the fair
work that my Master began there, is like a bird dying in the shell;
and what will I then have to show of all my labour, in the day of my
compearance before Him, when the Master of the vineyard calleth
the labourers, and giveth them their hire? Thirdly, But truly, when
Christ's sweet wind is in the right airth, I repent, and I pray Christ to
take law-burrows of my quarrelous unbelieving sadness and sorrow.
Lord, rebuke them that put ill betwixt a poor servant like me and his
good Master. Then I say, whether the black cross will or not, I must
climb on hands and feet up to my Lord. I am now ruing from my
heart that I pleasured the law (my old dead husband) so far as to
apprehend wrath in my sweet Lord Jesus. I had far rather take a hire
to plead for the grace of God, for I think myself Christ's sworn
debtor; and the truth is (to speak of my Lord what I cannot deny), I
am over head and ears, drowned in many obligations to His love and
mercy.
He handleth me some time so, that I am ashamed almost to seek
more for a four-hours, but to live content (till the marriage-supper of
the Lamb) with that which He giveth. But I know not how greedy
and how ill to please love is. For either my Lord Jesus hath taught
me ill manners, not to be content with a seat, except my head lie in
His bosom, and except I be fed with the fatness of His house; or
else I am grown impatiently dainty, and ill to please, as if Christ
were obliged, under this cross, to do no other thing but bear me in
His arms, and as if I had claim by merit for my suffering for Him. But
I wish He would give me grace to learn to go on my own feet, and
to learn to do without His comforts, and to give thanks and believe,
when the sun is not in my firmament, and when my Well-beloved is
from home, and gone another errand. Oh, what sweet peace have I,
when I find that Christ holdeth and I draw; when I climb up and He
shuteth me down; when I grips Him and embrace Him, and He
seemeth to loose the grips and flee away from me! I think there is
even a sweet joy of faith, and contentedness, and peace, in His very
tempting unkindness, because my faith saith, "Christ is not in sad
earnest with me, but trying if I can be kind to His mask and cloud
that covereth Him, as well as to His fair face." I bless His great name
that I love His vail which goeth over His face, whill God send better;
for faith can kiss God's tempting reproaches when He nicknameth a
sinner, "A dog, not worthy to eat bread with the bairns" (Mark vii.
27, 28). I think it an honour that Christ miscalleth me, and
reproacheth me. I will take that well of Him, howbeit I would not
bear it well if another should be that homely; but because I am His
own (God be thanked), He may use me as He pleaseth. I must say,
the saints have a sweet life between them and Christ. There is much
sweet solace of love between Him and them, when He feedeth
among the lilies, and cometh into His garden, and maketh a feast of
honeycombs, and drinketh His wine and His milk, and crieth, "Eat, O
friends: drink, yea, drink abundantly, O well-beloved." One hour of
this labour is worth a shipful of the world's drunken and muddy joy;
nay, even the gate[254] to heaven is the sunny side of the brae, and
the very garden of the world. For the men of this world have their
own unchristened and profane crosses; and woe be to them and
their cursed crosses both; for their ills are salted with God's
vengeance, and our ills seasoned with our Father's blessing. So that
they are no fools who choose Christ, and sell all things for Him. It is
no bairns' market, nor a blind block; we know well what we get, and
what we give.
Now, for any resolution to go to any other kingdom, I dare not speak
one word.[255] My hopes of enlargement are cold, my hopes of re-
entry to my Master's ill-dressed vineyard again are far colder. I have
no seat for my faith to sit on, but bare omnipotency, and God's holy
arm and good-will. Here I desire to stay, and ride at anchor, and
winter, whill God send fair weather again, and be pleased to take
home to His house my harlot-mother. Oh, if her husband would be
that kind, as to go and fetch her out of the brothel-house, and chase
her lovers to the hills! But there will be sad days ere it come to that.
Remember my bonds. Grace be with you.
Yours, in our Lord Jesus,
S. R.
Aberdeen, 1637.
CLXIV.—To Ninian Mure [see Letter
CXCI.], one of the family of
Cassincarrie.
[We do not know more of Ninian Mure than that he was a
parishioner of Anwoth. The name "Mure" is found on several
tombs in the old churchyard, of which the oldest and most
interesting is the following, on the east side of the enclosed pile:

"Walking with God in purity of life,


In Christ I died, and endit all my strife.
For in my saul Christ here did dwell by grace;
Now dwells my saul in glory of His face.
Therefore my body shall not here remain,
But to full glory surely rise again."
"Marion Mure, goodwife of Cullindock,
Departed this life, anno 1612."]

(A YOUTH ADMONISHED.)
OVING FRIEND,—I received your letter. I entreat you now,
in the morning of your life, to seek the Lord and His face.
Beware of the follies of dangerous youth, a perilous time for your
soul. Love not the world. Keep faith and truth with all men in your
covenants and bargains. Walk with God, for He seeth you. Do
nothing but that which ye may and would do if your eye-strings
were breaking, and your breath growing cold. Ye heard the truth of
God from me, my dear heart, follow it, and forsake it not. Prize
Christ and salvation above all the world. To live after the guise and
course of the rest of the world will not bring you to heaven; without
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like