compose_bgm_candidates.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. """Three distinct cheerful acoustic candidates. Does NOT replace the active BGM.
  2. Original scores rendered with the pinned CC0 VSCO CE recordings. numpy + ffmpeg.
  3. """
  4. from pathlib import Path
  5. import hashlib, json, subprocess, wave
  6. import numpy as np
  7. from acoustic_sampler import note, sample, SR
  8. ROOT=Path(__file__).resolve().parents[2]
  9. OUT=ROOT/'Art/Audio/Candidates_20261112'
  10. OUT.mkdir(exist_ok=True)
  11. ACTIVE=ROOT/'Art/Audio/NeonDaydream.wav'
  12. original_hash=hashlib.sha256(ACTIVE.read_bytes()).hexdigest()
  13. class Score:
  14. def __init__(self,code,title,bpm,meter,bars,key,instruments):
  15. self.code=code;self.title=title;self.bpm=bpm;self.beat=60/bpm;self.meter=meter;self.bars=bars
  16. self.key=key;self.instruments=instruments;self.rng=np.random.default_rng(bpm*173)
  17. self.mix=np.zeros((round(meter*bars*self.beat*SR),2))
  18. def add(self,y,beat,gain,pan=0):
  19. offset=beat*self.beat+self.rng.uniform(-.007,.007)
  20. idx=(np.arange(len(y))+round(offset*SR))%len(self.mix)
  21. gain*=self.rng.uniform(.94,1.04)
  22. np.add.at(self.mix[:,0],idx,y*gain*np.sqrt((1-pan)/2))
  23. np.add.at(self.mix[:,1],idx,y*gain*np.sqrt((1+pan)/2))
  24. def n(self,voice,pitch,beat,length,gain,pan=0):
  25. self.add(note(voice,pitch,length*self.beat+.12),beat,gain,pan)
  26. def drum(self,name,beat,gain,pan=0):
  27. self.add(sample(name+'.wav',.17),beat,gain,pan)
  28. def export(self):
  29. y=self.mix;dry=y.copy()
  30. for delay,gain in [(.047,.055),(.089,.03),(.137,.015)]:y+=np.roll(dry[:,::-1],round(delay*SR),axis=0)*gain
  31. y-=y.mean(axis=0)
  32. y*=min(.79/abs(y).max(),.105/np.sqrt(np.mean(y*y)))
  33. bridge=round(.002*SR);y[-bridge:]+=np.linspace(0,1,bridge)[:,None]*(y[0]-y[-1])
  34. pcm=np.round(y*32767).astype('<i2');path=OUT/(self.code+'.wav')
  35. with wave.open(str(path),'wb') as f:
  36. f.setnchannels(2);f.setsampwidth(2);f.setframerate(SR);f.writeframes(pcm.tobytes())
  37. subprocess.run(['ffmpeg','-v','error','-y','-i',str(path),'-t','24','-af','afade=t=out:st=23:d=1','-codec:a','libmp3lame','-q:a','2',str(OUT/(self.code+'-preview.mp3'))],check=True)
  38. return dict(file=path.name,preview=self.code+'-preview.mp3',title=self.title,bpm=self.bpm,meter=str(self.meter)+'/4',bars=self.bars,key=self.key,seconds=len(y)/SR,instruments=self.instruments,
  39. peakDbFS=float(20*np.log10(abs(y).max())),rmsDbFS=float(20*np.log10(np.sqrt(np.mean(y*y)))),clippedSamples=int((abs(pcm.astype(np.int32))>=32767).sum()),loopBoundaryDelta=float(abs(y[0]-y[-1]).max()))
  40. # A: syncopated tropical mallets and flowing harp; a light, sunny outdoor feel.
  41. a=Score('A_SunnySteps','Sunny Steps / 海岛律动',112,4,16,'D major',['marimba','harp','pizzicato bass','conga','shaker'])
  42. chords=[[50,57,62,66],[47,54,59,62],[43,50,55,59],[45,52,57,61]]*4
  43. roots=[38,35,31,33]*4
  44. melodies=[[(.25,74,.5),(1,69,.5),(1.75,66,.5),(2.5,69,.75),(3.5,71,.4)],
  45. [(.5,74,.6),(1.5,71,.6),(2.5,69,.9)],
  46. [(.25,67,.5),(1,71,.6),(2,74,.6),(2.75,76,.6)],
  47. [(.5,73,.6),(1.5,69,.5),(2.25,64,.5),(3,66,.6)]]
  48. for bar in range(16):
  49. base=bar*4
  50. for j,offset in enumerate([0,.75,1.5,2,2.75,3.5]):a.n('harp',chords[bar][[0,2,3,1,2,3][j]],base+offset,1.2,.078,-.3)
  51. for off,pitch,length in melodies[bar%4]:a.n('marimba',pitch+(2 if bar==10 and off==2 else 0),base+off,length,.24,.15)
  52. for off,pitch in [(0,roots[bar]),(2.5,roots[bar]+7)]:a.n('bass',pitch,base+off,1,.13)
  53. for off,gain in [(0,.024),(1.5,.038),(2.75,.026),(3.5,.03)]:a.drum('conga',base+off,gain,-.1)
  54. for off in [.5,1.5,2.5,3.5]:a.drum('shaker',base+off,.014,.28)
  55. # B: swung eighth-note clarinet, upright piano comping, walking acoustic bass.
  56. b=Score('B_CafeSwing','Cafe Swing / 咖啡馆摇摆',126,4,16,'F major',['upright piano','clarinet','walking pizzicato bass','wood taps'])
  57. chords=[[53,57,60,62],[50,53,57,60],[55,58,62,65],[48,52,55,58],
  58. [46,50,53,57],[55,58,62,65],[50,54,57,60],[48,52,55,58]]*2
  59. walk=[[41,45,48,50],[38,41,45,47],[43,46,50,49],[36,40,43,45],
  60. [34,38,41,42],[43,46,50,49],[38,42,45,46],[36,40,43,40]]*2
  61. phrases=[[(0,69),(2/3,72),(1.5,74),(2.67,72),(3.67,69)],
  62. [(.5,69),(1.67,65),(2.5,64),(3.67,65)],
  63. [(0,67),(2/3,70),(1.67,74),(2.67,77),(3.67,74)],
  64. [(.5,76),(1.67,72),(2.5,70),(3.67,67)],
  65. [(0,69),(2/3,74),(1.67,77),(2.67,74),(3.67,72)],
  66. [(.5,70),(1.67,74),(2.5,77),(3.67,79)],
  67. [(0,78),(2/3,74),(1.67,72),(2.67,69),(3.67,66)],
  68. [(.5,67),(1.67,64),(2.5,65),(3.67,67)]]
  69. for bar in range(16):
  70. base=bar*4
  71. for beat,pitch in enumerate(walk[bar]):b.n('bass',pitch,base+beat,.75,.14)
  72. for off in [.67,1.67,2.33,3.67]:
  73. for j,pitch in enumerate(chords[bar]):b.n('piano',pitch,base+off+j*.012,.65,.055,-.2)
  74. for off,pitch in phrases[bar%8]:b.n('clarinet',pitch,base+off,.6,.16,.23)
  75. for off in [1,3]:b.drum('wood',base+off,.023,.1)
  76. for off in [.67,2.67]:b.drum('shaker',base+off,.012,-.25)
  77. # C: quick 3/4 chamber waltz, flute answers over bouncing string pizzicato.
  78. c=Score('C_PocketWaltz','Pocket Waltz / 童话圆舞曲',138,3,24,'G major',['flute','pizzicato violin','harp','acoustic bass','wood taps'])
  79. chords=[[43,55,59,62],[38,54,57,62],[40,55,59,64],[36,55,60,64],
  80. [45,57,60,64],[38,54,57,62],[43,55,59,62],[38,54,57,62]]*3
  81. phrases=[[(0,74),(1,71),(2,67)],[(0,69),(1.5,74),(2.25,78)],
  82. [(0,76),(1,74),(2,71)],[(0,72),(1.5,76),(2.25,79)],
  83. [(0,76),(1,72),(2,69)],[(0,74),(1.5,78),(2.25,81)],
  84. [(0,79),(1,74),(2,71)],[(0,69),(1.5,66),(2.25,69)]]
  85. for bar in range(24):
  86. base=bar*3;chord=chords[bar]
  87. c.n('bass',chord[0]-12 if chord[0]>40 else chord[0],base,.85,.12)
  88. for off in [1,2]:
  89. for j,pitch in enumerate(chord[1:]):c.n('pizz',pitch,base+off+j*.01,.55,.061,(-1)**j*.22)
  90. for off,pitch in phrases[bar%8]:
  91. c.n('flute',pitch,base+off,.58,.18,.1)
  92. for j,pitch in enumerate(chord[1:]):c.n('harp',pitch+12,base+.5+j*.75,.55,.025,-.25)
  93. if bar%2==1:c.drum('wood',base+2,.014,.25)
  94. records=[score.export() for score in [a,b,c]]
  95. manifest=dict(date='2026-11-12',method='Three original acoustic arrangements rendered from pinned VSCO CE CC0 recordings',activeBgmUnchanged=hashlib.sha256(ACTIVE.read_bytes()).hexdigest()==original_hash,activeBgmSha256=original_hash,tracks=records)
  96. (OUT/'Candidates.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
  97. assert manifest['activeBgmUnchanged']
  98. print(json.dumps(manifest,ensure_ascii=False,indent=2))