Skip to content

Instantly share code, notes, and snippets.

@Munksgaard
Created December 20, 2022 19:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Munksgaard/111f7364ce34e4d31cb541df402ee518 to your computer and use it in GitHub Desktop.
Save Munksgaard/111f7364ce34e4d31cb541df402ee518 to your computer and use it in GitHub Desktop.
Music in Futhark
.PHONY: all
all:
futhark c futmusic.fut
rm -f output.wav
echo "" | ./futmusic -b | tail -c+18 | head -c-1 | ffmpeg -f s8 -i - output.wav
mpv output.wav
def volume = 1.0f32
def fs = 44100i32
def standard_pitch = 440.0f32
def duration_to_num_samples (duration: f32): i64 =
i64.f32 (f32.i32 fs * duration)
def clamp min max = f32.max min <-< f32.min max
def note (num_samples: i64) (i: f32): []f32 =
let pitch = standard_pitch * 2 ** (i/12)
in tabulate num_samples (\k -> volume * f32.sin (2 * f32.pi * f32.i64 k * pitch / f32.i32 fs))
def play [n] (samples: [n]f32): [n]i8 =
samples
|> map ((*) (f32.i8 i8.highest))
|> map (clamp (f32.i8 i8.lowest) (f32.i8 i8.highest))
|> map i8.f32
def main =
let duration = duration_to_num_samples 0.5
in note duration 3
++ note duration 5
++ note duration 7
++ note duration 3
|> play
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment