Python Forum
How can one generate triangular and sawtooth waves in python?
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can one generate triangular and sawtooth waves in python?
#1
I finally found out how to use python to make .wav files. It requires the modules numpy and scipy (the latter just for the ability to write .wav files).

I was able to get a formula from a youtube video that showed how to generate a sine wav (note that I imported numpy as np):

eachSampleNumber=np.arange(duration*sps)
waveform=np.sin(2*np.pi*eachSampleNumber*freq/sps)
This uses three variables:

freq: frequency, herz, or pitch in layman's terms
duration: length of the the note is played
sps: samples per second (don't really know what that means)

Looking at the wikipedia articles on waves, I found that a square wave can be generated from a sine wave simply by finding its 'sign', which in python code looks like this:

np.sign(np.sin(2*np.pi*eachSampleNumber*freq/sps)
And I have checked the arrays these generate, the latter does in fact produce a square wave.

However, I don't understand the mathematics for triangular and sawtooth waves. They both involve an 'epsilon' symbol, whose meaning I do not know. Obviously, I'm far from an expert on mathematics. And even then, I haven't the faintest idea how to convert these formulas into, well, computer formulas.

Does anyone know how to do this?
Reply
#2
see: https://techoverflow.net/2018/12/31/easi...gineering/
Reply
#3
That is interesting, though it doesn't seem those functions are optimized for creating sound waves.

I have found the scipy apparently has functions for generating square and sawtooth waves, however, the version I downloaded (which I did through pip), doesn't appear to have those functions.
Reply
#4
Messing around with this UliEngineering thing I keep running into problems.

I can't specify the duration of a note for one. Even if I try to, it either gives me an error message or it changes the pitch along with the duration.

And I've also found that I can't seem to concatenate individual sound files into one. With the UliEngieneering modules, the IDE throws out an error message saying that the array is too big. However, in my sine and square wave programs (which only use numpy and scipy), concatenating the sound files causes the pitch to rise!

And here I thought I had finally found a way to make sound files. It would seem that I can only make sound files that play a single note... I guess that's fine, I could possibly use an array to make pygame's mixer play multiple sound files in a row.
Reply
#5
You could use the module scipy.signal

Sawtooth:
Output:
Examples -------- A 5 Hz waveform sampled at 500 Hz for 1 second: >>> from scipy import signal >>> import matplotlib.pyplot as plt >>> t = np.linspace(0, 1, 500) >>> plt.plot(t, signal.sawtooth(2 * np.pi * 5 * t))
Square:
Output:
Examples -------- A 5 Hz waveform sampled at 500 Hz for 1 second: >>> from scipy import signal >>> import matplotlib.pyplot as plt >>> t = np.linspace(0, 1, 500, endpoint=False) >>> plt.plot(t, signal.square(2 * np.pi * 5 * t)) >>> plt.ylim(-2, 2) A pulse-width modulated sine wave: >>> plt.figure() >>> sig = np.sin(2 * np.pi * t) >>> pwm = signal.square(2 * np.pi * 30 * t, duty=(sig + 1)/2) >>> plt.subplot(2, 1, 1) >>> plt.plot(t, sig) >>> plt.subplot(2, 1, 2) >>> plt.plot(t, pwm) >>> plt.ylim(-1.5, 1.5)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#6
Well, that gives me a sawtooth wave. Still doesn't give me a triangular wave though.

Also, the sawtooth function causes the pitch to drop if I increase the duration of the sound. I don't understand why that happens. Wish I knew how all these functions actually worked. I've actually been thinking that I would be better off coding in C, just so I can actually understand everything my programs do. Right now I'm working with formulas whose workings are a complete mystery to me.

Well, stack exchange proved useful for once. I tried to search for 'scipy triangle wave', and I found a post on stack exchange that reveals how to do a triangle wave with the sawtooth function. It accepts a second parameter that determines the shape of the sawtooth. 1 (the default) gives you a right-sided sawtooth, 0 gives a left-sided one, and 0.5 gives a triangle.

Of course, that still doesn't explain why increasing the length of a sound causes the pitch to drop. I've also noticed that the actual volumes of the different wave forms are different, even if the amplitude is the same. I found a video claiming that square waves sound louder than sine waves because of harmonics or something (I don't know anything about acoustics, beyond what I've learned trying to figure this out).
Reply
#7
(Sep-25-2019, 06:13 PM)xBlackHeartx Wrote: Wish I knew how all these functions actually worked. I've actually been thinking that I would be better off coding in C, just so I can actually understand everything my programs do. Right now I'm working with formulas whose workings are a complete mystery to me.
They have docs.

You probably might be better off discussing it with people that use numpy and scipy a lot (possibly doing the same thing you are doing). Which seems to be their mailing lists.

One thing i know is if you start getting into 3rd party modules and specific functions (some of which might not be popular). It is better to go to the source of where they are discussing it. Maybe even the authors and those in the close network around them that use it often and thus know it well. They would be better equipped to explain things from their own module. This forum focuses on the standard library for the most part. And only those who have experience using 3rd party libraries end up answering such questions. So once you ask a question about a 3rd party library you have already reduced your effective audience here. And its even more reduced when you ask about a specific function in that 3rd party library. Sometimes you get lucky and find someone here that knows the module well, sometimes you dont.
Recommended Tutorials:
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with Python Script to generate SVG Dot Matrix Pattern for LED Light Guide iamrickm 2 709 Aug-25-2023, 06:07 PM
Last Post: iamrickm
  Generate Python variables dynamically Pedroski55 5 2,806 Mar-04-2022, 10:13 PM
Last Post: deanhystad
  Generate RPM package from a Python + Kivy application for an "offline" installation pruvosim 2 2,168 Jun-04-2020, 12:16 PM
Last Post: pruvosim
  generate UML design from python code Phaze90 2 2,428 Apr-13-2020, 11:36 AM
Last Post: Phaze90
  Generate a report in Python qureshi 2 3,571 Aug-24-2019, 04:50 AM
Last Post: ndc85430
  I need help using Python to generate usernames and passwords with excel documents Jannejannesson 3 3,949 May-08-2019, 02:30 PM
Last Post: Jannejannesson
  How to only extract upper or lower triangular matrix into tabular form SriRajesh 3 25,473 Jan-04-2019, 01:21 AM
Last Post: scidam
  How to generate calendar with 2 formats in python luizcrf 1 2,620 Nov-01-2018, 06:46 AM
Last Post: Larz60+
  How to generate more MP3 files at the same time in Amazon Polly using Python code? makiwara 2 3,718 Jul-02-2018, 08:43 PM
Last Post: makiwara
  how to generate sha256 hash for each line of my txt file | using python version 3.6.4 rajtekken5 2 9,031 Feb-11-2018, 01:41 PM
Last Post: rajtekken5

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020