♪Music, Built

Act VII · The Craft

Part 44 of 68

Music for Picture and Play

Foundationsstarts at this level33 min of film12 chaptersprerequisites: Part 4, Part 11, Part 19, Part 27, Part 31, Part 40, Part 42, Part 43

What does music do to a picture, and how is music written for a scene of unknown length?

One animated scene of ours, three scores, three different films; then the same comic score cut to the picture and 0.6 s late, where every hit misses. The part covers what film music does (Boltz's experiment, Cohen's model), leitmotifs (a motive in three moods), spotting and hit points, and the tolerance of sync (sound may lag a picture by about 125 ms but lead it by only 45). It works the click track's arithmetic (frames per beat = 1440 / tempo) and finds, by scanning every tempo, the only two between 70 and 160 that put three hits within a frame of a beat: 88.28 (beats 4, 11 and 16) and 153.69; the nearest written click, 16-2, drifts 1.6 frames by the landing, and a variable click lands every hit exactly. It hears Hollywood harmony (chromatic mediants, the Lydian sound, the minor iv), ducks music under a model voice (6 dB more room in the speech band), and builds an adaptive score as a state machine driven by a simulated game, whose transitions wait half a boundary on average (0.25 s for a beat, 1 s for a bar, 2 s for a phrase). A sound chip of ours shows duty cycles, LFSR noise and the one-channel arpeggio chord. The Tune becomes a cue on a hit point, a leitmotif and an adaptive loop.

What you need. Part 4 for masking; Part 11 for meter; Part 19 for mixture; Part 27 for Wagner; Part 31 for transformations; Part 40 for the sidechain; Part 42 for motives and dice games; Part 43 for timing. Frame rates, state machines.

Ideas, mathematics and history
what film music does, leitmotifs, hit points and click-track arithmetic, adaptive game music, chiptune under hardware limits
What we build, compute and hear
one scene scored three ways; an adaptive score driven by a game

What you will be able to do

Foundations

  • Hear one scene read three ways by three scores, and music that misses its picture.
  • Hear a leitmotif change mood, and sound early, in sync and late against a picture.
  • Hear film harmony's chromatic mediants and minor iv, and music ducked under a voice.

Full course

  • Convert between tempo, frames per beat and click notation, and find tempos that hit a set of hit points.
  • Build an adaptive score as a state machine and compute its transition delays.
  • Compute a pulse wave's harmonics from its duty cycle, and build a chip's channels.

Research

  • Design a player study comparing transition rules for responsiveness and musical coherence.

Practice

  • Spot a scene and set its tempos; write segments, layers and stingers for middleware; mix under dialogue.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Foundations 22 min · Full course 32 min · Research 33 min · Practice 32 min.

  1. 0One scene, two cutsFoundations2 min
  2. 1What music does to an imageFoundations4 min
  3. 2LeitmotifsFoundations3 min
  4. 3Spotting and hit pointsFoundations3 min
  5. 4A tempo that hits three actionsFoundations4 min
  6. 5Harmony on screenFoundations2 min
  7. 6Music under dialogueFoundations3 min
  8. 7Music for playPractice3 min
  9. 8An adaptive score, playedPractice2 min
  10. 9Music under hardware limitsPractice4 min
  11. 10Frontier: scores that compose themselvesResearch2 min
  12. Variation 44, recap and problemsAll tracks2 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.

One scene, two cutsFoundations2 min

One scene with three scores is three different films. First, a test for your eyes and ears together. A short animated scene, shown twice, with the same music both times. Once the music was cut to the picture; the other time it starts a little late. Which one fits?

The first. In the second the music starts seconds late, so the door creaks after it has opened, the trill teeters over empty ground, and the thump lands after the figure. The same music, moved by a fraction of a second, stops belonging to the picture. Film composers spend much of their craft on exactly these fractions.

Music decides much of what a picture means: one scene with three scores is three different films. Film music is written to the picture, timed to the frame, with actions and cuts landing on the beat. Games broke that: nobody knows how long a scene will last, or what the player will do next. So game scores are systems: pieces that rearrange themselves as the game runs. This part works the arithmetic of hitting a cut on the beat, and builds a score that adapts.

A short history. So-called silent films were never silent: many screenings used live musicians or recorded accompaniment, while provision varied by place, venue and occasion. From the 1910s studios sent cue sheets, lists of scenes with suggested music and timings. From 1926 the Vitaphone system put a score on a disc synchronised with the film, and with sound film the score became part of the film itself, timed to the frame. Games, fifty years later, undid the fixed timing again.

Here is the plan. What music does to an image, and leitmotifs. Spotting, hit points and the click track's arithmetic. A tempo that hits three actions. Harmony on screen, and music under dialogue. Game music: an adaptive score driven by a simulated game. And a sound chip, and what its limits did to music.

1What music does to an imageFoundations4 min

Can music change what we see?

Does music change what we see? In 2001 Marilyn Boltz showed people the same ambiguous film clips with positive music, negative music or none. They judged the characters' intentions by the music: the same stranger was friendly or sinister. They even remembered the objects that fitted the music's mood better. Music does not decorate a picture; it tells the viewer how to read it. Annabel Cohen's model puts it this way: music's associations attach to whatever on screen is congruent with it.

Try it here. Our scene, three times, with three scores of ours, each written to the same three hit points: the door, the edge, and the landing. First comic, then suspense, then heroic. Watch the figure, and notice what you think it is.

