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.
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:
- 4 Audio Presets: Speech, Singing, Instrumental, Whistle/Flute (optimized parameters)
- Automatic Segmentation: Silence-based note/syllable detection
- Flexible Pitch Analysis: Mean, median, or mode pitch extraction per segment
- Adjustable Threshold: Semitone threshold for U/D/R determination
- Comprehensive Visualization: 6-panel display with waveforms, pitch contour, Parsons codes
- TextGrid Output: Annotated TextGrid with notes, codes, and pitch values
- Statistical Analysis: Counts and percentages of U/D/R patterns
- Melodic Tendency: Automatic classification (ascending/descending/static/balanced)
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
- In Praat, select exactly one Sound object (mono recommended).
- Run script… →
Melodic_Contour_Parsons_Code.praat. - Choose Preset: Speech, Singing, Instrumental, Whistle/Flute, or Custom.
- Adjust Silence_threshold_dB (louder = fewer segments).
- Set Min_silence_duration_s and Min_sounding_duration_s.
- Set Threshold_semitones (1.0 = ±1 semitone = R, beyond = U/D).
- Choose Pitch_summary: Median (recommended), Mean, or Mode.
- Enable Show_visualization for comprehensive graphical output.
- Enable Create_TextGrid_output for annotated segmentation.
- Click OK — analysis runs, Parsons code displayed, visualization shown.
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
| Symbol | Meaning | Color | Musical Interpretation |
|---|---|---|---|
| * | First note (reference) | Blue | Starting point, tonic reference |
| U | Up (higher pitch) | Green | Ascending motion, melodic rise |
| D | Down (lower pitch) | Red | Descending motion, melodic fall |
| R | Repeat/Reference (same) | Yellow | Stable pitch, repeated note, within threshold |
Note: "R" doesn't mean exactly same pitch — means within threshold_semitones
Mathematical Encoding
Properties & Advantages
🎯 Why Parsons Code Works
Transposition invariance:
Tempo invariance:
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
- 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"
- 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:
Parameters explained:
| Parameter | Typical Range | Effect |
|---|---|---|
| silence_threshold_dB | -40 to -20 dB | Lower = more sensitive (more segments) |
| min_silence_duration_s | 0.03-0.20 s | Shorter = more sensitive to brief pauses |
| min_sounding_duration_s | 0.03-0.15 s | Shorter = detects briefer notes |
Preset Segmentation Settings
Pitch Analysis per Segment
🎵 Extracting Representative Pitch
Praat Pitch object: Autocorrelation-based fundamental frequency estimation
Pitch summarization methods:
| Method | Calculation | Advantages | Disadvantages |
|---|---|---|---|
| Median | 50th percentile of pitch values | Robust to outliers, recommended | May miss pitch inflection points |
| Mean | Average of pitch values | Sensitive to overall contour | Affected by pitch extraction errors |
| Mode | Most frequent pitch value | Reflects stable pitch regions | May be unstable for short segments |
Hz to Semitone Conversion
Segment Validation
- 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
- "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
Threshold Semitones Parameter
🎚️ Determining What Constitutes "Same" Pitch
Interpretation of threshold_semitones:
Recommended values by musical style:
| Style | Threshold (semitones) | Rationale |
|---|---|---|
| Equal-tempered instruments | 0.5-1.0 | Precise intonation, small errors |
| Singing (trained) | 0.75-1.5 | Vibrato, expressive intonation |
| Folk/pop singing | 1.0-2.0 | Less precise intonation |
| Speech/chant | 2.0-3.0 | Pitch as contour, not exact notes |
| Children's singing | 1.5-2.5 | Large intonation variability |
Effect on code: Larger threshold → more "R", fewer "U"/"D"
Statistical Analysis
📊 Quantifying Melodic Contour
Basic counts:
Melodic tendency classification:
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
| Panel | Content | Purpose |
|---|---|---|
| Title | Script name, filename, preset | Context |
| Waveform | Original sound with segment boundaries (red dotted) | Show segmentation accuracy |
| Pitch Contour | Pitch track with colored segment markers and Parsons codes | Show pitch extraction and coding |
| Semitone Plot | Piano-roll style, semitone y-axis | Show equal-tempered perspective |
| Parsons Code | Sequence of U/D/R/* symbols | Show final Parsons code |
| Legend & Statistics | Color key, counts, percentages, tendency | Interpretation aids |
| Time Axis | Timeline with tick marks | Temporal 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
Causes: Silence threshold too sensitive/insensitive, duration thresholds wrong
Solutions: Adjust silence_threshold_dB (±5 dB), min_silence_duration_s, min_sounding_duration_s
Causes: threshold_semitones too small/large
Solutions: Adjust threshold_semitones (0.5-3.0 typical), check pitch extraction quality
Causes: Unvoiced segments, noisy audio, pitch outside floor/ceiling range
Solutions: Adjust pitch_floor_Hz/pitch_ceiling_Hz, use cleaner recording, ensure voiced content
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
- 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
- "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