Play A Sound With Python - Audio - Stack Overflow

    1. Home
    2. Questions
    3. Tags
    4. Users
    5. Companies
    6. Labs
    7. Jobs
    8. Discussions
    9. Collectives
    10. Communities for your favorite technologies. Explore all Collectives

  1. Teams

    Ask questions, find answers and collaborate at work with Stack Overflow for Teams.

    Try Teams for free Explore Teams
  2. Teams
  3. Ask questions, find answers and collaborate at work with Stack Overflow for Teams. Explore Teams

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Get early access and see previews of new features.

Learn more about Labs Play a Sound with Python [duplicate] Ask Question Asked 16 years, 1 month ago Modified 8 years, 5 months ago Viewed 492k times 119 This question already has answers here: Play audio with Python (25 answers) Closed 11 years ago.

What's the easiest way to play a sound file (.wav) in Python? By easiest I mean both most platform independent and requiring the least dependencies. pygame is certainly an option, but it seems overkill for just sound.

Share Improve this question Follow asked Nov 20, 2008 at 23:40 Claudiu's user avatar ClaudiuClaudiu 229k173 gold badges503 silver badges697 bronze badges 2
  • Very similar question to stackoverflow.com/questions/260738/play-audio-with-python. – Paige Ruten Commented Nov 20, 2008 at 23:43
  • Or this: stackoverflow.com/questions/276266/… – lpfavreau Commented Nov 21, 2008 at 1:23
Add a comment |

10 Answers 10

Sorted by: Reset to default Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 122

For Windows, you can use winsound. It's built in

import winsound winsound.PlaySound('sound.wav', winsound.SND_FILENAME)

You should be able to use ossaudiodev for linux:

from wave import open as waveOpen from ossaudiodev import open as ossOpen s = waveOpen('tada.wav','rb') (nc,sw,fr,nf,comptype, compname) = s.getparams( ) dsp = ossOpen('/dev/dsp','w') try: from ossaudiodev import AFMT_S16_NE except ImportError: from sys import byteorder if byteorder == "little": AFMT_S16_NE = ossaudiodev.AFMT_S16_LE else: AFMT_S16_NE = ossaudiodev.AFMT_S16_BE dsp.setparameters(AFMT_S16_NE, nc, fr) data = s.readframes(nf) s.close() dsp.write(data) dsp.close()