Three different films. The comic score mirrors every footstep and action, and the figure becomes clumsy and harmless. The suspense score, with low drones, a heartbeat and stabs at the hits, makes it a figure in danger, or a dangerous one. The heroic score gives it a horn motive and full chords, and the fall becomes a triumphant landing.

What does film music do? It sets the place and period, with a harpsichord, a synthesizer or a folk instrument. It sets the mood, and tells us what a character feels or hides. It binds cuts together: music running across shots makes them one scene. It points: a sting tells us where to look, a motif who is near. And it paces: the score's tempo becomes the scene's.

Two theories give names to what we have just heard. In 1987 Claudia Gorbman described how the classical Hollywood score works: mostly unnoticed, cueing the story, binding the shots and signalling emotion. Three years later the composer and critic Michel Chion argued that sound and image are not added together, but combined. Sound adds value: it makes us see something in the picture, and we credit what we saw to the picture. And a sound and an image that coincide fuse into one event, whatever made them. Chion called that synchresis. It is why the late cut in this part's opening felt wrong, and why chapter three counts frames.

One more distinction. Source music, which film scholars call diegetic, is music the characters can hear: a radio, a band in the scene. Score is music only the audience hears. Films play with the line between them: a song on a radio swells into the score, or a character seems to answer it. Games blur it further, when the player's actions make the music inside the world. Either way, the audience reads the scene through it.

Our comic score hit everything. That style is called Mickey-Mousing, after the Disney cartoons of the 1930s, where composers such as Carl Stalling timed scores to the frame with click tracks, later at Warner Brothers too. Max Steiner's King Kong of 1933 brought the technique into a feature film. Used sparingly it is comic or emphatic; used everywhere, it tires. Chapter two turns to music that follows characters rather than actions.

2LeitmotifsFoundations3 min

How does music follow a character?

Music can follow characters, not only actions. Wagner's leitmotifs, from Part 27, gave each character, object or idea a motive and transformed it with the drama. Max Steiner and Erich Korngold, trained in Vienna, brought the idea to Hollywood in the 1930s, and John Williams revived the full symphonic leitmotif score in the 1970s and 1980s. A motive heard early comes back changed, and the audience reads the change as the story. These are Part 42's operations on a motive, used for drama.

Here is Part 42's motive, E, D, C, up to G, as a leitmotif in three moods. Heroic: a horn, the rhythm sharpened into a dotted figure, over strings. Tender: a flute, slower, an octave up. Menacing: low strings, in the minor, with the leap bent from a fifth to a tritone.

What makes all three the same motive? They keep the contour, down, down, then up by a leap, and the order of long and short notes. They change the instrument, register, tempo, mode and the size of the leap. Listeners recognise a motive by its contour and rhythm long after its exact intervals have changed, as Part 14 found for melodies. So a score can tell a story with one idea: who the character is stays the same, how they are changes. Chapter three turns to deciding where the music goes.

Games use leitmotifs too. A theme for a place, a character or an item found; a short jingle that becomes the sound of an event, a door unlocked or a level cleared. Heard hundreds of times, such motives have become some of the best-known music of their generation. A long-running series can carry a motive across decades, re-orchestrated for each new machine, so the motive outlives every sound chip that ever played it.

Some famous cases, described rather than played, since these scores are in copyright. Bernard Herrmann's Psycho of 1960 is for strings only, with the shower scene's shrieking glissandi. John Williams's Jaws, of 1975, is two notes a semitone apart, played faster as the shark comes nearer. Howard Shore's Lord of the Rings scores use dozens of leitmotifs, as Wagner's Ring does. The simplest motives travel furthest: a rhythm, an interval, a timbre.

3Spotting and hit pointsFoundations3 min

How exactly must music meet a picture?

Scoring starts with spotting. The director and composer watch the cut together and decide where music starts and stops, and what it does. Each cue gets start and end times, and hit points: moments the music must meet. This example uses twenty-four frames a second; actual delivery frame rates vary, so one frame lasts forty-one point seven milliseconds, and timecode names every frame. A cue is written so that its hits land on beats, or on strong parts of beats. Much of the craft is arithmetic, done before a note is written.

Spotting produces a cue sheet. Here is ours: the cue's first downbeat and the three hit points, each in seconds, in timecode, hours, minutes, seconds and frames, and as a frame count. The last column, the beat each hit falls on, is what chapter four will compute.

A question for your eyes and ears. A door slams, three times. Once the sound comes a hundred and twenty milliseconds early, once a hundred and twenty late, and once in sync. Which one is in sync?

The third. The first was late, the second early. Audio-visual synchrony judgments often tolerate more sound lag than lead, but the window depends on content, task, listener and equipment. Physical propagation can contribute, without making this a universal verdict on these examples.

How far can they drift before anyone notices? Broadcasters measured it for television: the cited television tests report approximate detection thresholds of milliseconds early, or up to about milliseconds late. The window is lopsided, for the same reason the early slam felt wrong. In frames, that is about one frame early and three late: these are content- and task-dependent guidance values, not guaranteed acceptability limits for every cue.

The tool for hitting is the click track. It is a metronome in the players' headphones, written in frames per beat. Frames per beat are twenty-four times sixty over the tempo: a hundred and twenty beats a minute is twelve frames, written twelve dash nought. The number after the dash counts eighths of a frame: fourteen dash three is fourteen and three-eighths frames, about a hundred beats a minute. A hit t seconds into a cue lands on beat t times the tempo over sixty, and the composer wants that number whole. Chapter four finds a tempo that makes three of them whole at once.

4A tempo that hits three actionsFoundations4 min

