audio — Audio Playback and Recording
This module provides audio recording and playback functionality, using P8 and P9 pins as audio decode output. Since the mPython Board does not have an integrated speaker, it cannot directly play audio sources. You can use an expansion board with an integrated speaker or connect P8 and P9 externally to an amplifier speaker.
How to connect a 3.5mm headphone to the mPython Board:
P8 – Left channel
P9 – Right channel
GND – GND
Functions
Basic Audio Functions
Playback
- audio.player_init()
Audio playback initialization, allocates buffer for audio decoding
- audio.play(url)
Local or network audio playback, currently only supports wav and mp3 audio formats.
You can play MP3 audio from the file system or MP3 audio resources from the network. Playing local MP3 audio is limited by the MicroPython file system and RAM size; when the file is larger than 1MB, it is basically difficult to download. Therefore, audio file size should be as small as possible. When playing network MP3 audio, you must first connect to the network, and the URL must be a complete address, such as “http://wiki.labplus.cn/images/4/4e/Music_test.mp3”. Returns the decode status: when 0, it indicates the audio decode command can be accepted; when 1, it indicates the system is currently decoding and cannot respond.
url(str): Audio file path, type is string. Can be a local path address or a URL address on the network.
1import audio # Import audio
2from mpython import wifi # Import wifi
3
4mywifi=wifi() # Instantiate the wifi class
5mywifi.connectWiFi('ssid','password') # Connect to the Wi-Fi network
6
7audio.player_init() # Playback initialization
8audio.play('music.mp3') # Local audio decoding
9audio.play("http://wiki.labplus.cn/images/4/4e/Music_test.mp3") # Play network audio URL
10audio.player_deinit() # Playback finished, release resources
- audio.set_volume(vol)
Set audio volume
vol: Volume setting, range 0~100
- audio.stop()
Stop audio playback
- audio.pause()
Pause audio playback
- audio.resume()
Resume audio playback, used to resume after pausing
- audio.player_status()
Used to check whether the system is in audio playback state. Returns 1 if currently playing, returns 0 if playback has ended and the system is idle.
- audio.player_deinit()
Release buffer after audio playback ends
Recording
- audio.recorder_init()
Recording initialization
- audio.record(file_name, record_time=5)
Record audio and store in wav format. Audio parameters are 8000Hz sample rate, 16-bit, mono.
file_name- wav file storage pathrecord_time- Recording duration, default 5 seconds. Recording duration is limited by file system space; maximum duration depends on actual conditions.
- audio.recorder_deinit()
Release resources after recording ends
Recording example:
import audio
from mpython import *
audio.recorder_init()
rgb[0] = (255, 0, 0) # Use LED to indicate recording start/end
rgb.write()
audio.record('test.wav',5)
rgb[0] = (0, 0, 0)
rgb.write()
audio.recorder_deinit()