Note
Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.
Why Join?
Expert Support: Solve post-sale issues and technical challenges with help from our community and team.
Learn & Share: Exchange tips and tutorials to enhance your skills.
Exclusive Previews: Get early access to new product announcements and sneak peeks.
Special Discounts: Enjoy exclusive discounts on our newest products.
Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.
👉 Ready to explore and create with us? Click [here] and join today!
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.
It’s definitely convenient to buy a whole kit, here’s the link:
Name |
ITEMS IN THIS KIT |
LINK |
|---|---|---|
Raphael Kit |
337 |
You can also buy them separately from the links below.
COMPONENT INTRODUCTION |
PURCHASE LINK |
|---|---|
- |
Experimental Procedures
Step 1: Build the circuit.
After building the circuit according to the above diagram, then plug the audio cable into the Raspberry Pi’s 3.5mm audio jack.
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.
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().