Which tempos land every hit on a beat?

Our scene has three hit points: the door opens at three point two seconds, the figure reaches the edge at seven point nine five, and it lands at eleven point four. The cue's first downbeat is at half a second. Which tempo puts a beat within one frame of all three?

Search every tempo from seventy to a hundred and sixty beats a minute, in steps of a hundredth. For each, measure how far, in frames, the worst of the three hits falls from its nearest beat. The curve is a thicket of near-misses. Only narrow windows dip below one frame: about beats a minute, where the hits fall on beats four, eleven and sixteen, and about . Allow hits on half-beats as well and there are windows; composers often do.

Here are that tempo's beats under the scene, numbered from the cue's first downbeat. Hear the comic score again, which was written at this tempo: its door chord falls on beat four, its trill starts on beat eleven, and its thump on beat sixteen.

Now a trap. The exact tempo is frames a beat. The nearest written click is dash , a slightly faster tempo. Its misses grow beat by beat: , and frames at the three hits. A tiny rounding error, multiplied by sixteen beats, becomes more than a frame and a half. Modern scoring software sets tempos to thousandths; older practice changed the click in the middle of a cue.

There are other ways to hit. A variable click changes tempo between hits: , then , then beats a minute lands every hit exactly, with changes too small to hear. A composer can hit on off-beats and half-beats, or start with a pickup. An orchestra can play in free time, the conductor watching streamers and punches, lines and flashes drawn on the film itself. Or the editor can move a cut by a frame or two: the picture bends too. Chapter five turns to the harmony film scores share.

Hear the variable click: the comic score's walking line, its tempo changing very slightly at each hit, so that every hit lands exactly. Can you hear the tempo change?

Judge it for yourself. Changes of a percent or two may escape notice in some passages, but are not universally inaudible, which is why a variable click is a composer's quiet friend.

In practice the picture often arrives with music already on it. Editors cut films to a temp track, existing music laid in while the film is assembled. Directors grow used to it, and the composer is asked for something like it, but new. Composers call this temp love, and its hidden cost is arithmetic: the cut's rhythm, and its hit points, were set by someone else's tempo. Chapter five turns to harmony.

5Harmony on screenFoundations2 min

Is there a Hollywood harmony? Frank Lehman's book of 2018 analyses the chords of film scores as a style. Many scores in this tonal symphonic tradition move between keys freely; film music also includes other harmonic and textural practices, often by chords a third apart. Selected chromatic-mediant voicings keep one note while others move by one or two semitones, Part 31's transformations L, P and R in combination. They sound strange and inevitable at once: a step outside the key that the ear can follow. And film has built a shared vocabulary in which certain progressions mean certain things.

Hear four progressions on strings and horn, each going out from C major and back. C to A flat major and back: awe and grandeur. C to E major: the bright, heroic lift. The Lydian sound, a D major chord over C, the raised fourth that scores use for wonder and flight. And the minor four, F minor in a major key, for nostalgia and loss.

Why do they work? C major to A flat major keeps C, lets E fall to E flat and G rise to A flat: a smooth move to a distant key. C to E keeps E, while C falls to B and G rises to G sharp: a lift towards brighter keys. In the Lydian sound, the F sharp is outside C major but asks for no resolution, so it floats. The minor four borrows A flat from C minor, a shadow over the major key: Part 19's mixture. And the meanings are also learned from films, as well as heard in the chords.

Genres have codes too. Horror: clusters, extended techniques, low drones and silence. Thrillers: ostinatos, synthesizer pulses, the ticking clock. Romance: strings, suspensions and the minor four. Many recent films favour sound design and texture over melody, the score as atmosphere, Part 30's world. Chapter six turns to the score's hardest partner, the human voice.

6Music under dialogueFoundations3 min

How does a score stay out of the actors' way?

On screen, the voice comes first: if a line is not understood, the scene fails. Speech intelligibility lives mostly between one and four kilohertz, in the consonants and upper formants of Part 8. Music in that band, at that moment, masks the words, as Part 4 showed. So the mixer lowers the music under every line: ducking, the sidechain of Part 40. Our dialogue is Part 17's model voice babbling vowels, which has a voice's spectrum but no words.

Hear a passage of strings and horn with the voice over it, first at full level, then with the music ducked by up to ten decibels whenever the voice speaks.

Measure the voice against the music in the speech band. Before ducking the voice is decibels below the music there; after, . The ten-decibel duck bought about six decibels over the whole passage, because the music comes back up in every pause.

Here is the duck. In blue, the voice's envelope, phrase by phrase. In gold, the music's gain: down by ten decibels as each phrase starts, and back up a quarter of a second after it ends. A good mix makes this inaudible: the music seems to make room by itself.

There are also rules for the whole programme. European broadcasters normalise to a target loudness, minus twenty-three LUFS under EBU R 128. EBU R 128 normally uses integrated programme loudness; dialogue-gated measurements belong to particular other delivery specifications, and music and effects get the room the dialogue leaves. Cinema mixes keep a wide range, quiet dialogue and very loud action, and home versions compress it. Part 57 builds the loudness meter itself.

Good scores make the mixer's job easy. Composers write around dialogue: thin textures, low or high registers, careful register and texture around the voice, without a universal ban on melody in its range. A solo clarinet under a tenor's line competes; sustained low strings may compete less, depending on levels and spectra. The final mix balances three stems, dialogue, music and effects, and cinema mixes aim the dialogue at a steady loudness, which Part 57 measures. Chapter seven turns to games, where nobody knows what happens next.

