Playing sound with python

Play sound in Python

Play sound on Python is easy. There are several modules that can play a sound file (.wav).
These solutions are cross platform (Windows, Mac, Linux).

The main difference is in the ease of use and supported file formats. All of them should work with Python 3. The audio file should be in the same directory as your python program, unless you specify a path.

Play sound in Python

playsound module

The playsound module is a cross platform module that can play audio files. This doesn’t have any dependencies, simply install with pip in your virtualenv and run!

from playsound import playsound
playsound(‘audio.mp3’)

Implementation is different on platforms. It uses windll.winm on Windows, AppKit.NSSound on Apple OS X and GStreamer on Linux.

I’ve tested this with Python 3.5.3. This should work with both WAV and MP3 files.

pydub

You can play sound files with the pydub module. It’s available in the pypi repository (install with pip).
This module can use PyAudio and ffmpeg underneath.

from pydub import AudioSegment
from pydub.playback import play

Читайте также:  Java плагин заблокирован chrome

song = AudioSegment.from_wav(«sound.wav»)
play(song)

snack sound kit

The module snack sound kit can play several audio files: WAV, AU, AIFF, MP3, CSL, SD, SMP, and NIST/Sphere.

You can install it with your package manager: ‘apt install python3-tksnack’. For old versions there’s ‘python-tksnack’.

This module depends on Tkinter. That means that to play sound with this module, you’d also have to import the gui module Tkinter. The module doesn’t seem to have been updated in a while.

from Tkinter import *
import tkSnack

root = Tk()
tkSnack.initializeSnack(root)

snd = tkSnack.Sound()
snd.read(‘sound.wav’)
snd.play(blocking=1)

native player

You can also play sounds natively on your system. This requires you to have some kind of audio player installed on the terminal. On Linux you can use mpg123 for that.

This simply plays the mp3 file with an external player.

# apt install mpg123

import os

file = «file.mp3»
os.system(«mpg123 « + file)

Create a Python Web Server

Источник

winsound — Sound-playing interface for Windows¶

The winsound module provides access to the basic sound-playing machinery provided by Windows platforms. It includes functions and several constants.

winsound. Beep ( frequency , duration ) ¶

Beep the PC’s speaker. The frequency parameter specifies frequency, in hertz, of the sound, and must be in the range 37 through 32,767. The duration parameter specifies the number of milliseconds the sound should last. If the system is not able to beep the speaker, RuntimeError is raised.

winsound. PlaySound ( sound , flags ) ¶

Call the underlying PlaySound() function from the Platform API. The sound parameter may be a filename, a system sound alias, audio data as a bytes-like object , or None . Its interpretation depends on the value of flags, which can be a bitwise ORed combination of the constants described below. If the sound parameter is None , any currently playing waveform sound is stopped. If the system indicates an error, RuntimeError is raised.

winsound. MessageBeep ( type = MB_OK ) ¶

Call the underlying MessageBeep() function from the Platform API. This plays a sound as specified in the registry. The type argument specifies which sound to play; possible values are -1 , MB_ICONASTERISK , MB_ICONEXCLAMATION , MB_ICONHAND , MB_ICONQUESTION , and MB_OK , all described below. The value -1 produces a “simple beep”; this is the final fallback if a sound cannot be played otherwise. If the system indicates an error, RuntimeError is raised.

The sound parameter is the name of a WAV file. Do not use with SND_ALIAS .

The sound parameter is a sound association name from the registry. If the registry contains no such name, play the system default sound unless SND_NODEFAULT is also specified. If no default sound is registered, raise RuntimeError . Do not use with SND_FILENAME .

All Win32 systems support at least the following; most systems support many more:

Corresponding Control Panel Sound name

Источник

How to Play Sound, Audio or MP3 Files in Python

How to Convert PNG to TIFF in Python?

There are numerous ways for us to play sound, audio, or MP3 files using the Python programming language. These include modules such as playsound , VLC , pygame , mpg123 , etc. We can also play it natively on macOS and Linux as we will see later on.

Most of the modules that we will be using don’t come pre-installed with Python, which means we will have to install them ourselves. Therefore, you need to have Python and PIP installed on your system, before installing these Python modules.

Luckily, playing audio in Python is straightforward and can be done with a few lines of code. In this guide, we will be going over the steps to play sound, audio, or MP3 files in Python on Windows , Linux , and macOS .

Note: In this guide, a 4-second MP3 file is used named testaudio.mp3 and it is located in the same directory as the .py file which we will be using to run the code.

Table of Contents

Playing Sound, Audio, or MP3 Files in Python on Windows

Using Playsound

