0

I am pretty new to Python. I've been trying to make a sciript that plays random WAV files from a specific folder whenever run. if I try a single wav file it works all fine but doesn't work with random/file. I have tried pygame and some other modules for audio but I ran issues with every single one. For example pygame refuses to open a WAV or MP3 file. When I print it I can see that it does choose random files but windows does a "bring" sound and doesn't play the audio. Really basic probably but I somehow cannot fix this. Thanks for the help.

import winsound
import random
import os
winsound.PlaySound(random.choice(os.listdir("D:/randomsoundfolder/dem/")), winsound.SND_ASYNC)

Jeager
  • 1

2 Answers2

0

Sorry for duplicate post before. You can check out pya, example in : https://stackoverflow.com/a/60902249/4930109

As playing wav requires PyAudio(wrapper for portaudio), For windows users, you can install the wheels from : https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyaudio

However, I find the easiest way is to just use Anaconda to install PyAudio as it will install non python library:

conda install pyaudio 

I would recommend you to use Anaconda for handling your Python environment as it will give your a much more clean way to organise each project as they might need different Python versions, different dependencies and so on. There are many benefits of Anaconda.

Then

pip install pya

Then you can follow the first link to play the wav file. If you want to play mp3 then you will need ffmpeg as well, please out pya (https://github.com/interactive-sonification/pya) for instruction on installing ffmpeg for your OS.

Hope this helps.

J_yang
  • 2,672
  • 8
  • 32
  • 61
0
import winsound
import random
import os
import glob

#Create a placeholder for the soundfile that will be selected
soundfile = ''
 
# Path to the sound file directory, in this example we will use a random wav file from the Windows Media folder.
path = 'C:\Windows\Media'
 
# Extract the list of filenames from the path that are wav files only.
soundfiles = glob.glob(path + '\*.wav', recursive=False)
 
# Loop to print the filenames and create a list of the soundfiles
for filename in soundfiles:
    print(filename)

# Pick a random sound file from a list
soundfile = random.choice(soundfiles)

print("Play a random sound") 
winsound.PlaySound(soundfile, winsound.SND_ASYNC)
Exx
  • 23
  • 2