7Music for playPractice3 min

How do you score a scene of unknown length?

Game music started as loops. Space Invaders, in 1978, played a four-note bass loop that sped up as the invaders came down. By 1991 LucasArts' iMUSE system, designed by Michael Land and Peter McConnell, changed cue at musically sensible moments as the player moved through a scene. The problem is simple: a film cue has a known length, but a game state lasts as long as the player takes. So game music is built from pieces and rules, and the score is a program: Part 42's dice game, two centuries later, with a player rolling the dice.

Four techniques do most of the work. Horizontal resequencing: short segments that can follow one another in any allowed order. Vertical layering: stems that play together and fade in or out with the intensity. Transitions: wait for the next beat, bar or phrase, or cut at once with a bridging phrase. And stingers: short phrases fired at events, over whatever is playing. Middleware such as FMOD and Wwise lets composers build such rules without writing code.

Here is our adaptive score as a state machine. The game has four states: exploring, danger when an enemy is seen, combat when it attacks, and victory, which lasts three seconds before exploring again. Each state has a two-bar segment in its own key and texture, looped for as long as the state lasts. Intensity, which rises and falls smoothly with the state, chooses one to four layers: a pad, a bass, drums, and the motive in the brass. At each change a stinger sounds at once, and the new segment starts at the next bar line.

Hear the difference one transition makes. The player is exploring; at five point three seconds, combat starts. First the music switches at once, wherever it happens to be. Then it waits for the next bar line, with a stinger at the moment combat begins.

The first lurches: the new segment cuts in mid-bar. The second keeps the old music for seconds, but the stinger marks the moment, and the change lands on a downbeat.

What makes such a score work? These simple layers share tempo, harmonic plan and bar length; other adaptive systems can reconcile polymeter, changing keys or asynchronous textures. Segments must join: each ends where any allowed successor can begin, the dice game's trick again. Intensity changes only on beat boundaries, which aligns entries to the selected grid, though held notes can still cross that boundary. The composer writes the pieces and the joins; the game decides the order. Chapter eight plays a game and lets us hear its score.

8An adaptive score, playedPractice2 min

What does a game's score sound like as it happens?

Here is forty-eight seconds of a simulated game. Across the top, its states; below, the intensity, and the four layers as they come and go. The white ticks are state changes, where a stinger sounds; the dashed lines are the next bar lines, where the new segment begins. Listen for the music following the game.

Waiting for a musical boundary costs time. Over two hundred simulated games, a change waits on average a quarter of a second for the next beat, a second for the next bar, and two seconds for the next phrase. Half a boundary is the expectation if event phases are uniform relative to that boundary; correlated or scripted events can differ. The worst case is the whole length: almost four seconds of the wrong music for a phrase. In our game the bar-line delay averaged seconds; the stinger covers it.

An adaptive score raises a strange problem. It can never be heard whole: every playthrough is a different piece. So it is tested by playing, hours of sessions, listening for wrong music and bad joins, and logs of game states let a team replay the score's decisions offline, as we just did. Repetition is the enemy: players can hear the same loop for hours, so segments get variants. The composer becomes a designer of possibilities.

So every adaptive score trades responsiveness against musicality. Switch at once and the music lurches mid-phrase. Switch at the phrase and a fight can start in peaceful music. The usual answer is ours: a stinger now, and the full change at the next bar. The right choice depends on the game: a rhythm game must be exact, an exploration game can wait. Chapter nine turns to the machines that played the first game music.

9Music under hardware limitsPractice4 min

What can you play with three voices and a noise?

Early game sound used varied discrete and chip-based circuits; programmable sound chips shaped the examples here. The AY-3-8910 and SN76489 offered three tone channels plus noise generation, with different architectures: the AY shares its noise generator across channel mixers. Nintendo's console chip of 1983 had two pulse waves, a triangle, a noise channel and short samples, and the Commodore 64's SID of 1982 had three oscillators with a real filter. A few voices, crude waveforms, volumes in sixteen steps, registers changed fifty or sixty times a second. Our chip works in their manner: two pulse channels, a four-bit triangle, a noise channel from a shift register, updated sixty times a second.

The pulse channel's one timbre control is its duty cycle, the share of each cycle spent high. Hear A four at fifty, twenty-five and twelve and a half per cent. The harmonics follow a simple law: the k-th harmonic's strength is the sine of pi k times the duty, over k. At fifty per cent every even harmonic is missing, the hollow square wave; at twenty-five every fourth; at twelve and a half every eighth. Narrower pulses sound thinner and nasal.

The noise channel is not random at all. A fifteen-bit shift register combines two of its bits at each step and feeds the result back in. In its long mode it runs thirty-two thousand seven hundred and sixty-seven steps before repeating, and sounds like hiss; in its short mode the loop is short enough to have a pitch, a metallic buzz. Clocked fast with a short decay it is a hi-hat; slowly, a snare or an explosion. Hear the long mode, the short mode, and three noise drums.

A question for your ears. Two C major chords on our chip. One uses three channels sounding at once; the other uses a single channel. Which one uses only one?

The second. One channel steps through C, E and G, changing note times a second, once every frame of the console's display. That is too fast to hear as separate notes and too slow to fuse into a clean chord, and the buzz it makes became one of the signature sounds of chip music: a chord from a single voice, leaving the other channels free.

Here is the Tune's first two phrases on the chip, with every channel used: the melody on one pulse, the chords as arpeggios on the other, the bass on the triangle, and a short noise hit as a drum.

