How to play music (wav / mp3) files on Raspberry Pi python

How to play music with python

There are five main methods as follows.

  1. pygame
  2. PyAudio
  3. vlc
  4. aplay
  5. mpg321

In this post,

I will mainly write.

Also, 3. ~ 5. are often used when you just want to play music on a Raspberry Pi, not from python. Aplay of 4. is included by default, but if you install vlc, you can play music and edit easily based on GUI, so I think it is convenient.

1.pygame

It seems that a module called pygame is installed by default in the python package of Raspberry Pi. The code below.

audio_pygame.py


#!/usr/bin/env python
#-*- cording: utf-8 -*-

import pygame.mixer
import time

#Initialize mixer module
pygame.mixer.init()
#Reading music files
pygame.mixer.music.load("file name.mp3")
#Music playback and playback count settings(-1 is loop playback)
pygame.mixer.music.play(-1)

time.sleep(60)
#End of playback
pygame.mixer.music.stop()

mixer.music is a module for playing music. You can read mp3 files and ogg files. * Added on February 12, 2017 </ font> pygame.mixer.music was wav file playback not supported </ font>!

Use the mixer.Sound module to play short sounds such as sound effects. The Sound module can play wav files, but there is a limit of 500kB or less.

For details, please refer to the following Japanese reference. Pygame.mixer in general pygame.mixer.music

2.PyAudio

First of all, how to install. Apt-get install with LXTerminal (command line).

$ sudo apt-get install python-pyaudio python3-pyaudio

Reference: PyAudio

The code is as follows.

audio_PyAudio.py


#-*- cording: utf-8 -*-

import wave
import pyaudio

#Specify the number of chunks
CHUNK = 1024
filename = "file name.wav"

#Create an instance of PyAudio
p = pyaudio.PyAudio()

#Generate Stream
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=wf.getframerate(),
                output=True)

"""
 format:Data type when reading and writing a stream
 channels:1 for monaural, 2 for stereo, no other numbers
 rate:Sample frequency
 output:Output mode
"""

#Read 1024 data at a time
data = wf.readframes(CHUNK)

#Run
while data != '':
    #Write to stream
    stream.write(data)
    #Read 1024 again
    data = wf.readframes(CHUNK)

#Finish processing when the file is finished
stream.stop_stream()
stream.close()

p.terminate()

Reference: Takeshi memorandum

I tried various things, but there was no example of playing an mp3 file with PyAudio. They are all wav files.

As you can see from the program above, music is played while constantly reading data by streaming.

Also, the sound may be played intermittently. Stack overflow also had a [report example](http://ja.stackoverflow.com/questions/23655/raspberry-pi does not sound wav files properly using pyaudio), but a fundamental solution has been made. It doesn't seem to be. * Added on February 12, 2017 </ font> We found that the cause of the choppy playback was the sample size, sample rate, and number of channels of the music file. I confirmed the playback of the following wav file. Especially if the sample size is larger than this, it cannot be played well.

  • Sample size: 16bit
  • Sample rate: 44100Hz
  • Number of channels: 2

3.vlc From the following, the command will be executed using subprocess.

* Added on February 12, 2017 </ font> By setting up multithreading with multiprocessing etc., you can perform other processing on python while playing music using suborocess. I did.

First, install vlc.

$ sudo apt-get install vlc

Then VLC media player will be added to the menu as shown below.

スクリーンショット 2016-12-02 02.12.02.png

When opened, it looks like this.

スクリーンショット 2016-12-02 02.12.22.png

Now you can play and edit music / video based on GUI. (vlc can also convert wav files to mp3 files. Reference: Notes rather than blogs)

Now, there are two ways to operate vlc on the command line.

  1. Use the cvlc command
  2. Use vlc -I rc command

This time, we will proceed with method 2.

audio_vlc.py


#-*- cording: utf-8 -*-

import subprocess

subprocess.call("vlc -I rc --play-and-stop file name.wav", shell=True)

On the command line to end playback

> stop

You need to type. Of course Ctrl + C is fine too.

vlc cannot be played with root privileges. So vlc cannot be used if you have to run sudo in relation to other libraries in the program.

The vlc command is written in Norian Diary. You can also check with the help command. There is an Official Wiki in vlc, so you can look for it there.

And vlc can play both wav and mp3. There seems to be no upper limit on the file size.

This time I introduced the execution on the command line, but it seems that there is also a library called python-vlc. There is very little python-vlc information on the net, so it seems that the only way to use it is to read the py file of examples.

Also, since subprocess is the first appearance, that story is a little. It seems that os modules such as os.system are old and not officially recommended for use. So using subprocess.call instead of os.system seems to be the now and younger way to go.

4.aplay aplay is a typical music playback command in Linux. This is also called from subprocess like vlc.

audio_aplay.py


#-*- cording: utf-8 -*-

import subprocess

subprocess.call("aplay filename.wav", shell=True)

Depending on the size of the sample size, the following ERROR will appear.

aplay: set_params:1233:Sample format not available
Available formats:
- U8
- S16_LE

I mentioned the sample size for pyAudio, but the sample size must be 16bit for aplay as well.

Unlike vlc, aplay can be played with root privileges. So if you need to process with sudo, you should use this.

Also, aplay cannot play mp3 files. wav only. When I tried playing the mp3 file, the noise continued to flow. Reference: IT Women's Raspberry Pi Introductory Struggle

5.mpg321 It seems that there is a module called mpg321 to play mp3 files. (Honestly, if you install vlc, you can do anything ...)

First install.

$ sudo apt-get install mpg321

These are also executed by subprocess as in 3. and 4.

audio_mpg321.py


#-*- cording: utf-8 -*-

import subprocess

subprocess.call("mpg321 file name.mp3", shell=True)

The details of video playback on mpg321 are described in the above IT Women's Raspberry Pi Struggle.

Bonus 1: Specifying the music output destination

As a way to specify whether to output music from HDMI or earphone jack

  1. Command line specification
  2. Operation with raspi-config

There are two types.

1. Command line operation

$ amixer cset numid=3 <1>

The <> part is 1 for earphone jack and 2 for HDMI output. If it is 0, it is automatically determined. Reference: Nos Diary Japanese translation of Raspberry Pi official document

2. Operation with raspi-config

First, open the Configuration Tool.

$ sudo raspi-config

After that, select the output destination from 7. Advanced Option → A9 Audio.

スクリーンショット 2016-12-02 03.02.20.png スクリーンショット 2016-12-02 03.02.42.png スクリーンショット 2016-12-02 03.03.17.png

Done.

Bonus 2: Sound quality

Regardless of which method you use, if you output from the earphone jack as it is, noise will occur. The solution is

  1. Use DAC
  2. Use USB speakers and headphones
  3. Somehow pull out music from the HDMI terminal

There are likely to be three. (Maybe there are others ...) Try to output music from USB using USB-earphone jack converter However, the noise has stopped.

Preparation like this is required for music output from USB.

Summary

When I tried to play music with python, I got mad because I got ERROR, so I wrote a summary article. I hope you find it useful.

Recommended Posts