Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

python - How can I play a sine/square wave using Pygame?

I'm trying to play a sine wave using Pygame's sndarray.make_sound function. However, when I use this array to play it:

np.sin(2 * np.pi * np.arange(44100) * 440 / 44100).astype(np.float32)

where 440 is the frequency and 44100 is the sample rate, a loud, jarring noise plays instead. This works using pyaudio.PyAudio(), however I need something that doesn't block execution. This happens with square waves, too, however there it just doesn't play anything. I'm using channels=1 for the mixer.pre_init and mixer.init functions.

How can I fix this? If it helps, I'm using a Mac. Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can load the numpy array directly to a pygame.mixer.Sound object and play it:

import pygame
import numpy as np

pygame.mixer.init()

buffer = np.sin(2 * np.pi * np.arange(44100) * 440 / 44100).astype(np.float32)
sound = pygame.mixer.Sound(buffer)

sound.play(0)
pygame.time.wait(int(sound.get_length() * 1000))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...