The chips grew. From the late 1980s, FM chips from Yamaha gave consoles and personal computers several voices with rich, changing timbres. FM, frequency modulation, lets one oscillator bend another's frequency and so makes many partials from two sine waves, as Part 52 will show. Then came sample playback, and then streamed recordings: by the 2000s a game could carry a recorded orchestra. The limit moved from the sound to the structure, to how the music adapts. Chapter ten looks at scores that compose themselves.

The limits became a style. Fast arpeggios for chords, echo made by repeating a note softer a moment later, drums from noise. Koji Kondo's score for Super Mario Bros., in 1985, fitted everything into the console's few channels. Melodies had to carry alone, and few voices make strong tunes. Chiptune is now a genre of its own, played on the old machines and new ones. Part 51 builds oscillators and filters from scratch.

10Frontier: scores that compose themselvesResearch2 min

Can a score be written for every possible playthrough?

Where is this going? Brian Eno wrote generative music for the game Spore in 2008: rules and samples that never play the same way twice. No Man's Sky, in 2016, cut a band's recordings into pieces and let the game reassemble them endlessly. Research systems compose to emotion targets, tension curves like Part 42's, driven by the game's state. Learned models now generate music to a description or a picture, Parts 65 and 66. The open question is control: keeping the composer's intention at every moment.

Psychology studies how all this works. Annabel Cohen's congruence-association model: the music's structure is first matched to the picture's, and then its meaning attaches to what matched. Eye tracking shows music can steer where viewers look within a shot. Accents that line up with visual events bind sound and image into one event: the hook's lesson. And players play differently with different music: faster, more cautious, or more lost. Part 46 asks how music makes expectation and emotion at all.

A concrete version. Take an adaptive score with several transition rules: at once, on the bar, on the phrase, with or without stingers. Have players play the same game with each, and measure how they play and how much they enjoy it. Measure how often the music was wrong: calm music in a fight, a lurch in mid-phrase. What transition rule best balances responsiveness and musical coherence for players? An answer would turn a craft rule of thumb into a measured design choice.

Variation 44, recap and problemsAll tracks2 min

Every part ends by doing something to the Tune with what it built. Here, three things. A cue: the tempo chosen so that fourteen beats carry the first two phrases to a hit point at seconds, where the brass lands. Then the first phrase as a leitmotif in three moods. And then an adaptive loop, gaining a layer on every pass.

Row forty-four of the ledger: seconds; the measurement is the cue's arithmetic, the tempo and click that land its last note on the hit.

What did we find? Music tells a viewer how to read a picture. A leitmotif keeps its contour and rhythm while its mood changes. Hits are arithmetic: beats equal seconds times tempo over sixty, to within a frame. Sound may lag a picture more than it may lead it. Adaptive scores are state machines, and waiting costs half a boundary on average under a uniform event-phase assumption. And hardware limits made a style: duty cycles, arpeggio chords and noise drums.

Five problems. One to compute, one to prove, one for your ears, one to build, and a research problem, marked with a star. Solutions are in this part's notes. Pause here.

Where does this come back? In the auditory scene, how the ear binds a sound to its source. In expectation and emotion. In oscillators and filters built from scratch. In the workstation and the sequencer. And in machines that compose, and generative audio.

And in practice. Film composers spot with the director, then set their tempos to the frame. Music editors cut, stretch and move cues whenever the picture changes. Game audio teams write segments, layers and stingers, and then the rules that join them. And mixers duck the music under dialogue and carve out the speech band.

The books and papers this part follows. The full list, with notes, is in the README.

Where it goes next. The auditory scene in Part 45; expectation and emotion in Part 46; oscillators in Part 51; FM in Part 52; the workstation in Part 53; loudness in Part 57; machines that compose in Part 65.

Key results

The part's results in one place, for revision.

Frames per beat\(\displaystyle f = 24 \times 60 / \text{tempo}\)
A hit\(\displaystyle \text{beat} = (t - t_0) \times \text{tempo} / 60\)
The scene\(\displaystyle 88.28 \text{ bpm: }\allowbreak \text{beats } 4, 11, 16\)
Waiting for a boundary\(\displaystyle E[\text{delay}] = u / 2\)
A pulse of duty d\(\displaystyle a_k \propto |\sin(\pi k d)| / k\)

Try it

Lab 44 · Music for picture and play, computed

Spot a scene of your own and find the tempos that hit it; see what rounding a click costs; and measure how long an adaptive score keeps the wrong music.

Figure produced by Lab 44: Music for picture and play, computed
Produced by the lab below, seed 0, in 0.5 s.
python -m videos.music.labs 44 needs numpy, scipy, matplotlib · download lab44.py · source on GitHub
tempos that hit every point within TOL frames                                            88.28 (click 16-2, beats [4.0, 11.0, 16.0]); 153.69 (click 9-3, beats [7.0, 19.0, 28.0])
the nearest written click 16-2 (88.62 bpm): misses in frames                             0.20, 0.05, 1.60
adaptive score, switching at 'bar': mean / worst delay (s); theory                       1.02 / 1.99; 1.00
pulse at duty 0.25: missing harmonics (of 16)                                            4, 8, 12, 16
ear problem: two clicks, then a slam meant for the third click; early, in sync or late?  late, in sync, in sync

A hit t seconds after the downbeat falls on beat t x bpm / 60; the finder scans tempos for the ones that make every such number nearly whole. Waiting for a boundary of length u costs u/2 on average. A pulse of duty d loses every harmonic k with k d whole.
The code (79 lines; it asserts its own result)
"""Lab 44: music for picture and play, computed: a tempo finder for your own hit points, click arithmetic, an
adaptive score's transition delays, and the chip's pulse spectra."""

