Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a sine wave using Python?

I'm trying to generate a sine wave of a given frequency for a given duration and then write it into a .wav file. I'm using numpy's sin function and scipy's wavfile function. I'm getting a weird sound that is definitely not a sine wave.

import numpy as np
from scipy.io import wavfile

fs = 44100

f = int(raw_input("Enter fundamental frequency: "))
t = float(raw_input("Enter duration of signal (in seconds): "))

samples = np.arange(t * fs)

signal = np.sin(2 * np.pi * f * samples)

signal *= 32767

signal = np.int16(signal)

wavfile.write(str(raw_input("Name your audio: ")), fs, signal)

Any help would be appreciated. Have I made some fundamentally incorrect assumption about sine waves or something?

like image 456
Badrinarayan Rammohan Avatar asked Dec 31 '17 13:12

Badrinarayan Rammohan


2 Answers

Change

samples = np.arange(t * fs)

to

samples = np.linspace(0, t, int(fs*t), endpoint=False)

(This assumes that fs*t results in an integer value.)

Or, as Paul Panzer suggests in a comment,

samples = np.arange(t * fs) / fs

Your samples was just the sequence of integers 0, 1, 2, ... fs*t. Instead, you need the actual time values (in seconds) of the samples.

like image 183
Warren Weckesser Avatar answered Sep 22 '22 15:09

Warren Weckesser


You are mixing sample value and length! Try:

samples = np.linspace(0, t, t * fs)

Another detail: you don't need the str around raw_input.

like image 39
grovina Avatar answered Sep 20 '22 15:09

grovina