Thursday, 19 May 2016

Raspberry Pi - Playing a Sound File with Python

A question I get asked a lot in Picademy is how to I play a sound file using Python.

Using just whats on the standard Raspbian image the easiest way, IMO, is to use Pygame.

This small code snippet below shows you how. Just put the wav file in the same place as your program.

import pygame
from time import sleep

#Initialise pygame and the mixer
pygame.init()
pygame.mixer.init()

#load the sound file
mysound = pygame.mixer.Sound("mysound.wav")

#play the sound file for 10 seconds and then stop it
mysound.play()
time.sleep(10)
mysound.stop()

You will have to use wav files, as opposed to other sounds files such as mp3, ogg, etc - use media.io to convert them.

5 comments:

  1. We have used a variety of wav files in Python. Some work and some don't. We discovered that exporting them from Audacity seems to eliminate problems. Is there a way in Python to ensure that sounds play correctly? FYI, we're using the Pygame library.

    ReplyDelete
    Replies
    1. Interesting, I have never had a problem with *.wav files. Mp3's, ogg and other formats, yes lots of problems.

      Delete
  2. Yes, there are lots of problems, but will give these codes a try so I can I play a sound file using Python as easy as 123. If you're looking for website to buy an essay online cheap, check this out.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete

Note: only a member of this blog may post a comment.