compose_bgm.py 4.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. """Original deterministic 116 BPM instrumental, authored for Diamond Arrow.
  2. No samples or third-party composition. Requires numpy; exports stereo PCM WAV.
  3. All notes, room tails and delays wrap into the loop instead of a fade-to-silence.
  4. """
  5. from pathlib import Path
  6. import json, wave
  7. import numpy as np
  8. SR = 44100
  9. BPM = 116
  10. BEAT = 60 / BPM
  11. FRAMES = round(64 * BEAT * SR)
  12. mix = np.zeros((FRAMES, 2), dtype=np.float64)
  13. rng = np.random.default_rng(314159)
  14. def add(signal, beat, gain=1, pan=0):
  15. idx = (np.arange(len(signal)) + round(beat * BEAT * SR)) % FRAMES
  16. np.add.at(mix[:, 0], idx, signal * gain * np.sqrt((1-pan)/2))
  17. np.add.at(mix[:, 1], idx, signal * gain * np.sqrt((1+pan)/2))
  18. def note(midi, beats, voice):
  19. duration = beats * BEAT
  20. t = np.arange(round((duration + .28) * SR)) / SR
  21. f = 440 * 2 ** ((midi - 69) / 12)
  22. attack = 1 - np.exp(-t * 350)
  23. release = np.exp(-np.maximum(t-duration, 0) * 26)
  24. if voice == 'bass':
  25. y = np.sin(2*np.pi*f*t) + .22*np.sin(4*np.pi*f*t)
  26. return y * attack * np.exp(-t*3) * release
  27. if voice == 'bell':
  28. y = np.sin(2*np.pi*f*t + 1.1*np.exp(-t*9)*np.sin(2*np.pi*f*2*t))
  29. y += .14*np.sin(2*np.pi*f*3*t)*np.exp(-t*7)
  30. return y * attack * np.exp(-t*4.8) * release
  31. y = np.sin(2*np.pi*f*t) + .26*np.sin(2*np.pi*f*2*t) + .08*np.sin(2*np.pi*f*3*t)
  32. return y * attack * np.exp(-t*2.8) * release
  33. def drum(kind):
  34. duration = {'kick':.28,'clap':.15,'hat':.055,'open':.16}[kind]
  35. t = np.arange(round(duration*SR)) / SR
  36. noise = rng.normal(0,1,len(t)); high = np.r_[0,np.diff(noise)]*.35
  37. if kind == 'kick':
  38. phase = 2*np.pi*(48*t + 63*.018*(1-np.exp(-t/.018)))
  39. y = np.sin(phase)*np.exp(-t*16) + high*np.exp(-t*170)*.13
  40. elif kind == 'clap':
  41. y = high*np.exp(-t*34)*.7 + np.sin(2*np.pi*185*t)*np.exp(-t*36)*.16
  42. else:
  43. y = high*np.exp(-t*(80 if kind=='hat' else 30))*.5
  44. return y*np.minimum(1,t*2000)
  45. # D major, B minor, G major, A major; second phrase adds a gentle lift.
  46. chords = [[62,66,69,73],[59,62,66,69],[55,59,62,66],[57,61,64,69],
  47. [55,59,62,66],[57,61,64,69],[54,57,62,66],[57,61,64,69]]*2
  48. roots = [38,35,31,33,31,33,38,33]*2
  49. melodies = [
  50. [(0,78,.5),(1,81,.5),(1.75,78,.5),(2.5,76,.5),(3.25,74,.65)],
  51. [(.5,78,.5),(1.25,76,.5),(2,74,.75),(3.25,73,.5)],
  52. [(0,71,.5),(.75,74,.5),(1.5,78,.75),(3,76,.75)],
  53. [(.25,76,.5),(1,73,.5),(2,69,1)],
  54. [(0,74,.75),(1.25,78,.5),(2,81,.5),(3,83,.65)],
  55. [(.5,81,.5),(1.25,78,.5),(2,76,.75),(3.25,73,.5)],
  56. [(0,78,.5),(1,76,.5),(2,74,1)],
  57. [(.5,73,.5),(1.25,76,.75),(2.5,73,.5),(3.25,69,.5)]]
  58. for bar in range(16):
  59. base = bar*4
  60. for b in (0,1,2,3): add(drum('kick'),base+b,.26 if b%2==0 else .20)
  61. for b in (1,3): add(drum('clap'),base+b,.12,.12)
  62. for i in range(8): add(drum('open' if i==7 and bar%4==3 else 'hat'),base+i*.5+(0.035 if i%2 else 0),.07 if i%2 else .045,(-1)**i*.35)
  63. for offset, pitch in [(0,roots[bar]),(1.5,roots[bar]),(2.5,roots[bar]+12),(3.5,roots[bar]+7)]:
  64. add(note(pitch,.4,'bass'),base+offset,.17)
  65. for offset in (.5,2.5):
  66. for j,pitch in enumerate(chords[bar]): add(note(pitch,.7,'keys'),base+offset+j*.012,.047,(j-1.5)*.22)
  67. for offset,pitch,length in melodies[bar%8]:
  68. signal=note(pitch+(12 if bar==12 and offset==3 else 0),length,'bell')
  69. pan=.12*np.sin(bar)
  70. add(signal,base+offset,.105,pan);add(signal,base+offset+.75,.019,-pan-.25)
  71. if bar>=8:
  72. for i,pitch in enumerate(chords[bar]): add(note(pitch+12,.25,'bell'),base+3+i*.25,.018,(-1)**i*.5)
  73. # A light circular room return and gentle saturation, no hard clip or silence gap.
  74. dry=mix.copy()
  75. for seconds,gain in [(.071,.09),(.113,.065),(.173,.04)]: mix += np.roll(dry[:,::-1],round(seconds*SR),axis=0)*gain
  76. mix=np.tanh(mix*1.12)
  77. mix *= min(.88/np.max(np.abs(mix)), .13/np.sqrt(np.mean(mix**2)))
  78. pcm=np.round(mix*32767).astype('<i2')
  79. root=Path(__file__).resolve().parents[2]
  80. out=root/'Art/Audio/NeonDaydream.wav'
  81. with wave.open(str(out),'wb') as wav:
  82. wav.setnchannels(2);wav.setsampwidth(2);wav.setframerate(SR);wav.writeframes(pcm.tobytes())
  83. report={'title':'Neon Daydream','bpm':BPM,'key':'D major','bars':16,'seconds':FRAMES/SR,'sampleRate':SR,'channels':2,'peakDbFS':float(20*np.log10(np.max(np.abs(mix)))),'rmsDbFS':float(20*np.log10(np.sqrt(np.mean(mix**2)))),'loopBoundaryDelta':float(np.max(np.abs(mix[0]-mix[-1]))),'clippedSamples':int(np.sum(np.abs(pcm)>=32767)),'source':'Original procedural composition; no third-party samples'}
  84. (root/'Art/Audio/NeonDaydream.json').write_text(json.dumps(report,indent=2)+'\n',encoding='utf-8')
  85. print(json.dumps(report))