How do i play a sound in python 3?

27,257

Solution 1

Add python to windows 7 PATH

  1. Hold Win and press Pause.
  2. Click Advanced System Settings.
  3. Click Environment Variables.
  4. In "User variables" Click "New" if there is no PATH, else select PATH variable and click "Edit"
  5. Append ;C:\python34 to the Path variable.
  6. Restart Command Prompt.

enter image description here

Installing pygame

You first want to install pygame. You can do this in a number of ways. But to install from source

  1. Download and extract pygame-1.9.1release.zip
  2. Open a terminal
  3. cd into the pygame-1.9.1release folder you just extracted
  4. Run python setup.py

Alternatively if python is associated with .py files in your windows installation (this is the default), open the extracted folder and double click setup.py

Running pygame

You need to run

pygame.init()

Before any calls to pygame modules !

Hope that solves the problem for you

Example

import pygame
pygame.init()
s = pygame.mixer.Sound("C:\\Users\\Asdf\\Documents\\Audio.wav")

# Start playback
s.play()

# Stop playback
s.stop()

Play a sound on windows (without pygame)

import winsound

fname = "C:\\Users\\Asdf\\Documents\\Audio.wav"
winsound.PlaySound(fname, winsound.SND_FILENAME)

Solution 2

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)
Share:
27,257
Admin
Author by

Admin

Updated on December 15, 2020

Comments

  • Admin
    Admin over 3 years

    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!