Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sound generation / synthesis with python?

Is it possible to get python to generate a simple sound like a sine wave?

Is there a module available for this? If not, how would you go about creating your own?

Also, would you need some kind of host environment for python to run in in order to play sound, or can it be achieved just from making calls from the terminal?

If the answer is OS-dependent, I'm using a mac.

like image 707
Alex Coplan Avatar asked Mar 19 '12 12:03

Alex Coplan


People also ask

Can Python make sound?

The simpleaudio module is a package of Python 3 that can play audio sounds. This module is mainly designed to play wav files and NumPy arrays. You will need to install the package before using this module. This sound package directly depends on another package called libasound2-dev.

How are sounds synthesized?

The process of creating sounds using synthesizers is called synthesis. It is done so through the process of creating sound waves through electronic signals that are converter into sound waves using instruments and loudspeakers.


1 Answers

I was looking for the same thing, In the end, I wrote this code which is working fine.

import math        #import needed modules import pyaudio     #sudo apt-get install python-pyaudio  PyAudio = pyaudio.PyAudio     #initialize pyaudio  #See https://en.wikipedia.org/wiki/Bit_rate#Audio BITRATE = 16000     #number of frames per second/frameset.        FREQUENCY = 500     #Hz, waves per second, 261.63=C4-note. LENGTH = 1     #seconds to play sound  if FREQUENCY > BITRATE:     BITRATE = FREQUENCY+100  NUMBEROFFRAMES = int(BITRATE * LENGTH) RESTFRAMES = NUMBEROFFRAMES % BITRATE WAVEDATA = ''      #generating wawes for x in xrange(NUMBEROFFRAMES):  WAVEDATA = WAVEDATA+chr(int(math.sin(x/((BITRATE/FREQUENCY)/math.pi))*127+128))      for x in xrange(RESTFRAMES):   WAVEDATA = WAVEDATA+chr(128)  p = PyAudio() stream = p.open(format = p.get_format_from_width(1),                  channels = 1,                  rate = BITRATE,                  output = True)  stream.write(WAVEDATA) stream.stop_stream() stream.close() p.terminate() 
like image 166
Liam Avatar answered Sep 21 '22 20:09

Liam