File: reverb.py

package info (click to toggle)
firmware-microbit-micropython 1.0.1-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid
  • size: 25,448 kB
  • sloc: ansic: 83,496; cpp: 27,664; python: 2,475; asm: 274; makefile: 245; javascript: 41; sh: 25
file content (50 lines) | stat: -rw-r--r-- 1,345 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import audio

def from_file(file, frame):
    ln = -1
    while ln:
        ln = file.readinto(frame)
        yield frame

def reverb_gen(src, buckets, reflect, fadeout):
    bucket_count = len(buckets)
    bucket = 0
    for frame in src:
        echo = buckets[bucket]
        echo *= reflect
        echo += frame
        yield echo
        buckets[bucket] = echo
        bucket += 1
        if bucket == bucket_count:
            bucket = 0
    while fadeout:
        fadeout -= 1
        echo = buckets[bucket]
        echo *= reflect
        yield echo
        buckets[bucket] = echo
        bucket += 1
        if bucket == bucket_count:
            bucket = 0

def reverb(src, delay, reflect):
    #Do all allocation up front, so we don't need to do any in the generator.
    bucket_count = delay>>2
    buckets = [ None ] * bucket_count
    for i in range(bucket_count):
        buckets[i] = audio.AudioFrame()
    vol = 1.0
    fadeout = 0
    while vol > 0.05:
        fadeout += bucket_count
        vol *= reflect
    return reverb_gen(src, buckets, reflect, fadeout)

def play_file(name, delay=80, reflect=0.5):
    #Do allocation here, as we can't do it in an interrupt.
    frame = audio.AudioFrame()
    with open(name) as file:
        gen = from_file(file, frame)
        r = reverb(gen, delay, reflect)
        audio.play(r)