Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i play a sound in python 3?

I wanted to write a python script to play a sound (recorded using windows recorder)!

I read pygame can do the job and installed pygame! But I don't know how to write a code that plays a sound from a specific path! I have to play an audio file located at C:\Users\Asdf\Documents\Audio.wav

I tried a script from here http://pythonprogramming.net/adding-sounds-music-pygame/

import pygame
crash_sound = pygame.mixer.Sound("crash.wav")

But then I get an error message:

Traceback (most recent call last): File "", line 1, in crash_sound = pygame.mixer.Sound("crash.wav") AttributeError: 'module' object has no attribute 'mixer'

So how do I write the script to play that Audio.wav file using pygame?

I am using Python 3.4 64 bit version!

like image 810
whatname Avatar asked Mar 18 '26 09:03

whatname


1 Answers

I've used pydub effectively for this purpose. The module can be installed as

pip install pydub

pydub does need FFMPEG installed. Details of installation of pydub and ffmpeg given @ https://github.com/jiaaro/pydub

Once the above dependancies are installed, The library provides comprehensive manipulation of various audio formats across different platforms [ windows , Linux , Mac ] in rather easy way.

Here is an example

from pydub import AudioSegment
from pydub.playback import play

fname = "C:\\Users\\Asdf\\Documents\\Audio.wav"
mysong = AudioSegment.from_wav(fname)
play(mysong)
like image 65
Anil_M Avatar answered Mar 20 '26 00:03

Anil_M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!