3.1.3 Audio Module¶
In this project, let’s make a DIY stereo with an audio power amplifier module, 8ohm/2w speakers and a 3.5mm Audio cable.
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.
Step 3: Run.
After the code runs, you can enjoy the music.
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.
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 mixer.init() def main(): mixer.music.load('/home/pi/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()
from pygame import mixer mixer.init()
mixer method in the
pygame library and initialize the method.
mixer.music.load('/home/pi/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
/home/pi/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.
You can also upload other music files to your Raspberry Pi. For a detailed tutorial, please refer to: Filezilla Software.
mixer.music.stop() will stop playing audio.
In addition, you can also pause with
mixer.music.pause() and continue with