I was just messing around with python making wav files; when I came up with this (what I think is) pretty neat script. It takes each character and represents it with a tone.

import wave
import struct
from math import sin
import os

RATE = 44100
maxVol = 2 ** 15 - 1.0  # maximum amplitude

noise_output = wave.open('noise2.wav', 'w')
noise_output.setparams((2, 2, 44100, 0, 'NONE', 'not compressed'))

a = lambda i, f: sin(f * i / RATE)
f = open(os.path.basename(__file__)).read()
values = [[a, (ord(l))] for l in f]
result = []
count = 0

for i, j in values:
    count_end = count + RATE / 8
    while count < count_end:
        packed_value = struct.pack('h', maxVol * i(count, j * 20 + 1000))
        count += 1

result_str = ''.join(result)


I found the original here. The original just makes a constant tone. Runs fine with Python 3. I would love to see a decoder for this; but I don't know enough about calculating frequencies.

  • You should not use single letter variables.
  • Rather than a lambda you can create an actual function and pass its name.
  • There are still several magic numbers. What is 8, 20, etc.?
  • maxVol should also be uppercase, and should probably be named MAXIMUM_AMPLITUDE to avoid the need for the comment.
  • Rather than duplicating result.append you can use a separate function with a counter for how many times you want to repeat it.
  • Encapsulate functionality in functions or objects. Initialising noise_output (or the output as an object), the for loop and outputting/closing the stream are candidates.
  • Check whether it's possible to use with wave.open('noise2.wav', 'w') as noise_output: or similar.
  • Rather than reading the whole file into memory you can read a chunk at a time to speed up the program.
  • Some variable names are difficult to understand. values is almost meaningless (all it tells me is that it's an array-like structure), results likewise (how about something like audio_bytes?).
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.