Melodic Contour - Parsons Code — User Guide

Melodic contour analysis: extracts Parsons code (U/D/R/*) from audio by segmenting into notes/syllables, analyzing pitch, and encoding direction changes relative to a semitone threshold.

Author: Shai Cohen Affiliation: Department of Music, Bar-Ilan University, Israel Version: 1.0 (2025) License: MIT License Repo: https://github.com/ShaiCohen-ops/Praat-plugin_AudioTools
Contents:

What this does

This script implements Parsons Code extraction — a melodic contour analysis system that converts audio into Parsons code (U/D/R/*). Process: (1) Segmentation: Detect notes/syllables using silence detection. (2) Pitch analysis: Extract fundamental frequency for each segment. (3) Contour encoding: Compare consecutive pitches, encode direction as U (up), D (down), R (repeat/reference), * (first note). (4) Threshold application: Use semitone threshold to determine what constitutes meaningful change. Result: Compact symbolic representation of melodic contour suitable for music retrieval, analysis, and comparison.

Key Features:

What is Parsons code? Invented by Denys Parsons (1975) for melodic retrieval. Each note encoded relative to previous: U = up, D = down, R = repeat/reference (within threshold), * = first note. Advantages: (1) Transposition invariant: Same code regardless of key. (2) Tempo invariant: Same code regardless of speed. (3) Compact: Simple symbolic representation. (4) Robust: Works with imperfect pitch extraction. (5) Searchable: Enables melodic database queries. Use cases: Music information retrieval (query-by-humming), ethnomusicology (melodic pattern analysis), music education (ear training), computational musicology (melodic similarity), audio indexing (content-based retrieval).

Technical Implementation: (1) Silence detection: Praat's To TextGrid (silences) with adjustable threshold/durations. (2) Pitch extraction: Praat's To Pitch with floor/ceiling Hz. (3) Segment pitch summarization: Median/mean/mode calculation per segment. (4) Hz to semitone conversion: MIDI-like scale: semitones = 69 + 12×log₂(Hz/440). (5) Direction encoding: Compare consecutive semitone values, apply threshold_semitones. (6) Statistics: Count U/D/R, calculate percentages, determine melodic tendency. (7) Visualization: 6-panel plot: waveform, pitch contour, semitone piano roll, Parsons codes, legend, statistics. (8) TextGrid creation: Three-tier annotation (note numbers, Parsons codes, pitch values).

Quick start

  1. In Praat, select exactly one Sound object (mono recommended).
  2. Run script… → Melodic_Contour_Parsons_Code.praat.
  3. Choose Preset: Speech, Singing, Instrumental, Whistle/Flute, or Custom.
  4. Adjust Silence_threshold_dB (louder = fewer segments).
  5. Set Min_silence_duration_s and Min_sounding_duration_s.
  6. Set Threshold_semitones (1.0 = ±1 semitone = R, beyond = U/D).
  7. Choose Pitch_summary: Median (recommended), Mean, or Mode.
  8. Enable Show_visualization for comprehensive graphical output.
  9. Enable Create_TextGrid_output for annotated segmentation.
  10. Click OK — analysis runs, Parsons code displayed, visualization shown.
Quick tip: Start with appropriate preset: Singing for vocals, Instrumental for monophonic instruments, Speech for spoken melody. Check segmentation results in visualization — red dotted lines should align with note/syllable boundaries. Adjust threshold_semitones based on musical style: Western classical (0.5-1.0), folk/pop (1.0-2.0), speech/chant (2.0-3.0). Use median pitch (most robust against pitch extraction errors). Enable TextGrid output for further analysis in Praat. The Parsons code string appears in Info window and visualization — copy for database queries. Visualization shows color coding: Green=U, Red=D, Yellow=R, Blue=*.
Important: MONOPHONIC INPUT REQUIRED — script analyzes single melodic line, not chords/polyphony. Voiced audio needed — works with singing, speech, monophonic instruments; may fail with percussive/noisy sounds. Silence detection limitations — legato passages may be merged; adjust min_silence_duration_s. Pitch extraction errors — octave errors, voicing detection failures possible. Threshold_semitones critical — too small = many U/D, too large = many R. Segment count matters — very few segments (<5) yields short code; many segments (>50) yields long code (consider filtering). Visualization may be dense for many segments — use zoom for details. Original sound unchanged.

Parsons Code Theory

Historical Background

📜 Denys Parsons' Musical Fingerprints (1975)

Original purpose: Allow people to identify tunes by humming/whistling

Methodology: Listeners describe melody as up/down/same relative to previous note

Publication: Parsons, D. (1975). The Directory of Tunes and Musical Themes

Database: 15,000+ classical and popular themes encoded

Modern adaptation: Automated extraction from audio signals

The Parsons Code Alphabet

🎵 Four Symbol System

SymbolMeaningColorMusical Interpretation
*First note (reference)BlueStarting point, tonic reference
UUp (higher pitch)GreenAscending motion, melodic rise
DDown (lower pitch)RedDescending motion, melodic fall
RRepeat/Reference (same)YellowStable pitch, repeated note, within threshold

Note: "R" doesn't mean exactly same pitch — means within threshold_semitones

Mathematical Encoding

INPUT: Sequence of pitch values P₁, P₂, ..., Pₙ (in Hz) STEP 1: Convert to semitones (MIDI-like scale): STᵢ = 69 + 12 × log₂(Pᵢ / 440) STEP 2: Calculate interval differences: Δᵢ = STᵢ - STᵢ₋₁ (for i ≥ 2) STEP 3: Apply threshold τ (threshold_semitones): IF i = 1: code = "*" ELSE IF Δᵢ > τ: code = "U" ELSE IF Δᵢ < -τ: code = "D" ELSE (|Δᵢ| ≤ τ): code = "R" OUTPUT: String of symbols: * U D R U R D ...

Properties & Advantages

🎯 Why Parsons Code Works

Transposition invariance:

If melody transposed by k semitones: STᵢ' = STᵢ + k Δᵢ' = (STᵢ + k) - (STᵢ₋₁ + k) = STᵢ - STᵢ₋₁ = Δᵢ Thus: Parsons code unchanged by transposition

Tempo invariance:

Parsons code based on pitch relationships only Duration/timing information ignored Thus: Same code regardless of performance tempo

Robustness to errors:

  • Octave errors don't affect code (Δ mod 12 irrelevant)
  • Small pitch extraction errors absorbed by threshold τ
  • Works with approximate pitch (humming, imperfect singing)

Compact representation:

  • n notes → n symbols (simple string)
  • Efficient for storage and comparison
  • Human-readable and memorable

Limitations & Extensions

What Parsons code doesn't capture:
  • Exact intervals: Only up/down/same, not specific interval sizes
  • Rhythm: No duration/timing information
  • Harmony: Monophonic only, no chords
  • Ornamentation: Trills, grace notes may be lost
  • Large leaps vs steps: Both encoded as "U" or "D"
Extensions in this implementation:
  • Threshold τ: Configurable semitone boundary
  • Pitch summarization: Multiple methods per segment
  • Statistical analysis: U/D/R counts and percentages
  • Melodic tendency: Automatic classification
  • Visualization: Contextual display with original audio

Segmentation Process

Silence Detection Algorithm

🔇 Praat's To TextGrid (silences)

Based on intensity threshold:

PROCESS: 1. Calculate intensity contour 2. Threshold at silence_threshold_dB 3. Apply hysteresis: - Region above threshold = "sounding" - Region below threshold = "silent" 4. Filter by minimum durations: - min_silence_duration_s: ignore brief silences - min_sounding_duration_s: ignore brief sounds OUTPUT: TextGrid with alternating "silent"/"sounding" intervals

Parameters explained:

ParameterTypical RangeEffect
silence_threshold_dB-40 to -20 dBLower = more sensitive (more segments)
min_silence_duration_s0.03-0.20 sShorter = more sensitive to brief pauses
min_sounding_duration_s0.03-0.15 sShorter = detects briefer notes

Preset Segmentation Settings

SPEECH preset: silence_threshold_dB = -25 dB min_silence_duration_s = 0.15 s min_sounding_duration_s = 0.10 s Rationale: Speech has natural pauses, longer syllables SINGING preset: silence_threshold_dB = -30 dB min_silence_duration_s = 0.08 s min_sounding_duration_s = 0.08 s Rationale: Legato singing, shorter note separations INSTRUMENTAL preset: silence_threshold_dB = -35 dB min_silence_duration_s = 0.05 s min_sounding_duration_s = 0.05 s Rationale: Precise articulation, fast passages WHISTLE/FLUTE preset: silence_threshold_dB = -40 dB min_silence_duration_s = 0.03 s min_sounding_duration_s = 0.03 s Rationale: Continuous tone, minimal silences

Pitch Analysis per Segment

🎵 Extracting Representative Pitch

Praat Pitch object: Autocorrelation-based fundamental frequency estimation

PARAMETERS: pitch_floor_Hz = minimum expected pitch (75-200 Hz) pitch_ceiling_Hz = maximum expected pitch (400-2000 Hz) TIME STEP: 0.0 (Praat default, ~0.01 s for 100 Hz) VOICING THRESHOLD: 0.45 (Praat default)

Pitch summarization methods:

MethodCalculationAdvantagesDisadvantages
Median50th percentile of pitch valuesRobust to outliers, recommendedMay miss pitch inflection points
MeanAverage of pitch valuesSensitive to overall contourAffected by pitch extraction errors
ModeMost frequent pitch valueReflects stable pitch regionsMay be unstable for short segments

Hz to Semitone Conversion

STANDARD FORMULA (equal temperament): semitones = 69 + 12 × log₂(Hz / 440) WHERE: 440 Hz = A4 = MIDI note 69 log₂(x) = ln(x) / ln(2) IMPLEMENTATION: pitchST = 69 + 12 * ln(pitchHz / 440) / ln(2) PROPERTIES: - Linear in perceptual space (semitone ≈ just noticeable difference) - Allows threshold_semitones in perceptually meaningful units - Facilitates comparison with musical notation

Segment Validation

Quality checks applied:
  • Pitch defined: Segment skipped if pitchHz = undefined
  • Positive pitch: Segment skipped if pitchHz ≤ 0
  • Voiced check: Implicit via Praat's voicing decision
  • Duration check: Already enforced by min_sounding_duration_s
Error messages:
  • "No sounding segments detected!" → Adjust silence threshold/durations
  • "No pitch detected in audio!" → Check if audio contains pitched content
  • "No pitched notes detected!" → Segmentation found but pitch extraction failed

Parsons Code Generation

Direction Encoding Algorithm

🔄 From Pitch Sequence to Code String

INPUT: Sequence of valid segments with pitchST values INITIALIZATION: previousPitchST = undefined parsonsCode$ = "" FOR each segment i from 1 to n: IF previousPitchST = undefined: code = "*" # First note ELSE: Δ = pitchST[i] - previousPitchST IF Δ > threshold_semitones: code = "U" ELSIF Δ < -threshold_semitones: code = "D" ELSE: code = "R" APPEND code to parsonsCode$ previousPitchST = pitchST[i] OUTPUT: parsonsCode$ (e.g., "* U R D U U R")

Threshold Semitones Parameter

🎚️ Determining What Constitutes "Same" Pitch

Interpretation of threshold_semitones:

IF |Δ| ≤ threshold_semitones: code = "R" (repeat/reference) IF Δ > threshold_semitones: code = "U" (up) IF Δ < -threshold_semitones: code = "D" (down)

Recommended values by musical style:

StyleThreshold (semitones)Rationale
Equal-tempered instruments0.5-1.0Precise intonation, small errors
Singing (trained)0.75-1.5Vibrato, expressive intonation
Folk/pop singing1.0-2.0Less precise intonation
Speech/chant2.0-3.0Pitch as contour, not exact notes
Children's singing1.5-2.5Large intonation variability

Effect on code: Larger threshold → more "R", fewer "U"/"D"

Statistical Analysis

📊 Quantifying Melodic Contour

Basic counts:

totalSegments = n firstNotes = 1 (always) comparisons = n - 1 countU = Σ [code[i] = "U" for i=2 to n] countD = Σ [code[i] = "D" for i=2 to n] countR = Σ [code[i] = "R" for i=2 to n] percentU = countU / comparisons × 100% percentD = countD / comparisons × 100% percentR = countR / comparisons × 100%

Melodic tendency classification:

IF countU > countD + 2: tendency$ = "Generally ASCENDING" IF countD > countU + 2: tendency$ = "Generally DESCENDING" IF countR > countU AND countR > countD: tendency$ = "Relatively STATIC" ELSE: tendency$ = "BALANCED / WAVE-LIKE"

TextGrid Output Structure

📝 Three-Tier Annotation

Tier 1: Note numbers

  • Label: "Notes"
  • Content: "N1", "N2", "N3", ...
  • Purpose: Segment identification

Tier 2: Parsons codes

  • Label: "Parsons"
  • Content: "*", "U", "D", "R"
  • Purpose: Contour symbols

Tier 3: Pitch values (optional)

  • Label: "Pitch"
  • Content: "256Hz", "440Hz", ...
  • Purpose: Absolute pitch reference
  • Controlled by: Show_pitch_values parameter

File naming: [original]_parsons.TextGrid

Visualization Components

📊 Six-Panel Display

PanelContentPurpose
TitleScript name, filename, presetContext
WaveformOriginal sound with segment boundaries (red dotted)Show segmentation accuracy
Pitch ContourPitch track with colored segment markers and Parsons codesShow pitch extraction and coding
Semitone PlotPiano-roll style, semitone y-axisShow equal-tempered perspective
Parsons CodeSequence of U/D/R/* symbolsShow final Parsons code
Legend & StatisticsColor key, counts, percentages, tendencyInterpretation aids
Time AxisTimeline with tick marksTemporal reference

Color coding: Consistent across panels for intuitive interpretation

Applications

Music Information Retrieval

Query-by-humming systems: User hums melody → Parsons code → database search

Melodic similarity: Compare Parsons codes using string distance metrics

Audio indexing: Create searchable melodic index of audio collection

Musicological Analysis

Melodic contour studies: Analyze contour patterns in musical corpora

Style analysis: Compare contour statistics across genres/composers

Oral tradition studies: Track melodic variation in folk traditions

Music Education

Ear training: Visual feedback for melodic dictation exercises

Sight-singing practice: Compare performed contour with notated melody

Intonation feedback: See pitch accuracy relative to equal temperament

Computational Creativity

Melodic generation: Use Parsons code patterns as constraints for composition

Style imitation: Extract contour patterns from exemplars, generate new melodies

Algorithmic remixing: Recombine Parsons codes from different sources

Practical Examples

🎵 Analyzing a Folk Song Recording

Goal: Extract melodic contour for ethnomusicological study

Settings: Singing preset, threshold_semitones=1.5, median pitch

Output: Parsons code, contour statistics, annotated TextGrid

Analysis: Compare with notated version, identify characteristic contour patterns

🔍 Building a Query-by-Humming System

Goal: Create melodic database for retrieval

Process: Batch process music collection → extract Parsons codes → store in database

Query: User hums → extract code → string search → return matches

Enhancement: Add n-gram analysis, fuzzy matching

🎼 Music Theory Pedagogy Tool

Goal: Help students understand melodic contour

Exercise: Student sings melody → view Parsons code → compare with target

Visualization: Real-time pitch contour with Parsons coding

Learning outcomes: Understand up/down patterns, develop relative pitch

Troubleshooting & Optimization

Problem: Too many/few segments
Causes: Silence threshold too sensitive/insensitive, duration thresholds wrong
Solutions: Adjust silence_threshold_dB (±5 dB), min_silence_duration_s, min_sounding_duration_s
Problem: Parsons code has too many U/D or too many R
Causes: threshold_semitones too small/large
Solutions: Adjust threshold_semitones (0.5-3.0 typical), check pitch extraction quality
Problem: Pitch extraction failures (undefined values)
Causes: Unvoiced segments, noisy audio, pitch outside floor/ceiling range
Solutions: Adjust pitch_floor_Hz/pitch_ceiling_Hz, use cleaner recording, ensure voiced content
Problem: Octave errors in pitch extraction
Causes: Praat pitch tracking confusion, harmonic structure
Solutions: Usually doesn't affect Parsons code (interval mod 12), but may create large U/D

Advanced Techniques

For research and advanced applications:
  • N-gram analysis: Analyze patterns of U/D/R sequences (e.g., "UD" patterns)
  • Weighted thresholds: Different thresholds for small vs large intervals
  • Temporal smoothing: Apply moving average to pitch before coding
  • Multi-level coding: Create codes at different temporal resolutions
  • Comparative analysis: Compute similarity between multiple Parsons codes
  • Database integration: Store codes with metadata for retrieval systems
  • Real-time processing: Adapt for live audio input
  • Visualization enhancements: Interactive plot with segment selection

Parsons Code Examples

Famous melodies and their Parsons codes:
  • "Twinkle Twinkle Little Star": * U U R D D R U U R D D R (with τ=1.0)
  • "Happy Birthday": * R U U R D R U U R D R (approximate, depends on version)
  • Major scale ascending: * U U U U U U U (all U with τ=1.0)
  • Chromatic scale ascending: * U U U U U U U U U U U (all U with τ=0.5)
  • Arpeggio up and down: * U U D D (C-E-G-E-C with τ=2.0)

Note: Actual codes depend on threshold τ and exact performance