import numpy as np

from videos.coursekit import labs
from explainer.music.monochord import SR, Clip, concat, mix
from explainer.music.monochord import screen as S
from videos.music.music44 import compute as C

TITLE = "Music for picture and play, computed"
GOAL = ("Spot a scene of your own and find the tempos that hit it; see what rounding a click costs; and measure how long "
        "an adaptive score keeps the wrong music.")
TASKS = [
    "Edit HITS and START. How many tempos between LO and HI hit all of them within TOL frames? Allow half-beats (SUB = 2).",
    "Change QUANTISE ('now', 'beat', 'bar', 'phrase') and BPM. Check that the mean delay is half the boundary's length.",
    "Change DUTY. Which harmonics vanish, and why?",
]
HITS = [3.2, 7.95, 11.4]
START = 0.5
LO, HI, TOL, SUB = 70.0, 160.0, 1.0, 1
QUANTISE = "bar"
BPM = 120.0
DUTY = 0.25


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()
    r = S.find_tempo(HITS, start=START, lo=LO, hi=HI, tol_frames=TOL, subdivision=SUB)
    sols = r["solutions"]
    lab.row("tempos that hit every point within TOL frames", "; ".join(f"{s['bpm']:.2f} (click {s['click'][0]}-{s['click'][1]}, beats {s['beats']})" for s in sols) or "none")
    if sols:
        b = min(sols, key=lambda s: s["worst_frames"])
        w, e = b["click"]
        cb = S.click_bpm(w, e)
        err = [abs(((h - START) / (60 / cb)) - round((h - START) / (60 / cb))) * (60 / cb) * 24 for h in HITS]
        lab.row(f"the nearest written click {w}-{e} ({cb:.2f} bpm): misses in frames", ", ".join(f"{x:.2f}" for x in err))
    sc = S.Score(BPM)
    d = [s["delay"] for seed_ in range(100) for s in S.adapt(S.simulate(seed_, 120.0), sc, QUANTISE)["switches"][1:]]
    unit = {"now": 0.0, "beat": sc.beat, "bar": sc.bar, "phrase": sc.bar * sc.segment_bars}[QUANTISE]
    assert abs(np.mean(d) - unit / 2) < 0.15
    lab.row(f"adaptive score, switching at '{QUANTISE}': mean / worst delay (s); theory", f"{np.mean(d):.2f} / {np.max(d):.2f}; {unit / 2:.2f}")
    h = S.pulse_harmonics(DUTY, 16)
    lab.row(f"pulse at duty {DUTY}: missing harmonics (of 16)", ", ".join(str(i + 1) for i, a in enumerate(h) if a < 1e-9) or "none")

    # sound: a click track over the hits; ear problem: door slams at random offsets
    beat = 60.0 / (min(sols, key=lambda s: s["worst_frames"])["bpm"] if sols else 120.0)
    parts, t = [], START
    while t < max(HITS) + 0.5:
        parts.append((Clip(C.piano(84, 0.08, 0.6), SR), t, -10.0))
        t += beat
    for hh in HITS:
        parts.append((Clip(C.P40.kick(), SR), hh, 0.0))
    clicks = Clip(mix(parts, duration=max(HITS) + 1.5).y, SR)
    slams, offs = [], []
    for i in range(3):
        off = float(rng.choice([-0.12, 0.0, 0.12]))
        ref = [(Clip(C.piano(84, 0.08, 0.6), SR), t0, -8.0) for t0 in (0.0, 0.5)]        # two clicks set the pulse
        slams.append(Clip(mix(ref + [(Clip(C.P40.kick(), SR), 1.0 + off, 0.0)], duration=2.0).y, SR))
        offs.append({-0.12: "early", 0.0: "in sync", 0.12: "late"}[off])
    lab.audio = concat([clicks] + slams, gap=1.0)
    lab.row("ear problem: two clicks, then a slam meant for the third click; early, in sync or late?", ", ".join(offs))

    fig, (ax1, ax2) = labs.figure(2)
    ax1.plot(r["bpm"], r["worst"], color="C0", lw=0.6)
    ax1.axhline(TOL, color=labs.GOLD, lw=1)
    ax1.set_ylim(0, 12)
    ax1.set_xlabel("tempo (bpm)")
    ax1.set_ylabel("worst miss (frames)")
    ax1.set_title("the tempo finder")
    ax2.bar(range(1, 17), h, color=labs.GOLD)
    ax2.set_xlabel("harmonic")
    ax2.set_title(f"pulse wave, duty {DUTY}")
    lab.fig = fig
    lab.note = ("A hit t seconds after the downbeat falls on beat t x bpm / 60; the finder scans tempos for the ones that make "
                "every such number nearly whole. Waiting for a boundary of length u costs u/2 on average. A pulse of duty d "
                "loses every harmonic k with k d whole.")
    return lab

Now change it

  1. Edit HITS and START. How many tempos between LO and HI hit all of them within TOL frames? Allow half-beats (SUB = 2).
  2. Change QUANTISE ('now', 'beat', 'bar', 'phrase') and BPM. Check that the mean delay is half the boundary's length.
  3. Change DUTY. Which harmonics vanish, and why?

Problems, with solutions

