Created
April 3, 2026 18:50
-
-
Save uwezi/8972afbb5e3846b390a7d217030dcc77 to your computer and use it in GitHub Desktop.
[create sound] Create a tone and play it in Manim. #manim #audio #wav #sound
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import wave | |
| import struct | |
| class increaseFreq(Scene): | |
| def construct(self): | |
| fsamp = 44.1e3 | |
| f0 = 440 | |
| f1 = 880 | |
| time = 3 | |
| ts = np.linspace(start = 0, stop = time, num=int(fsamp*time)) | |
| def f(t): | |
| return f0 + (f1-f0)*t/time | |
| def signal(t): | |
| return np.sin(2*PI*f(t)*t) | |
| ys = [signal(t) for t in ts] | |
| wav_file=wave.open("myaudio.wav","w") | |
| # wav params | |
| nchannels = 1 | |
| sampwidth = 2 # 16-bit audio | |
| nframes = len(ys) | |
| comptype = "NONE" | |
| compname = "not compressed" | |
| wav_file.setparams((nchannels, sampwidth, fsamp, nframes, comptype, compname)) | |
| for sample in ys: | |
| wav_file.writeframes(struct.pack('h', int( sample * 32767.0 ))) | |
| wav_file.close() | |
| ax = Axes( | |
| x_range=[0,3,0.5], | |
| y_range=[0,1000,100], | |
| tips=False, | |
| x_length=12, | |
| y_length=6 | |
| ).add_coordinates().to_edge(LEFT,buff=0.5) | |
| ylabel = Tex(r"frequency $f$ [Hz]").rotate(90*DEGREES).next_to(ax,LEFT,buff=0.1) | |
| xlabel = Tex(r"time $t$ [s]").next_to(ax,DOWN,buff=0.1) | |
| pl = ax.plot( | |
| f | |
| ) | |
| self.add(ax,xlabel,ylabel) | |
| self.add_sound("myaudio.wav") | |
| self.play( | |
| Create(pl), | |
| rate_func=rate_functions.linear, | |
| run_time=3 | |
| ) | |
| self.wait() |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
increaseFreq.mp4