Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating sine wave sound in Python

Tags:

python

audio

I need to generate a sine wave sound in Python, and I need to be able to control frequency, duration, and relative volume. By 'generate' I mean that I want it to play though the speakers immediately, not save to a file.

What is the easiest way to do this?

like image 551
astrofrog Avatar asked Nov 28 '11 16:11

astrofrog


People also ask

What is frequency of a sine wave?

The number of times the sine wave goes through a complete cycle in the space of 1 second is called the frequency. Indeed the unit used to be cycles per second, but now the unit of measurement is hertz (Hz). A frequency of 1000Hz, or 1 kHz, means that the sine wave goes through 1000 complete cycles in 1 s.


1 Answers

import pyaudio import numpy as np  p = pyaudio.PyAudio()  volume = 0.5     # range [0.0, 1.0] fs = 44100       # sampling rate, Hz, must be integer duration = 1.0   # in seconds, may be float f = 440.0        # sine frequency, Hz, may be float  # generate samples, note conversion to float32 array samples = (np.sin(2*np.pi*np.arange(fs*duration)*f/fs)).astype(np.float32)  # for paFloat32 sample values must be in range [-1.0, 1.0] stream = p.open(format=pyaudio.paFloat32,                 channels=1,                 rate=fs,                 output=True)  # play. May repeat with different volume values (if done interactively)  stream.write(volume*samples)  stream.stop_stream() stream.close()  p.terminate() 
like image 58
ivan_onys Avatar answered Sep 27 '22 20:09

ivan_onys