Try each problem before opening its solution.

  1. Compute. A hit falls 9.5 s after a cue's downbeat. Which tempos between 100 and 130 put it on a beat?

    Solution

    The hit falls on beat 9.5 × tempo / 60, so the tempo must be 60n / 9.5 for a whole number n: n = 16, 17, 18, 19 and 20 give 101.05, 107.37, 113.68, 120.00 and 126.32 beats a minute. 120 is the easy one: 19 beats, a 12-0 click.

  2. Prove. Prove that waiting for the next boundary of length u delays a randomly timed event by u/2 on average.

    Solution

    If the event's position within the boundary interval is uniform on [0, u), the wait is u minus that position, also uniform on (0, u], whose mean is u/2. The 200 simulated games give 0.25, 1.01 and 1.99 s for 0.5, 2 and 4 s boundaries.

  3. Ear. The lab plays door slams with random offsets; say early, in sync or late.

    Solution

    The lab prints them. Two clicks set a pulse and the slam should land on the third: a slam 120 ms early jumps ahead of the pulse, one 120 ms late drags; early is usually the easier to hear.

  4. Build. Add a state ("stealth") to the adaptive score, with its own segment and layers.

    Where to look. Add the state to screen.simulate's transitions and intensity levels, and a chord loop for it in STATE_C in videos/music/music44/compute.py; then adapt and render_game handle it. Give it a thin texture and a quiet pulse, and a stinger that differs from combat's.

  5. ★ Which transition rule best balances responsiveness and coherence for players?

    Where the frontier is. Build one game with several transition rules; have players play each; log play, enjoyment and every moment the music contradicts the game; model enjoyment against delay and the count of mid-phrase cuts.

Notes and sources

Sources

  • F. Karlin and R. Wright, On the Track (2nd ed., 2004); F. Lehman, Hollywood Harmony (2018); K. Collins, Game Sound (2008) and (ed.) From Pac-Man to Pop Music (2008).
  • M. G. Boltz, "Musical soundtracks as a schematic influence on the cognitive processing of filmed events", Music Perception (2001); A. J. Cohen, "Congruence-association model of music and multimedia" (2013).
  • ITU-R BT.1359, "Relative timing of sound and vision for broadcasting" (1998); EBU R 128, loudness normalisation.
  • M. Z. Land and P. N. McConnell, the iMUSE patent, US 5,315,057 (1994).
  • B. Eno and others on generative music for Spore (2008); the procedural soundtrack of No Man's Sky (2016).
  • C. Gorbman, Unheard Melodies: Narrative Film Music (1987), the principles of the classical score in chapter 1.
  • M. Chion, Audio-Vision: Sound on Screen (1990; tr. C. Gorbman, 1994): added value and synchresis, chapter 1.
About this partfrom its README

Part 44 of a sixty-eight-part course in music (see the series plan and the syllabus), the last part of Act VII, The Craft. One animated scene, three scores, three different films. Then a problem film composers never had: in a game nobody knows how long the scene will last. This part works the arithmetic of hitting a cut on the beat and builds a score that rearranges itself. The tools are Monochord's (explainer/music/monochord/screen.py). Every scene, cue, game and score is ours; film and game scores are described, never played. Published findings are the ones listed under Sources.

  • One scene, two cuts. An ear-and-eye question (the same score cut to the picture and 0.6 s late: which fits?); a short history (cue sheets, Vitaphone); music for picture and play; the plan.
  • 1. What music does to an image. Boltz's experiment; one scene, three scores (comic, suspense, heroic), heard; what film music does; Mickey-Mousing; source and score.
  • 2. Leitmotifs. From Wagner to Hollywood; Part 42's motive in three moods, heard; what the transformations keep; motives in games; motives on screen (described).
  • 3. Spotting and hit points. Spotting; a cue sheet for our scene; an ear-and-eye question (a door slam 120 ms early, in sync, late); the tolerance of sync (about 45 ms early, 125 ms late); the click track's arithmetic.
  • 4. A tempo that hits three actions. The problem; the worst miss for every tempo from 70 to 160 (two solutions: 88.28 on beats 4, 11 and 16, and 153.69; eight with half-beats); the beats under the scene, heard; the rounding trap (the 16-2 click drifts 1.6 frames); other ways to hit; a variable click, heard; the temp track.
  • 5. Harmony on screen. Lehman's Hollywood harmony; four progressions, heard (C–A♭–C, C–E–C, D/C, C–Fm–C); why they work; genre codes.
  • 6. Music under dialogue. The voice comes first; music ducked 10 dB under a model voice, heard (the voice gains 6 dB in the speech band); the duck drawn; loudness standards; writing for the mix.
  • 7. Music for play. From loops to systems (Space Invaders, iMUSE); the techniques; our score as a state machine; one change heard switching at once and at the bar line; what makes it work.
  • 8. An adaptive score, played. 48 seconds of a simulated game and its score, heard; what waiting for a boundary costs (0.25, 1.0 and 2.0 s on average for beat, bar and phrase, half the boundary as theory says); testing a score you cannot hear whole; responsive or musical?
  • 9. Music under hardware limits. Sound chips; one pulse at three duty cycles, heard, with its missing harmonics; the noise channel's shift register, heard; an ear question (a chord on three channels or one?); the Tune on the chip; after the chips; limits as a style.
  • 10. Frontier: scores that compose themselves. Generative and adaptive scoring; the cognition of film and game music; ★ research problem: which transition rule best balances responsiveness and coherence for players?
  • Variation 44, recap and problems. The Tune as a cue whose 14 beats land on a hit at 9.0 s (98.8 bpm, a 14-5 click), as a leitmotif in three moods, and as an adaptive loop gaining a layer each pass; the ledger; what we found; five problems; where it comes back; in practice; references; Part 45.
