compose_sfx.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. """Diamond Arrow effects: soft recorded wood/hand percussion for frequent interactions.
  2. Other celebration cues retain their original deterministic D-major synthesis.
  3. Layered bell partials, filtered noise, pitch sweeps and short ambience. Requires numpy.
  4. """
  5. from pathlib import Path
  6. import json, wave
  7. import numpy as np
  8. from acoustic_sampler import sample
  9. SR = 44100
  10. ROOT = Path(__file__).resolve().parents[2]
  11. OUT = ROOT / 'Art/Audio/SFX'
  12. OUT.mkdir(parents=True, exist_ok=True)
  13. rng = np.random.default_rng(112026)
  14. def time(seconds):
  15. return np.arange(round(seconds * SR)) / SR
  16. def soften(y):
  17. n = min(len(y)//2, round(.008*SR))
  18. y[:n] *= np.linspace(0, 1, n)
  19. y[-n:] *= np.linspace(1, 0, n)
  20. return y
  21. def bell(midi, seconds, decay=7):
  22. t = time(seconds); f = 440 * 2**((midi-69)/12)
  23. y = np.sin(2*np.pi*f*t + .65*np.sin(2*np.pi*2*f*t)*np.exp(-t*22))
  24. y += .23*np.sin(2*np.pi*f*2.003*t)*np.exp(-t*9)
  25. y += .07*np.sin(2*np.pi*f*3.99*t)*np.exp(-t*30)
  26. return soften(y*(1-np.exp(-t*900))*np.exp(-t*decay))
  27. def sweep(start, end, seconds):
  28. t=time(seconds); f=start+(end-start)*t/seconds
  29. return soften(np.sin(2*np.pi*np.cumsum(f)/SR)*np.sin(np.pi*t/seconds)**1.6)
  30. def noise(seconds, cutoff=12):
  31. y=rng.normal(0, 1, len(time(seconds)))
  32. y=np.convolve(y, np.ones(cutoff)/cutoff, mode='same')
  33. return soften(y*np.sin(np.linspace(0, np.pi, len(y)))**2)
  34. def mix(seconds, layers):
  35. y=np.zeros(round(seconds*SR))
  36. for offset, signal, gain in layers:
  37. start=round(offset*SR); count=min(len(signal), len(y)-start)
  38. y[start:start+count] += signal[:count]*gain
  39. return y
  40. def phrase(notes, spacing, seconds, gain=.5):
  41. return mix(seconds, [(i*spacing,bell(n, .65, 6),gain) for i,n in enumerate(notes)])
  42. def wood_tap():
  43. y = sample('wood.wav', .10, -5)
  44. return y * np.exp(-np.arange(len(y))/SR*35)
  45. clips={
  46. 'Tap': wood_tap(),
  47. 'Slide': mix(.27, [(0,noise(.23,40),.5),(.025,sample('wood.wav',.10,-7),.10)]),
  48. 'Blocked': mix(.20, [(0,sample('conga.wav',.18,-3),.5),(0,sample('wood.wav',.09,-9),.12)]),
  49. 'Hammer': mix(.48, [(0,sweep(190,55,.23),.55),(0,noise(.12,3),.35),(.05,bell(81,.38,10),.20),(.10,bell(90,.32,11),.13)]),
  50. 'Hint': phrase([78,81,86],.105,.88,.42),
  51. 'Heart': mix(.80, [(0,bell(74,.65,5),.36),(.10,bell(78,.62,5),.33),(.20,bell(81,.58,5),.32)]),
  52. 'Reward': phrase([74,78,81,86],.095,1.14,.45),
  53. 'Clear': mix(1.9, [(0,phrase([74,78,81,86],.13,1.2),.8),(.55,bell(74,1.2,3),.22),(.55,bell(81,1.2,3),.20),(.55,bell(86,1.2,3),.30),(.82,bell(93,.8,6),.14)]),
  54. 'Fail': mix(1.05, [(0,bell(69,.75,6),.40),(.18,bell(66,.70,5),.35),(.38,bell(62,.65,5),.38)]),
  55. 'Countdown': mix(.14, [(0,bell(81,.14,24),.35),(0,noise(.035,8),.08)]),
  56. 'ChestOpen': mix(.85, [(0,noise(.10,8),.35),(0,sweep(170,85,.13),.35),(.12,noise(.35,22),.50),(.16,sweep(280,1150,.43),.10),(.44,bell(81,.4,8),.22)]),
  57. }
  58. report=[]
  59. preview=[]
  60. for name,y in clips.items():
  61. # Short room tail; gentler than reverberant notes that mask repeated taps.
  62. dry=y.copy()
  63. for delay,gain in ([] if name in ('Tap','Slide','Blocked') else [(.031,.09),(.057,.045)]):
  64. shift=round(delay*SR)
  65. y[shift:]+=dry[:-shift]*gain
  66. y=soften(y)
  67. y *= ({'Tap':.24,'Slide':.33,'Blocked':.4,'Countdown':.47}.get(name,.68)) / max(abs(y).max(), 1e-9)
  68. with wave.open(str(OUT/(name+'.wav')), 'wb') as f:
  69. f.setnchannels(1); f.setsampwidth(2); f.setframerate(SR)
  70. f.writeframes((y*32767).astype('<i2').tobytes())
  71. report.append(dict(name=name,seconds=len(y)/SR,peakDb=round(20*np.log10(abs(y).max()),2),rmsDb=round(20*np.log10(np.sqrt(np.mean(y*y))),2),clippedSamples=int((abs(y)>=1).sum())))
  72. preview.extend([y,np.zeros(round(.35*SR))])
  73. (OUT/'SFX.json').write_text(json.dumps(report,indent=2)+'\n',encoding='utf-8')
  74. preview_path=ROOT/'Editor/Validation/Audio~'
  75. preview_path.mkdir(parents=True,exist_ok=True)
  76. with wave.open(str(preview_path/'SFX-showcase.wav'),'wb') as f:
  77. f.setnchannels(1); f.setsampwidth(2); f.setframerate(SR)
  78. f.writeframes((np.concatenate(preview)*32767).astype('<i2').tobytes())
  79. print(json.dumps(report,indent=2))