Playsound is a cross-platform Python module with no dependencies and a single function.

So, to use playsound to play audio:

play, read, open or run sound, audio or MP3 files in Python on Windows using playsound with Command Prompt command

If you would like to double-check that you’ve properly installed the module, enter python in the terminal to access the python terminal and then import playsound . If playsound is installed, there should be no errors in the output.

play, read, open or run sound, audio or MP3 files in Python on Windows using playsound with Command Prompt command

You can also enter pip list in the terminal to have a look at all the installed packages and their versions.

play, read, open or run sound, audio or MP3 files in Python on Windows using playsound with Command Prompt command

import playsound playsound.playsound('testaudio.mp3')

play, read, open or run sound, audio or MP3 files in Python on Windows using playsound

  1. After running the code, your audio will begin playing and will stop automatically depending on the length of your mp3 file.

Using VLC

VLC is an open-source and cross-platform media player that can be used to play audio and video files. VLC has a python module that enables us to play mp3 files.

Hence, to use VLC to play audio:

play, read, open or run sound, audio or MP3 files in Python on Windows using vlc

Confirm the installation by entering:

play, read, open or run sound, audio or MP3 files in Python on Windows using vlc

  1. We will be using another module alongside the Python VLC module in order to delay the execution of the file. The time module enables us to determine how long we want the file to delay execution so we can hear our audio being played. Otherwise, the file will finish executing immediately without our audio being played.
  2. In your code editor, enter the following:
import vlc import time p = vlc.MediaPlayer(‘testaudio.mp3’) p.play() print("The audio will finish playing in 4 seconds") time.sleep(4) p.stop()

play, read, open or run sound, audio or MP3 files in Python on Windows using vlc

The time.sleep(4) function tells the program to delay execution for 4 seconds before we call the p.stop() function. When running the program, it should look something like this:

play, read, open or run sound, audio or MP3 files in Python on Windows using vlc

A terminal window will appear and your audio should start playing. At the same time, the result of the print function is shown to indicate that the audio is 4 seconds long. The program will finish executing right after as that is the time we specify in time.sleep(4) .

Using Pygame

Pygame is a game development module that is cross-platform and enables us to use Python for graphics and audio purposes.

To use pygame to play audio:

play, read, open or run sound, audio or MP3 files in Python on Windows using pygame

import pygame import time pygame.mixer.init() # initialize mixer module pygame.mixer.music.load('testaudio.mp3') pygame.mixer.music.play() print("Audio will play for 4 seconds") time.sleep(4)

play, read, open or run sound, audio or MP3 files in Python on Windows using pygame

The result will look like this:

play, read, open or run sound, audio or MP3 files in Python on Windows using pygame

First, the audio will start playing, and the result of the print function will be shown on the screen. Then, the program will finish executing after 4 seconds as specified by the time.sleep() function.

Playing Sound, Audio, or MP3 Files in Python on Linux

Using Playsound

play, read, open or run sound, audio or MP3 files in Python on Linux using playsound

import playsound playsound.playsound(‘testaudio.mp3’)

play, read, open or run sound, audio or MP3 files in Python on Linux using playsound

play, read, open or run sound, audio or MP3 files in Python on Linux using playsound

Using os and mpg123

os is a standard Python module that doesn’t need to be installed. It allows us to interact with our Operating System through its functions. mpg123 is an open-source mp3 player for Linux systems.

So, we can use methods from both these functions to play audio files with Python through the following steps:

play, read, open or run sound, audio or MP3 files in Python on Linux using mpg123

import os os.system(‘mpg123 ‘ + ‘testaudio.mp3’)

play, read, open or run sound, audio or MP3 files in Python on Linux using mpg123

play, read, open or run sound, audio or MP3 files in Python on Linux using mpg123

Playing Sound, Audio, or MP3 Files in Python on macOS

Using Afplay and os

To play audio on a macOS-based machine, we will be using afplay and os . Afplay is a tool that allows us to play audio from a file on macOS.

import os os.system(“afplay ” + “testaudio.mp3”)

Conclusion

Learning how to play audio, sounds, and MP3 files in Python can be quite useful in many circumstances. There are a number of reasons why someone may want to play music or audio in Python.

These include wanting to add to their programming skills, adding music to a game, adding sound effects to an app, and many more!

With that said, in this article, we looked at the steps to play sound , audio , or MP3 files in Python on Windows , Linux , and macOS machines . We hope you’ve found this guide helpful when it comes to playing audio in Python.

Feel free to share this post with your fellow coders to guide them through playing sound, audio, or MP3 files with Python on Windows, Linux, and macOS!

Источник

Оцените статью