(Credit for ossaudiodev: Bill Dandreta http://mail.python.org/pipermail/python-list/2004-October/288905.html)

Share Improve this answer Follow edited Jul 11, 2016 at 14:33 Basj's user avatar Basj 46k109 gold badges445 silver badges793 bronze badges answered Nov 22, 2008 at 18:43 orestis's user avatar orestisorestis 17.2k4 gold badges27 silver badges25 bronze badges 9
  • this is good - it seems easy to build a wrapper that would at least work for these two platforms – Claudiu Commented Nov 22, 2008 at 21:02
  • 3 Avoid oss, it's old. I don't think I even have it installed anymore. – Jeffrey Aylesworth Commented Jan 30, 2010 at 19:47
  • 8 OSS isn't old. It's just that the Linux people have chosen to replace it with ALSA for reasons that have more to do with politics and ego than with software development. Regardless, OSS remains the only cross-platforn UNIX sound system, and will probably remain to be in the foreseeable future. – Martin Tournoij Commented Jul 13, 2011 at 21:08
  • 4 I started with this answer, added in a variant that also works on OS X, and uploaded it as a pure python, cross platform, single function module to pypi, called playsound. pip install playsound. Enjoy! – ArtOfWarfare Commented Jan 25, 2016 at 4:42
  • 2 I got a FileNotFoundError: [Errno 2] No such file or directory: '/dev/dsp', should this answer be opening another file on /dev? – lapisdecor Commented Feb 24, 2017 at 3:41
| Show 4 more comments 31

This seems ridiculous and far fetched but you could always use Windows (or whatever OS you prefer) to manage the sound for you!

import os os.system("start C:/thepathyouwant/file")

Simple, no extensions, somewhat slow and junky, but working.

Share Improve this answer Follow edited Jan 5, 2015 at 21:15 Matthew Murdoch's user avatar Matthew Murdoch 31.4k31 gold badges98 silver badges127 bronze badges answered Jul 31, 2013 at 18:53 Fillip's user avatar FillipFillip 4074 silver badges2 bronze badges 8
  • 2 Nice. Opening a whole lot of possibility knowing python had this feature – swdev Commented Oct 26, 2013 at 15:12
  • 17 this isn't a feature of python, it is a call to a process in the OS. it isn't cross platform, and it is terribly expensive – ealfonso Commented May 19, 2014 at 1:03
  • 23 Cross platform: import sys from subprocess import call if sys.platform == 'linux2': call(["xdg-open","sound.mp3"]) elif sys.platform == 'darwin': call(["afplay","sound.mp3"]) What's expensive is wasting time on all these malfunctioning sound libraries tbh. Substituting xdg-open for mpg123 will give afplay functionality on Linux – Louis Maddox Commented Jul 9, 2014 at 12:00
  • 2 yeah, not working osx: sh: start: command not found – Julio Marins Commented Mar 22, 2016 at 2:11
  • 11 This is really bad because (under windows) I could have made the default action for audio files be open in audio editor. The sound would never play and for some odd reason my audio editor would open all the time... – RedX Commented Nov 6, 2016 at 22:28
| Show 3 more comments 30

The Snack Sound Toolkit can play wav, au and mp3 files.

s = Sound() s.read('sound.wav') s.play() Share Improve this answer Follow answered Nov 21, 2008 at 1:11 csexton's user avatar csextoncsexton 24.7k15 gold badges57 silver badges57 bronze badges 4
  • Snack doesn't seem to work with some embeded system environment – Xun Yang Commented Sep 24, 2014 at 12:26
  • 4 it also isn't available on Pypi :-( – Danimal Commented Jul 30, 2015 at 12:33
  • 36 Snack seems to be dead (latest update 2005 - ten years ago). – Olli Commented Feb 13, 2016 at 10:37
  • 1 You can use 2to3.py to convert tkSnack.py to Python 3. Place tkSnack.py into the "Lib" folder in your Python directory. Then place the snacklib folder into the "tcl" folder in your Python directory. Tested on Python 3.2. – jacobtohahn Commented Dec 23, 2017 at 0:17
Add a comment | 20

Definitely use Pyglet for this. It's kind of a large package, but it is pure python with no extension modules. That will definitely be the easiest for deployment. It's also got great format and codec support.

import pyglet music = pyglet.resource.media('music.mp3') music.play() pyglet.app.run() Share Improve this answer Follow answered Nov 21, 2008 at 22:13 Peter Shinners's user avatar Peter ShinnersPeter Shinners 3,75626 silver badges24 bronze badges 4
  • 2 only one problem with this example: the media file needs to be on the (python-) path – Steen Commented Jun 2, 2009 at 10:12
  • 2 That's fine - so long as you don't mind pyglet taking over the python process. – Tom Commented Jun 20, 2014 at 0:09
  • pyglet.media.sources.riff.WAVEFormatException: Not a WAVE file – Schütze Commented Aug 9, 2018 at 1:50
  • @Steen you can specify the absolute path of the file when using music=pyglet.media.load(path) instead of music = pyglet.resource.media(path) – Sayyor Y Commented Jan 25, 2021 at 6:07
Add a comment | 10

After the play() command add a delay of say 10 secs or so, it'll work

import pygame import time pygame.init() pygame.mixer.music.load("test.wav") pygame.mixer.music.play() time.sleep(10)

This also plays .mp3 files.

Share Improve this answer Follow edited Sep 29, 2011 at 18:53 Bo Persson's user avatar Bo Persson 92.1k31 gold badges151 silver badges208 bronze badges answered Sep 29, 2011 at 5:42 ramkumar's user avatar ramkumarramkumar 1091 silver badge2 bronze badges 2
  • pygame doesn't use the correct sampling rate for the wave files I use – Octopus Commented Jul 21, 2013 at 7:23
  • 1 Does not always work, it is sometimes throwing segmentation fault and etc. I don't recommend this. – Schütze Commented Aug 9, 2018 at 1:48
Add a comment | 6

pyMedia's sound example does just that. This should be all you need.

import time, wave, pymedia.audio.sound as sound f= wave.open( 'YOUR FILE NAME', 'rb' ) sampleRate= f.getframerate() channels= f.getnchannels() format= sound.AFMT_S16_LE snd= sound.Output( sampleRate, channels, format ) s= f.readframes( 300000 ) snd.play( s ) Share Improve this answer Follow edited Nov 21, 2008 at 8:25 answered Nov 20, 2008 at 23:45 Rizwan Kassim's user avatar Rizwan KassimRizwan Kassim 8,1114 gold badges26 silver badges35 bronze badges 1
  • hehe, that works fine, but the snack example takes much less lines of code! i'm sure pymedia is more flexible – Claudiu Commented Nov 22, 2008 at 20:07
Add a comment | 3

I like pygame, and the command below should work:

pygame.init() pygame.mixer.Sound('sound.wav').play()

but it doesn't on either of my computers, and there is limited help on the subject out there. edit: I figured out why the pygame sound isn't working for me, it's not loading most sounds correctly, the 'length' attribute is ~0.0002 when I load them. maybe loading them using something other than mygame will get it morking more generally.

with pyglet I'm getting a resource not found error Using the above example, wigh both relative and full paths to the files.

using pyglet.media.load() instead of pyglet.resource.media() lets me load the files.

but sound.play() only plays the first fraction of a second of the file, unless I run pyglet.app.run() which blocks everything else...

Share Improve this answer Follow edited Mar 19, 2010 at 23:55 Tyler's user avatar Tyler 22.1k11 gold badges64 silver badges92 bronze badges answered Dec 5, 2009 at 12:52 suki's user avatar sukisuki 392 bronze badges 1
  • 1 From the manual: "The mixer module must be initialized like other pygame modules, but it has some extra conditions. The pygame.mixer.init - initialize the mixer module function takes several optional arguments to control the playback rate and sample size. Pygame will default to reasonable values, but pygame cannot perform Sound resampling, so the mixer should be initialized to match the values of your audio resources." - that might be why your resources load incorrectly... – Dominic Scheirlinck Commented Mar 13, 2012 at 8:42
Add a comment | 2

wxPython has support for playing wav files on Windows and Unix - I am not sure if this includes Macs. However it only support wav files as far as I can tell - it does not support other common formats such as mp3 or ogg.

Share Improve this answer Follow answered Dec 5, 2009 at 14:53 Dave Kirby's user avatar Dave KirbyDave Kirby 26.5k5 gold badges70 silver badges84 bronze badges Add a comment | 2

I just released a simple python wrapper around sox that will play a sound with Python. It's very easy to install as you need Python 2.6 or greater, sox (easy to get binaries for most architectures) and the wrapper ( https://github.com/standarddeviant/sound4python ). If you don't have sox, go here: http://sourceforge.net/projects/sox/files/sox/

You would play audio with it by:

from sound4python import sound import random a = [] for idx in xrange(1*16000): a.append(random.randint(-16384,16384)) sound(a)

Keep in mind, the only parts actually involved in playing audio are just these:

from sound4python import sound ... sound(a) Share Improve this answer Follow answered Mar 10, 2013 at 14:35 Dave C's user avatar Dave CDave C 1,42415 silver badges14 bronze badges Add a comment | 1

For Linux user, if low level pcm data manipulation is needed, try alsaaudio module. There is a playwav.py example inside the package too.

Share Improve this answer Follow answered Apr 2, 2013 at 15:46 GBY's user avatar GBYGBY 1,1001 gold badge10 silver badges13 bronze badges 2
  • link larsimmisch.github.io/pyalsaaudio/libalsaaudio.html#playwav-py – Seph Reed Commented May 16, 2016 at 8:08
  • Does not work with Python 3. – Schütze Commented Aug 9, 2018 at 2:00
Add a comment |

Not the answer you're looking for? Browse other questions tagged or ask your own question.

  • The Overflow Blog
  • The real 10x developer makes their whole team better
  • The ghost jobs haunting your career search
  • Featured on Meta
  • The December 2024 Community Asks Sprint has been moved to March 2025 (and...
  • Stack Overflow Jobs is expanding to more countries

Linked

157 Play audio with Python 2 How to play sound when the counter is equal to zero? -3 How to add a buzzer to my python project? 0 Cross Platform Python Sound Library for Linux, Windows, and Mac OS -2 How To Make Sound Play In Python 235 Sound alarm when code finishes 74 Automatically play sound in IPython notebook 53 Generating sine wave sound in Python 46 Python library for playing fixed-frequency sound 38 Read MP3 in Python 3 See more linked questions 13024 What does the "yield" keyword do in Python? 8020 Does Python have a ternary conditional operator? 7454 What are metaclasses in Python? 1939 Proper way to declare custom exceptions in modern Python? 7054 How do I merge two dictionaries in a single expression in Python? 2193 Why is reading lines from stdin much slower in C++ than Python? 4647 How slicing in Python works 1748 What is the best way of implementing singleton in Python

Hot Network Questions

  • Did the Israelites defecate when eating the manna?
  • Could a solar farm work at night?
  • How to report abuse of legal aid services?
  • How can I attach a second subpanel to this main?
  • What are the rules on carrying dairy produce in checked luggage when transiting airside in the EU?
  • Is there an MVP or "Hello world" for chess programming?
  • Corporate space exploration/espionage
  • Countable translations of a positive measure set cover an interval?
  • Locating the Sylow subgroup containing a subgroup
  • Can Ancient Joker choose a Suit you don’t have?
  • Is mathematics just "a part of physics", as stated by Arnold in 1997?
  • Is honey good or bad for kids?
  • Debian Bookworm always sets `COLUMNS` to be a little less than the actual terminal width
  • Collection closed under symmetric difference and translation
  • Extract signer information from portable executable (PE)
  • Balancing Magic Numbers and Readability in C++ Code
  • Is Luke 4:8 enjoining to "worship and serve" or serve only
  • Can I use bootstrapping for small sample sizes to satisfy the power analysis requirements?
  • I fire a mortar vertically upwards, with rifling. When it falls, which direction does it rotate? (Or alternatively: how will it behave?)
  • Sous vide pouches puffed up - Is this product contaminated?
  • Gack Id -1217291834 when installing the package
  • PSE Advent Calendar 2024 (Day 24): 'Twas the Meta before Christmas
  • Where did Tolstoy write that a man is like a fraction?
  • Debian doesn't recognise Desktop directory, and instead uses the entire home directory as the desktop
more hot questions lang-py

Từ khóa » Thư Viện Playsound Python