How to generate a sine wave sound in Python
In this tutorial, We are going to generate a sine wave sound at different frequencies in python. For this tutorial, We don’t have to download any extra modules for running. We will be using Pycharm to execute the code.
Firstly we need to import the packages(Builtin packages) and rename it.
from struct import pack from math import sin, pi import os
We will be creating the output file in .au extension and will open automatically when it is successfully executed.
In the main function, let us get some basic information from the user.
Output_file_name=input("Enter file name put with extension.au : ") frequency=int(input("Enter The Frequency of Sine Wave : ")) duration=int(input("Enter the duration in milliseconds : ")) Volume=int(input("Enter the volume : "))
get the output file name, frequency, duration of the output file, volume. Note that the output file name must be entered following .au. Be Careful while entering volume put it below 60. for the duration, put it in milliseconds for example 10000(10sec).
Now we will be generating the sound wave in a separate function and call it later.
def sound_generation(name, freq, dur, vol): a = open(name, 'wb') a.write(pack('>4s5L', '.snd'.encode("utf-8"), 24, 2*dur, 2, 9000, 1)) sine_factor = 2 * pi * freq/8000 for seg in range(8*dur): sine_segments = sin(seg * sine_factor) val = pack('b', int(vol * sine_segments)) a.write(val) a.close() print("file %s is written" % name)
firstly open the file and return it to the variable a. ‘wb’ mode is for writing in binary format. next line initializing the write operation. pack() used for writing in bytes to the file. ‘.snd’.encode(“utf-8”) declared that the bytes that are going to be stored in the variable a (i.e file object) should be encoded in UTF-8 snd format. assign the sampling rate as of 9000. for more details visit this site Struct.pack format
for a sine wave, each and every value corresponds to 2*pi*f/sampling_rate. that we named it as sine_factor
seg values range from 0 to 8*duration, calculate the sine values with degrees multiplication of seg*factor. Resulting sine values can be scaled with volume and written to the file.
sound_generation(Output_file_name, frequency, duration, Volume) os.startfile(Output_file_name)
finally, call the function and open the output file.
D:\Python\venv\Scripts\python.exe D:/Python/Packages/Internship/googlesearch.py Enter file name put with extension.au : sound.au Enter The Frequency of Sine Wave : 420 Enter the duration in milliseconds : 10000 Enter the volume : 50 file sound.au is written Process finished with exit code 0
See this link for the output file: