1

I am interested in producing a note in Python that changes frequency based on a variable. I want this note to sound as 'smooth' as possible and I have little experience in the realm of sound synthesis.

I want to have a wave (initially sine, although it would be nice if anyone had a general solution) respond in real time to a frequency variable. I am aware that many solutions will cause some discontinuities in the sound i.e. creating a new sine tone every time the frequency changes; I would like to avoid this as much as possible, especially as I expect the frequency to change a lot.

(If it makes any difference, I plan on having a real-time frequency input i.e. from a slider and playing a sound based on this input.)

I am using a Linux device (specifically a Raspberry Pi 1 model B.)

3
  • It may help to know that the effect you are talking about is called frequency modulation. You may find this page useful. Oct 29, 2016 at 9:47
  • If you are on windows, you should look into the winsound module. Oct 29, 2016 at 9:51
  • @Trak Unfortunately I intend to do this on Linux. I'll edit the question.
    – ChiCubed
    Oct 29, 2016 at 9:55

1 Answer 1

2

The effect you are talking about is called frequency modulation. This is the basis of FM radio as well as FM synthesis. This page shows in more detail what you need to do, but to recap the basics, you need to produce output according to the following formula:

y = sin(2π⋅fc⋅t + β⋅sin(2π⋅fm⋅t))

where fc is the carrier frecuency and fm is the modulation frequency. You can use β to indicate the "amount" of modulation.

The following code will modulate a 440 Hz carrier signal with a 220 Hz modulation signal:

import numpy


fs = 44100 # sampling frequency, Hz
fc = 440  # carrier frequency, Hz
fm = 220  # modulation frequency, Hz

T = 0.5 # seconds
twopi = 2*numpy.pi

t = numpy.linspace(0, T, int(T*fs), endpoint=False) # time variable

# Produce ramp from 0 to 1
beta = numpy.linspace(0, 1, int(T*fs))


output = numpy.sin(twopi*fc*t + beta*numpy.sin(twopi*fm*t))

Outputting the sound is a whole different story. If you are using Jupyter notebook, this will do the trick to listen to the sound:

from IPython.display import Audio
Audio(output, rate=fs)
2
  • 1
    Sometimes links die, making the future readability of this solution second to none. You should insert more information from the website in your answer (for example, just from reading your answer and not looking at the link, I don't understand how to use the equation.) You can use the link as support but include all relevant information in your answer.
    – ChiCubed
    Oct 29, 2016 at 10:01
  • is there any other option without using jupyter?
    – aheigins
    Mar 24, 2019 at 21:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.