What is computed and built

python -m videos.music.music44.compute (under a minute) fills .cache/music44/.

Item What it computes Checked against
scene, hook, three the hit points, the tempo finder, the rounded and variable clicks; the scene's scores every hit within a frame; the variable click lands exactly (tests)
sync three door slams —
motif, harmony a leitmotif in three moods; four progressions —
mix ducking under a model voice; the speech-band ratio the ratio improves (tests)
game, switch, quantise a simulated game, its adaptive score, transition delays over 200 games mean delay = boundary / 2 (tests)
duty, noise, arp, chip the chip's pulse, noise, arpeggio; the Tune on the chip missing harmonics; 4-bit triangle (tests)
tune, variation Variation 44 the cue lands on its hit (tests)

Monochord's tools are held in tests/music/test_screen.py; this part's claims and clips in tests/music/test_music44.py.

Sounds. Part 7's piano and Part 38's plucked bass (physical models), Part 41's additive orchestra, Part 40's drums, Part 17's model voice (it sings vowels, not words) and a sound chip of ours. Clips that mix the additive orchestra or the chip in are labelled synthesized. There are no recordings.

What the models are, and are not. The scene is a cartoon of ours, its music written to its hit points. The sync tolerances are the ITU's broadcast figures. The game is a four-state simulation, not a real game; the adaptive score is a small system of ours in the manner of middleware. The chip is our own design in the manner of 1980s chips, not an emulation of any of them.

Notes

Frame arithmetic uses 24 fps for this example; actual formats vary. Synchrony windows and tempo-change detection depend on content, task and listeners. Chromatic-mediant associations describe a film-scoring tradition, not fixed chord emotions. EBU R 128 uses integrated programme loudness, distinct from particular dialogue-gated specifications. Adaptive transition delay averages half a boundary only for uniform event phases. Layer compatibility rules are choices of this simple engine, not universal requirements. The vowel-only dialogue demonstrates band energy and ducking, not measured word intelligibility.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: an ear-and-eye question (cut to picture, or 0.6 s late?); a short history; music for picture and play; the plan.
  2. What music does to an image: Boltz; one scene, three scores, heard; what film music does; Mickey-Mousing; source and score.
  3. Leitmotifs: Wagner to Hollywood; a motive in three moods, heard; what transformations keep; motives in games; motives on screen.
  4. Spotting and hit points: spotting; a cue sheet; an ear-and-eye question (early, in sync, late?); the tolerance of sync; click arithmetic.
  5. A tempo that hits three actions: the problem; the worst miss for every tempo; the beats heard under the scene; the rounding trap; other ways; a variable click heard; the temp track.
  6. Harmony on screen: Hollywood harmony; four progressions heard; why they work; genre codes.
  7. Music under dialogue: the voice first; ducking heard; the duck drawn; loudness standards; writing for the mix.
  8. Music for play: loops to systems; the techniques; a state machine; one change heard two ways; what makes it work.
  9. An adaptive score, played: a game and its score heard; what waiting costs; playtesting; responsive or musical.
  10. Music under hardware limits: chips; duty cycles heard; the noise channel heard; an ear question (one channel or three?); the Tune on the chip; after the chips; limits as a style.
  11. Frontier: generative and adaptive scoring; cognition; the research problem.
  12. Variation 44: the Tune as a cue, a leitmotif in three moods, and an adaptive loop. Outro: problems, payoffs.

Covers: what music does to an image; leitmotifs; spotting and hit points; click-track arithmetic; harmony and affect on screen; mixing against dialogue; game music: resequencing, layering, transitions, stingers; chiptune under three-channel limits; middleware. Built and computed: monochord/screen.py: click arithmetic; a tempo finder over every tempo (two tempos between 70 and 160 hit our three hit points within a frame, 88.28 on beats 4, 11 and 16; the rounded 16-2 click drifts 1.6 frames; a variable click lands them exactly); ducking with the speech-band ratio (+6 dB for the voice); a simulated game driving an adaptive score as a state machine, with transition delays of half a boundary on average over 200 games; a sound chip of ours (pulse duty cycles and their missing harmonics, a 4-bit triangle, LFSR noise, arpeggio chords). Variation 44: the Tune as a cue whose 14 beats land on a 9.0 s hit (98.8 bpm, a 14-5 click), as a leitmotif in three moods, and as an adaptive loop. Frontier: generative and adaptive scoring; the cognition of film music (open: transition rules and players). Reading: Karlin & Wright, On the Track; Lehman, Hollywood Harmony; Collins, Game Sound.

Build the film

python -m videos.music.music44.compute        # the part's numbers, into .cache/music44
python tools/build.py music44                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py music44 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/music/music44. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.music.music44.compute                          # numbers and sounds (under a minute)
EXPLAINER_TTS=silent python tools/build.py music44 -q l --fps 15   # a silent-narration preview, with the sounds
python tools/qa_sound.py music44 --sync                         # the sound gates
python tools/dead_air.py renders/music44_480p.mp4 --sound music44  # no empty screen; no sound over a still one
python tools/lecture_length.py music44                          # 30 to 60 minutes, listening included
python tools/build.py music44                                   # 1080p30, narrated
python -m pytest -q tests/music                                 # Monochord against its references; this part's claims and clips
python -m videos.music.labs 44                                  # the lab (writes a figure and a short WAV)