"""Babble: a burst of beeps for a character speaking, like characters talking in an old role-playing game. There is about one beep for each syllable of the text, wandering over a pentatonic scale. The same text always gives the same tune, so a line sounds the same every time it is said. """ import math import re import zlib import numpy as np from .synth import rng_from, sampleRate # Notes of a pentatonic scale, in semitones above the lowest, for the beeps to wander between. scaleSteps = (0, 2, 4, 7, 9, 12) waves = ("round", "buzzy", "warble", "reedy") def count_syllables(text): """About how many syllables text has: groups of vowels, or one for each word if it has none the pattern knows, as in a language that does not use Latin letters.""" groups = re.findall(r"[aeiouyàáâãäåèéêëìíîïòóôõöùúûüýÿæœ]+", text.lower()) return len(groups) if groups else len(text.split()) def beep_wave(wave, frequency, seconds): """One beep: wave is "round" (soft), "buzzy", "warble" (high and quavering) or "reedy" (bright chirp).""" times = np.arange(int(sampleRate * seconds)) / sampleRate if wave == "buzzy": tone = np.tanh(4.0 * np.sin(2.0 * math.pi * frequency * times)) elif wave == "warble": wobble = 1.0 + 0.05 * np.sin(2.0 * math.pi * 11.0 * times) phases = np.cumsum(frequency * wobble) / sampleRate tone = np.sin(2.0 * math.pi * phases) + 0.25 * np.sin(4.0 * math.pi * phases) elif wave == "round": tone = np.sin(2.0 * math.pi * frequency * times) + 0.3 * np.sin(4.0 * math.pi * frequency * times) elif wave == "reedy": sine = np.sin(2.0 * math.pi * frequency * times) tone = 0.5 * np.sign(sine) + 0.5 * sine else: raise ValueError(f"Unknown babble wave {wave!r}; choose one of {', '.join(waves)}.") envelope = np.minimum(1.0, times / 0.005) * np.minimum(1.0, (seconds - times) / 0.02) return tone * envelope def babble(text, base=600.0, beepSeconds=0.075, gapSeconds=0.035, wave="round", seedKey=None, level=0.35, fewestBeeps=4, mostBeeps=12): """The burst of beeps before a character's line. base is the lowest note in cycles a second; each beep lasts beepSeconds, with gapSeconds of quiet after it. A line ending in "!" ends on the top note. seedKey, if given, chooses the tune in place of the text, so two characters can say the same line to different tunes. """ count = min(mostBeeps, max(fewestBeeps, count_syllables(text))) rng = rng_from(zlib.crc32((text if seedKey is None else seedKey).encode("utf-8"))) gap = np.zeros(int(sampleRate * gapSeconds)) parts = [] for number in range(count): step = rng.choice(scaleSteps) if number == count - 1 and text.rstrip().endswith("!"): # An exclamation ends on the top note. step = scaleSteps[-1] parts.append(beep_wave(wave, base * 2.0 ** (step / 12.0), beepSeconds)) parts.append(gap) return level * np.concatenate(parts)