0

I want to write a program in Python which plays random music. Is there any library that can directly play a sound of the given pitch or frequency, during the given time? For example, play(440, 4) should play the note A during 4 seconds.

I've found some libraries that can do what I said, but they don't play the music directly: you have to create a .wav file and, then, play this file. If I don't find any library that does what I want, I'll create a file, play it, and remove it for each note, but I think it would be more easy to do it directly.

ARD
  • 333
  • 1
  • 13
  • take a look at various libaries at: https://wiki.python.org/moin/Audio/. maybe pyaudio? http://people.csail.mit.edu/hubert/pyaudio/ – Raphael Jun 16 '19 at 14:33
  • @Raphael pyaudio can play .wav files but can not directly play the sound. – ARD Jun 16 '19 at 14:55

1 Answers1

1

I've finally found an answer to my question.

There's a module called winsound (https://docs.python.org/3/library/winsound.html) which can play a sound of a given frequency and duration: winsound.Beep(frequency, duration). But the problem is that it isn't cross-platform, only works for Windows operating systems.

So I've found another module called pyaudiere (https://pypi.org/project/pyaudiere/) which is cross-platform. It works a bit different than winsound. First you create a device: d = audiere.open_device(). Then, you can create a tone doing t = d.create_tone(440). To play the tone you do t.play() and to stop it t.stop(). If you want to play it during some seconds you can use the time module. I'm still investigating but I think it only works for Python2. This is the stackoverflow post where I found the answer: Python library for playing fixed-frequency sound.

ARD
  • 333
  • 1
  • 13