3.1.3 Audio Module

Introduction

In this project, let’s make a DIY stereo with an audio power amplifier module, 8ohm/2w speakers and a 3.5mm Audio cable.

Required Components

In this project, we need the following components.

../_images/audio2.png

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

Raphael Kit

337

Raphael Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

GPIO Extension Board

BUY

Breadboard

BUY

Audio Module and Speaker

-

Experimental Procedures

Step 1: Build the circuit.

../_images/4.1.4fritzing1.png

After building the circuit according to the above diagram, then plug the audio cable into the Raspberry Pi’s 3.5mm audio jack.

../_images/audio41.png

Step 2: Get into the folder of the code.

cd ~/raphael-kit/python/

Step 3: Run.

python3 3.1.3_AudioModule.py

After the code runs, you can enjoy the music.

Note

If your speaker have no sound, it may be because the Raspberry Pi has selected the wrong audio output (The default is HDMI), you need to Change Audio Output to Headphones.

If you feel that the volume of the speakers is too low, you can Adjust Volume.

Code

Note

You can Modify/Reset/Copy/Run/Stop the code below. But before that, you need to go to source code path like raphael-kit/python. After modifying the code, you can run it directly to see the effect.

from pygame import mixer
import os
user = os.getlogin()
user_home = os.path.expanduser(f'~{user}')

mixer.init()

def main():
    mixer.music.load(f'{user_home}/raphael-kit/music/my_music.mp3')
    mixer.music.set_volume(0.7)
    mixer.music.play()
    while True:
        pass# Don't do anything.

def destroy():
    mixer.music.stop()

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        destroy()

Code Explanation

from pygame import mixer

mixer.init()

Import the mixer method in the pygame library and initialize the method.

mixer.music.load(f'{user_home}/raphael-kit/music/my_music.mp3')
mixer.music.set_volume(0.7)
mixer.music.play()

This code reads the my_music.mp3 file in the ~/raphael-kit/music directory and sets the volume to 0.7(The range is 0~1). The Raspberry Pi will start playing audio When mixer.music.play() is called.

Note

You can also upload other music files to your Raspberry Pi. For a detailed tutorial, please refer to: Filezilla Software

mixer.music.stop()

Calling mixer.music.stop() will stop playing audio. In addition, you can also pause with mixer.music.pause() and continue with mixer.music.unpause().

Phenomenon Picture

../_images/3.1.3audio.JPG