LoginLogin

Convert Hz. to MML note

Root / Submissions / [.]

12Me21Created:
DEF FREQ$(HZ%)
 VAR NOTE#=LOG(HZ%/440,POW(2,1/12))+57
 VAR NOTE%=FLOOR(NOTE#)
 VAR DETUNE%=(NOTE#-NOTE%)*64
 RETURN FORMAT$("@D%DN%D",DETUNE%,NOTE%)
END
Example use:
INPUT HZ
BGMPLAY "@255"+FREQ$(HZ)

Ah, that's neat. You can also generate pure tones via sine waves.
DEF PURE HZ%
  DIM BUFF%[32730]
  VAR I%
  'Generate sine wave
  FOR I%=0 TO LEN(BUFF%)-1
    VAR B#=(I%*2*PI())/32730
    BUFF%[I%]=SIN(HZ%*B#)*POW(2,15)
  NEXT

  'Play it
  PCMSTREAM BUFF%

  'Wait for it to finish playing
  VAR PPOS%=0
  VAR POS%=0
  WHILE POS%>=PPOS%
    PPOS%=POS%
    POS%=PCMPOS
  WEND
  PCMSTOP
END
I'm sure you have a more efficient way of doing this, tho. e.g. PURE 850 Edit: tried doing it with WAVSETA so you don't need DLC.
DEF PURE HZ%
  DIM BUFF%[8180]
  VAR I%
    FOR I%=0 TO LEN(BUFF%)-1
      VAR B#=(I%*2*PI())/8180
      BUFF%[I%]=(SIN(HZ%*B#)*POW(2,7))+128
    NEXT
    WAVSETA 250,127,0,127,127,BUFF%,78,0,8179
    BEEP 250
END

Replying to:amihart
Ah, that's neat. You can also generate pure tones via sine waves.
DEF PURE HZ%
  DIM BUFF%[32730]
  VAR I%
  'Generate sine wave
  FOR I%=0 TO LEN(BUFF%)-1
    VAR B#=(I%*2*PI())/32730
    BUFF%[I%]=SIN(HZ%*B#)*POW(2,15)
  NEXT

  'Play it
  PCMSTREAM BUFF%

  'Wait for it to finish playing
  VAR PPOS%=0
  VAR POS%=0
  WHILE POS%>=PPOS%
    PPOS%=POS%
    POS%=PCMPOS
  WEND
  PCMSTOP
END
I'm sure you have a more efficient way of doing this, tho. e.g. PURE 850 Edit: tried doing it with WAVSETA so you don't need DLC.
DEF PURE HZ%
  DIM BUFF%[8180]
  VAR I%
    FOR I%=0 TO LEN(BUFF%)-1
      VAR B#=(I%*2*PI())/8180
      BUFF%[I%]=(SIN(HZ%*B#)*POW(2,7))+128
    NEXT
    WAVSETA 250,127,0,127,127,BUFF%,78,0,8179
    BEEP 250
END
IIRC, the user-set instruments all start as sine waves of some base pitch. That might be useful, or save you some work.