Skip to content

Instantly share code, notes, and snippets.

@PierceLBrooks
Created April 17, 2026 07:40
Show Gist options
  • Select an option

  • Save PierceLBrooks/faeb67fc52bc78a5a281c7b4ff1d80d4 to your computer and use it in GitHub Desktop.

Select an option

Save PierceLBrooks/faeb67fc52bc78a5a281c7b4ff1d80d4 to your computer and use it in GitHub Desktop.
# Author: Pierce Brooks
# python3 -d $PWD/wftwister.py $PWD/snd.wav "(math.cos(x)*2.0)-1.0" 0.5 0.25
import sys
import copy
import math
import wave
import struct
if (len(sys.argv) < 3):
sys.exit()
descriptor = wave.open(sys.argv[1], "rb")
if (sys.flags.debug):
print(str(descriptor.getnchannels()))
print(str(descriptor.getsampwidth()))
print(str(descriptor.getframerate()))
if not (descriptor.getsampwidth() == 2):
sys.exit()
if (descriptor.getnchannels() < 1):
sys.exit()
if (descriptor.getnchannels() > 2):
sys.exit()
samples = descriptor.readframes(descriptor.getnframes())
unpacker = "<{0}h".format(descriptor.getnframes()*descriptor.getnchannels())
samples = list(struct.unpack(unpacker, samples))
outputs = []
channels = []
duration = 0.0
offset = 0.0
scale = 0.1
extent = 2.0**16.0
change = 0.0
average = 0.0
total = 0
if (len(sys.argv) > 3):
offset += float(sys.argv[3])
if (len(sys.argv) > 4):
scale += float(sys.argv[4])
for i in range(descriptor.getnchannels()):
channel = samples[i::descriptor.getnchannels()]
for j in range(len(channel)):
channel[j] = (float(channel[j])/extent)*2.0
total += len(channel)
channels.append(channel)
outputs.append(copy.deepcopy(channel))
if not (duration > 0.0):
duration += float(len(channels[len(channels)-1]))/float(descriptor.getframerate())
if (sys.flags.debug):
print(str(len(channels[len(channels)-1]))+" @ "+str(i))
if (sys.flags.debug):
print(str(duration))
for i in range(len(outputs)):
for j in range(len(outputs[i])):
x = math.sin(math.pi*2.0*(float(j)/float(descriptor.getframerate())))
y = eval(sys.argv[2])
outputs[i][j] = ((outputs[i][j]-offset)*scale)+y
average += outputs[i][j]
average /= float(total)
if (sys.flags.debug):
print(str(average))
for i in range(len(outputs)):
for j in range(len(outputs[i])):
outputs[i][j] = min(1.0, max(-1.0, outputs[i][j]-average))
change += abs(channels[i][j]-outputs[i][j])
if (sys.flags.debug):
print(str((change/(float(total)*2.0))*100.0)+"%")
with wave.open(sys.argv[0]+".wav", "wb") as output:
output.setnchannels(descriptor.getnchannels())
output.setsampwidth(descriptor.getsampwidth())
output.setframerate(descriptor.getframerate())
if (len(outputs) == 1):
for sample in outputs[0]:
sample = int(sample*0.5*(extent-1.0))
output.writeframes(struct.pack("<h", sample))
else:
for samples in zip(outputs[0], outputs[1]):
for sample in samples:
sample = int(sample*0.5*(extent-1.0))
output.writeframes(struct.pack("<h", sample))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment