# Adafruit MAX98357 I2S Class-D Mono Amp

## Overview

![](https://cdn-learn.adafruit.com/assets/assets/000/032/638/medium800/adafruit_products_3006_iso_ORIG.jpg?1464033940)

If your microcontroller or microcomputer has digital audio capability, this amp is for you! It takes standard I2S digital audio input and, not only decodes it into analog, but also amplifies it directly into a speaker. Perfect for adding compact amplified sound, it takes 2 breakouts (I2S DAC + Amp) and combines them into one.

I2S (not to be confused with I2C) is a digital sound protocol that is used on circuit boards to pass audio data around. Many high end chips and processors manage all of the audio in digital I2S format. Then, to input or output data, three or four pins are used (data in, data out, bit clock and left-right channel select). Usually, for audio devices, there's a DAC chip that will take I2S in and convert it to analog that can drive a headphone.

This small mono amplifier is surprisingly powerful - able to deliver 3.2 Watts of power into a 4 ohm impedance speaker (5V power @ 10% THD). Inside the miniature chip is a class D controller, able to run from 2.7V-5.5VDC. Since the amp is a class D, it's incredibly efficient - making it perfect for portable and battery-powered projects. It has built in thermal and over-current protection but we could barely tell it got hot.

The audio input is I2S standard, you can use 3.3V or 5V logic data. The outputs are "Bridge Tied" - that means they connect directly to the outputs, no connection to ground. The output is a ~300KHz square wave PWM that is then 'averaged out' by the speaker coil - the high frequencies are not heard. All the above means that you can't connect the output into another amplifier, it should drive the speakers directly.

![](https://cdn-learn.adafruit.com/assets/assets/000/032/639/medium800/adafruit_products_3006_quarter_ORIG.jpg?1464033946)

There's a Gain pin that can be manipulated to change the gain. By default, the amp will give you **9dB** of gain. By connecting a pullup or pull down resistor, or wiring directly, the Gain pin can be set up to give 3dB, 6dB, 9dB, 12dB or 15dB.

the ShutDown/Mode pin can be used to put the chip in shutdown or set up which I2S audio channel is piped to the speaker. By default, the amp will output (L+R)/2 stereo mix into mono out. By adding a resistor, you can change it to be just left or just right output

Works great with Raspberry Pi, Arduino Zero, and any other microcontroller or microcomputer with I2S audio outputs

&nbsp;Specs:

- Output Power: 3.2W at 4Ω, 10% THD, 1.8W at 8Ω, 10% THD, with 5V supply
- PSRR: 77 dB typ @ 1KHz
- I2S sample rates from 8kHz to 96kHz
- No MCLK required
- Click + Pop reduction
- Five pin-selectable gains: 3dB, 6dB, 9dB, 12dB, 15dB
- Excellent click-and-pop suppression
- Thermal shutdown protection

![](https://cdn-learn.adafruit.com/assets/assets/000/032/640/medium800/adafruit_products_3006_kit_ORIG.jpg?1464033995)

Comes as an assembled and tested breakout board, with a small piece of optional header and 3.5mm terminal block. Some soldering is required to attach the header and terminal block if those are desired.

# Adafruit MAX98357 I2S Class-D Mono Amp

## Pinouts

![](https://cdn-learn.adafruit.com/assets/assets/000/032/613/medium800/adafruit_products_pinouts.jpg?1464025812)

The MAX98357A is an **I2S** amplifier - it does not use analog inputs, it only has digital audio input support! Don't confuse I2S with I2C, I2S is a sound protocol whereas I2C is for small amounts of data.

# Speaker Output
![](https://cdn-learn.adafruit.com/assets/assets/000/032/615/medium800/adafruit_products_spkr.jpg?1464026436)

 **This amplifier is designed to drive moving coil loudpeakers only. Speaker impedence must be 4Ω or more.** The output signal is a 330KHz PWM square wave with a duty cycle proportional to the audio signal. The inductance of the speaker coil serves as a low-pass filter to average out the high-frequency components. Do not try to use this as a pre-amplifier.  
  
The outputs of _each channel_ are "Bridge-Tied" with no connection to ground. This means that for each channels, the + and - alternate polarity to create a single channel amplifier with twice the available power.   
  
Connect your speakers using the 3.5mm screw-terminal blocks.

- 5V into 4Ω @ 10% THD - 3W max
- 5V into 4Ω @ 1% THD - 2.5W max
- 3.3V&nbsp;into 4Ω @ 10% THD - 1.3W max
- 3.3V&nbsp;into 4Ω @ 1% THD - 1.0W max

- 5V into 8Ω @ 10% THD - 1.8W max
- 5V into 8Ω @ 1% THD - 1.4W max
- 3.3V&nbsp;into 8Ω @ 10% THD - 0.8W max
- 3.3V&nbsp;into 8Ω @ 1% THD - 0.6W max

# Power Pins
![](https://cdn-learn.adafruit.com/assets/assets/000/032/614/medium800/adafruit_products_power.jpg?1464025962)

This is the power for the amplifier and logic of the amplifier. You can provide 2.5V up to 5.5V. Note that at 5V you can end up putting up to 2.8W into your speaker, so make sure your power supply can easily handle up to 650mA and we recommend a power supply spec'd for at least 800mA to give yourself some 'room'

If you have a 3.3V logic device, you can still power the amp from 5V, and that's recommended to get the most power output!

# I2S Pins
![](https://cdn-learn.adafruit.com/assets/assets/000/032/616/medium800/adafruit_products_i2spin.jpg?1464026643)

Three pins are used to receive audio data. These can be 3.3-5V logic

- **LRC** (Left/Right Clock) - this is the pin that tells the amplifier when the data is for the left channel and when its for the right channel
- **BCLK** (Bit Clock) - This is the pin that tells the amplifier when to read data on the data pin.
- **DIN** (Data In) - This is the pin that has the actual data coming in, both left and right data are sent on this pin, the LRC pin indicates when left or right is being transmitted

Note that this amplifier does not require an **MCLK** pin, if you have an MCLK output, you can leave it disconnected!

# Other Pins
![](https://cdn-learn.adafruit.com/assets/assets/000/032/617/medium800/adafruit_products_others.jpg?1464026809)

The other settings are handled by **GAIN** and **SD**

## Gain

**GAIN** is, well, the gain setting. You can have a gain of **3dB, 6dB, 9dB, 12dB** or **15dB**.

- **15dB** if a 100K resistor is connected between **GAIN** and **GND**
- **12dB** if&nbsp; **GAIN&nbsp;** is connected directly to&nbsp; **GND**
- **9dB** if **GAIN** is not connected to anything (this is the default)
- **6dB** if **GAIN** is connected directly to **Vin**
- **3dB** &nbsp;if a 100K resistor is connected between **GAIN** and **Vin**

This way, the default gain is 9dB but you can easily change it by tweaking the connection to the **GAIN** pin. Note you may need to perform a power reset to adjust the gain.

# SD / MODE

This pin is used for shutdown mode but is _also_ used for setting which channel is output. It's a little confusing but essentially:

- If **SD** is connected to ground directly (voltage is under 0.16V) then the amp is **shut down**
- If the voltage on **SD** is between 0.16V and 0.77V then the output is (Left + Right)/2, that is the stereo average.&nbsp;
- If the voltage on **SD** is between 0.77V and 1.4V then the output is just the Right channel
- If the voltage on **SD** is higher than 1.4V then the output is the Left channel.

This is compounded by an _internal_ 100K pulldown resistor on **SD** so you need to use a pullup resistor on SD to balance out the 100K internal pulldown.

For the breakout board, there's a 1Mohm resistor from **SD** to **Vin** which, when powering from 5V will give you the 'stereo average' output. If you want left or right channel only, or if you are powering from non-5V power, you may need to experiment with different resistors to get the desired voltage on **SD**

# Adafruit MAX98357 I2S Class-D Mono Amp

## Assembly

![](https://cdn-learn.adafruit.com/assets/assets/000/032/618/medium800/adafruit_products_3006_kit_ORIG.jpg?1464029419)

## Prepare the header strip:

Cut the strip to length if necessary. It will be easier to solder if you insert it into a breadboard - **long pins down**

![adafruit_products_header.jpg](https://cdn-learn.adafruit.com/assets/assets/000/032/619/medium640/adafruit_products_header.jpg?1464029729)

## Add the breakout board:

Place the breakout board over the pins so that the short pins poke through the breakout pads

![adafruit_products_place.jpg](https://cdn-learn.adafruit.com/assets/assets/000/032/620/medium640/adafruit_products_place.jpg?1464029738)

## And Solder!

Be sure to solder all pins for reliable electrical contact.  
  
_(For tips on soldering, be sure to check out our_ [_Guide to Excellent Soldering_](http://learn.adafruit.com/adafruit-guide-excellent-soldering)_)._

![adafruit_products_solder1.jpg](https://cdn-learn.adafruit.com/assets/assets/000/032/621/medium640/adafruit_products_solder1.jpg?1464029751)

![adafruit_products_solder2.jpg](https://cdn-learn.adafruit.com/assets/assets/000/032/622/medium640/adafruit_products_solder2.jpg?1464029759)

![adafruit_products_solder3.jpg](https://cdn-learn.adafruit.com/assets/assets/000/032/623/medium640/adafruit_products_solder3.jpg?1464029763)

You're done! Check your solder joints visually and continue onto the next steps

![adafruit_products_soldered.jpg](https://cdn-learn.adafruit.com/assets/assets/000/032/625/medium640/adafruit_products_soldered.jpg?1464029790)

If you want to use a terminal block for connecting a speaker, place the 3.5mm terminal so the mouthes point out.

![adafruit_products_termplace.jpg](https://cdn-learn.adafruit.com/assets/assets/000/032/626/medium640/adafruit_products_termplace.jpg?1464029799)

Solder in both pins with plenty of solder!

![adafruit_products_term1.jpg](https://cdn-learn.adafruit.com/assets/assets/000/032/627/medium640/adafruit_products_term1.jpg?1464029825)

![adafruit_products_term2.jpg](https://cdn-learn.adafruit.com/assets/assets/000/032/628/medium640/adafruit_products_term2.jpg?1464029834)

# Adafruit MAX98357 I2S Class-D Mono Amp

## Raspberry Pi Wiring

if you have a Raspberry Pi and you want higher quality audio than the headphone jack can provide, I2S is a good option! You only use 3 pins, and since its a pure-digital output, there can be less noise and interference. Of course, you'll need to make sure that you have a nice strong 5V power supply so make sure to add 500mA or more to your power supply requirements!

This board also works very well with boards that _don't_ have audio like the Pi Zero

Info: 

![](https://cdn-learn.adafruit.com/assets/assets/000/037/880/medium800/adafruit_products_3006_top_demo_ORIG.jpg?1481134474)

Connect:

- **Amp Vin** to Raspbery Pi **5V Power**
- **Amp GND** to Raspbery Pi **Ground**
- **Amp DIN** to Raspbery Pi **GPIO 21**
- **Amp BCLK** to Raspbery Pi **GPIO 18**
- **Amp LRCLK** to Raspbery Pi **GPIO 19**

[**Check Raspberry Pi documentation for which pins are GPIO 18, 19, 21, 5V and GND**](https://www.raspberrypi.com/documentation/computers/os.html#gpio-and-the-40-pin-header)

# Adafruit MAX98357 I2S Class-D Mono Amp

## Raspberry Pi Setup

Warning: 

Danger: 

# Setup Virtual Environment

If you are installing on the Bookworm version of Raspberry Pi OS or later, you will need to install your python modules in a virtual environment. You can find more information in the&nbsp;[Python Virtual Environment Usage on Raspberry Pi](https://learn.adafruit.com/python-virtual-environment-usage-on-raspberry-pi)&nbsp;guide. To Install and activate the virtual environment, use the following commands:

```terminal
sudo apt install python3-venv
python -m venv env --system-site-packages
```

To activate the virtual environment:

```terminal
source env/bin/activate
```

# Installer script

Luckily its quite easy to install support for I2S DACs on Raspbian.

[These instructions are totally cribbed from the PhatDAC instructions at the lovely folks at Pimoroni!](http://learn.pimoroni.com/tutorial/phat/raspberry-pi-phat-dac-install)

Run the following from your Raspberry Pi with Internet connectivity:

```terminal
sudo apt install -y wget
pip3 install adafruit-python-shell
wget https://github.com/adafruit/Raspberry-Pi-Installer-Scripts/raw/main/i2samp.py
sudo -E env PATH=$PATH python3 i2samp.py
```

![](https://cdn-learn.adafruit.com/assets/assets/000/129/696/medium800/adafruit_products_quickinstall.png?1714405053)

We've added an extra helper systemd script that will play quiet audio when the I2S peripheral isn't in use. This removes popping when playback starts or stops. It uses a tiny amount of CPU time (on a Pi Zero, 5%, on a Pi 2 or 3 its negligible). You don't need this on RetroPie because it never releases the I2S device, but it's great for Raspbian.

![](https://cdn-learn.adafruit.com/assets/assets/000/066/516/medium800/adafruit_products_image.png?1543384670)

You will need to reboot once installed.

![](https://cdn-learn.adafruit.com/assets/assets/000/044/812/medium800/adafruit_products_reboot.png?1501791755)

Warning: 

After rebooting, log back in and re-run the script again...It will ask you if you want to test the speaker. Say **y** es and listen for audio to come out of your speakers...

![](https://cdn-learn.adafruit.com/assets/assets/000/044/813/medium800/adafruit_products_spkrtest.png?1501791845)

If it sounds really distorted, it could be the volume is too high. However, in order to have volume control appear in Raspbian desktop or Retropie you must reboot a second time after doing the speaker test, with **sudo reboot**

Warning: 

Once rebooted, try running **alsamixer** and use arrow keys to lower the volume, 50% is a good place to start.

If you're still having audio problems, try re-running the script and saying **N** (disable) the `/dev/zero playback service`.

You can then go to the next page on testing and optimizing your setup. Skip the rest of this page on **Detailed**  **Installation** if the script worked for you!

# Detailed Install

If, for some reason, you can't just run the script and you want to go through the install by hand - here's all the steps!

## Update /etc/modprobe.d (if it exists)

Log into your Pi and get into a serial console (either via a console cable, the TV console, RXVT, or what have you)

Edit the raspi blacklist with

```terminal
sudo nano /etc/modprobe.d/raspi-blacklist.conf
```

![](https://cdn-learn.adafruit.com/assets/assets/000/032/629/medium800/adafruit_products_blacklist.png?1464031033)

 **If the file is empty, just skip this step**

However, if you see the following lines:

`blacklist i2c-bcm2708`  
`blacklist snd-soc-pcm512x `  
`blacklist snd-soc-wm8804`

![](https://cdn-learn.adafruit.com/assets/assets/000/032/630/medium800/adafruit_products_empty.png?1464031122)

Update the lines by putting a **#** before each line

![](https://cdn-learn.adafruit.com/assets/assets/000/032/631/medium800/adafruit_products_blacklisted.png?1464031154)

Save by typing **Control-X Y \<return\>**

## Disable headphone audio (if it's set)

Edit the raspi modules list with

```terminal
sudo nano /etc/modules
```

 **If the file is empty, just skip this step**

However, if you see the following line:

`snd_bcm2835`

![](https://cdn-learn.adafruit.com/assets/assets/000/032/632/medium800/adafruit_products_sndmod.png?1464031844)

Put a **#** in front of it

![](https://cdn-learn.adafruit.com/assets/assets/000/032/633/medium800/adafruit_products_nosnd.png?1464031943)

and save with **Control-X Y \<return\>**

## Create asound.conf file

Edit the raspi modules list with

```terminal
sudo nano /etc/asound.conf
```

This file ought to be blank!

![](https://cdn-learn.adafruit.com/assets/assets/000/032/634/medium800/adafruit_products_newasound.png?1464032034)

Copy and paste the following text into the file

```
pcm.speakerbonnet {
   type hw card 0
}

pcm.dmixer {
   type dmix
   ipc_key 1024
   ipc_perm 0666
   slave {
     pcm "speakerbonnet"
     period_time 0
     period_size 1024
     buffer_size 8192
     rate 44100
     channels 2
   }
}

ctl.dmixer {
    type hw card 0
}

pcm.softvol {
    type softvol
    slave.pcm "dmixer"
    control.name "PCM"
    control.card 0
}

ctl.softvol {
    type hw card 0
}

pcm.!default {
    type             plug
    slave.pcm       "softvol"
}
```

![](https://cdn-learn.adafruit.com/assets/assets/000/045/128/medium800/adafruit_products_asound.png?1502334751)

Save the file as usual

## Add Device Tree Overlay

&nbsp;Edit your Pi configuration file with

Info: For older versions of Raspberry Pi, edit /boot/config.txt instead.

```terminal
sudo nano /boot/firmware/config.txt
```

And scroll down to the bottom. If you see a line that says: `dtparam=audio=on`

![](https://cdn-learn.adafruit.com/assets/assets/000/032/636/medium800/adafruit_products_dtover.png?1464032257)

Disable it by putting a **#** in front.

Then add:

```auto
dtoverlay=max98357a
```

on the next line. Save the file and reboot your Pi with

```terminal
sudo reboot
```

# Adafruit MAX98357 I2S Class-D Mono Amp

## Raspberry Pi Test

# Speaker Tests!

OK you can use whatever software you like to play audio but if you'd like to test the speaker output, here's some quick commands that will let you verify your amp and speaker are working as they should!

## Simple white noise speaker test

Run

```terminal
speaker-test -c2
```

to generate white noise out of the speaker, alternating left and right.

If you have a mono output amplifier, the I2S amp merges left and right channels, so you'll hear continuous white noise

## Simple WAV speaker test

Once you've got something coming out, try to play an audio file with **speaker-test** (for WAV files, not MP3)

```terminal
speaker-test -c2 --test=wav -w /usr/share/sounds/alsa/Front_Center.wav
```

You'll hear audio coming from left and right alternating speakers

## Simple MP3 speaker test

If you want to play a stream of music, you can try

```terminal
sudo apt-get install -y mpg123
mpg123 http://ice1.somafm.com/u80s-128-mp3
```

[If you want to play MP3's on command, check out this tutorial which covers how to set that up](http://learn.adafruit.com/playing-sounds-and-using-buttons-with-raspberry-pi "Link: http://learn.adafruit.com/playing-sounds-and-using-buttons-with-raspberry-pi")

At this time, Jessie Raspbery Pi kernel **does not support mono audio** out of the I2S interface, **you can only play stereo** , so any mono audio files may need conversion to stereo!

Info: 

# Volume adjustment

Many programs like PyGame and Sonic Pi have volume control within the application. For other programs you can set the volume using the command line tool called **alsamixer**. Just type alsamixer in and then use the up/down arrows to set the volume. Press Escape once its set

![](https://cdn-learn.adafruit.com/assets/assets/000/045/130/medium800/adafruit_products_alsamixer.png?1502336173)

In Raspbian PIXEL you can set the volume using the menu item control. If it has an X through it, try restarting the Pi (you have to restart twice after install to get PIXEL to recognize the volume control

![](https://cdn-learn.adafruit.com/assets/assets/000/045/131/medium800/adafruit_products_2017-08-10-033949_1280x800_scrot.png?1502336515)

# Adafruit MAX98357 I2S Class-D Mono Amp

## Pi I2S Tweaks

Warning: 

# Reducing popping

For people who followed our original installation instructions with the simple alsa config, they may find that the I2S audio pops when playing new audio.

The workaround is to use a software mixer to output a fixed sample rate to the I2S device so the bit clock does not change. I use ALSA so I configured **dmixer** and I no longer have any pops or clicks. Note that the RaspPi I2S driver does not support **dmixer** by default and you must [follow these instructions provided](https://support.hifiberry.com/hc/en-us/articles/207397665-Mixing-different-audio-sources) to add it. Continue on for step-by-step on how to enable it!

## Step 1

Start by modify **/boot/firmware/config.txt** to add`dtoverlay=i2s-mmap`

Run **sudo nano /boot/firmware/config.txt** and add the text to the bottom like so:

![](https://cdn-learn.adafruit.com/assets/assets/000/044/822/medium800/adafruit_products_i2smmap.png?1501793168)

Warning: 

Save and exit.

Then change **/etc/asound.conf** to:

```
pcm.speakerbonnet {
   type hw card 0 
}

pcm.!default { 
   type plug 
   slave.pcm "dmixer" 
}

pcm.dmixer { 
   type dmix 
   ipc_key 1024
   ipc_perm 0666
   slave { 
     pcm "speakerbonnet" 
     period_time 0
     period_size 1024
     buffer_size 8192
     rate 44100
     channels 2 
   } 
}

ctl.dmixer { 
  type hw card 0 
}
```

By running `sudo nano /etc/asound.conf`

This creates a PCM device called speakerbonnet which is connected to the hardware I2S device. Then we make a new 'dmix' device (`type dmix`) called `pcm.dmixer`. We give it a unique Inter Process Communication key (`ipc_key 1024`) and permissions that are world-read-writeable `(ipc_perm 0666`) The mixer will control the hardware pcm device speakerbonnet (pcm "speakerbonnet") and has a buffer set up so its nice and fast. The communication buffer is set up so there's no delays (`period_time 0`, `period_size 1024` and `buffer_size 8192` work well). The default mixed rate is 44.1khz stereo (`rate 44100 channels 2`)

Finally we set up a control interface but it ended up working best to just put in the hardware device here -`ctl.dmixer { type hw card 0 }`

![](https://cdn-learn.adafruit.com/assets/assets/000/044/823/medium800/adafruit_products_alsaconfig.png?1501793177)

Save and exit. Then reboot the Pi to enable the mixer. Also, while it will _greatly_ reduce popping, you still may get one once in a while - especially when first playing audio!

# Add software volume control

The basic I2S chipset used here does not have software control built in. So we have to 'trick' the Pi into creating a software volume control. [Luckily, its not hard once you know how to do it](http://alsa.opensrc.org/How_to_use_softvol_to_control_the_master_volume).

Create a new audio config file in **~/.asoundrc** with `nano ~/.asoundrc` and inside put the following text:

```
pcm.speakerbonnet {
   type hw card 0
}

pcm.dmixer {
   type dmix
   ipc_key 1024
   ipc_perm 0666
   slave {
     pcm "speakerbonnet"
     period_time 0
     period_size 1024
     buffer_size 8192
     rate 44100
     channels 2
   }
}

ctl.dmixer {
    type hw card 0
}

pcm.softvol {
    type softvol
    slave.pcm "dmixer"
    control.name "PCM"
    control.card 0
}

ctl.softvol {
    type hw card 0
}

pcm.!default {
    type             plug
    slave.pcm       "softvol"
}
```

Warning: 

![](https://cdn-learn.adafruit.com/assets/assets/000/044/883/medium800/adafruit_products_softmaster.png?1501994429)

Warning: Pi OS Desktop will trash the ~/.asoundrc configuration file everytime it starts up.

You can set the immutable bit to prevent this file from being destroyed. This is due to the&nbsp;

lxplug-volumepulse desktop widget. Pi OS Lite does not have this issue.

```auto
chattr +i ~/.asoundrc
```

Save and exit

Now, here's the trick, you have to reboot, then play some audio through alsa, then reboot to get the alsamixer to sync up right:

`speaker-test -c2 --test=wav -w /usr/share/sounds/alsa/Front_Center.wav`

_Then_ you can type **alsamixer** to control the volume with the 'classic' alsa mixing interface

![](https://cdn-learn.adafruit.com/assets/assets/000/044/880/medium800/adafruit_products_alsamixer.png?1501993968)

Just press the up and down arrows to set the volume, and ESC to quit

# Adafruit MAX98357 I2S Class-D Mono Amp

## Play Audio with PyGame

You can use **mpg123** for basic testing but it's a little clumsy for use where you want to dynamically change the volume or have an interactive program. For more powerful audio playback we suggest using PyGame to playback a variety of audio formats (MP3 included!)

# Install PyGame

Start by installing pygame support, you'll need to open up a console on your Pi with network access and run:

```auto
sudo apt-get install python3-pygame
```

Next, download this pygame example zip to your Pi

[Click to download PyGame example code &amp; sample mp3s](https://cdn-learn.adafruit.com/assets/assets/000/041/506/original/pygame_example.zip?1493840708)
On the command line, run

`wget https://cdn-learn.adafruit.com/assets/assets/000/041/506/original/pygame_example.zip`

`unzip pygame_example.zip`

# Run Demo

Inside the zip is an example called **pygameMP3.py**

This example will playback all MP3's within the script's folder. To demonstrate that you can also adjust the volume within pygame, the second argument is the volume for playback. Specify a volume to playback with a command line argument between 0.0 and 1.0

For example here is how to play at 75% volume:

```
python pygameMP3.py 0.75
```

Here's the code if you have your own mp3s!

```
''' pg_midi_sound101.py
play midi music files (also mp3 files) using pygame
tested with Python273/331 and pygame192 by vegaseat
'''
#code modified by James DeVito from here: https://www.daniweb.com/programming/software-development/code/454835/let-pygame-play-your-midi-or-mp3-files


#!/usr/bin/python

import sys
import pygame as pg
import os
import time


def play_music(music_file):
    '''
    stream music with mixer.music module in blocking manner
    this will stream the sound from disk while playing
    '''
    clock = pg.time.Clock()
    try:
        pg.mixer.music.load(music_file)
        print("Music file {} loaded!".format(music_file))
    except pygame.error:
        print("File {} not found! {}".format(music_file, pg.get_error()))
        return

    pg.mixer.music.play()
    
    # If you want to fade in the audio...
    # for x in range(0,100):
    #     pg.mixer.music.set_volume(float(x)/100.0)
    #     time.sleep(.0075)
    # # check if playback has finished
    while pg.mixer.music.get_busy():
        clock.tick(30)


freq = 44100    # audio CD quality
bitsize = -16   # unsigned 16 bit
channels = 2    # 1 is mono, 2 is stereo
buffer = 2048   # number of samples (experiment to get right sound)
pg.mixer.init(freq, bitsize, channels, buffer)


if len(sys.argv) &gt; 1:

    try: 
        user_volume = float(sys.argv[1])
    except ValueError:
        print "Volume argument invalid. Please use a float (0.0 - 1.0)"
        pg.mixer.music.fadeout(1000)
        pg.mixer.music.stop()
        raise SystemExit

    print("Playing at volume: " + str(user_volume)+ "\n")
    pg.mixer.music.set_volume(user_volume)
    mp3s = []
    for file in os.listdir("."):
        if file.endswith(".mp3"):
            mp3s.append(file)

    print mp3s

    for x in mp3s: 
        try:
            play_music(x)
            time.sleep(.25)
        except KeyboardInterrupt:
            # if user hits Ctrl/C then exit
            # (works only in console mode)
            pg.mixer.music.fadeout(1000)
            pg.mixer.music.stop()
            raise SystemExit
else:
    print("Please specify volume as a float! (0.0 - 1.0)")
```

# Adafruit MAX98357 I2S Class-D Mono Amp

## Arduino Wiring & Test

The classic ATmega328P-based Arduino's like the UNO and Metro 328 don't have I2S interfaces, so you _can't_ use this breakout with them

But the newer ATSAMD21-based boards like the Zero, Metro M0, Feather M0 can! (Note, Gemma M0 & Trinket M0 do not have I2S pins available). And so can the even newer ATSAMD51-based boards like the Metro M4 and Feather M4.

To use I2S with M0 or M4 boards, you'll need to install the [Adafruit Zero I2S library](https://github.com/adafruit/Adafruit_ZeroI2S). It is available through the Library Manager. You can search for (see below) and then just click the install button.

![](https://cdn-learn.adafruit.com/assets/assets/000/070/283/medium800/adafruit_products_Screenshot_from_2019-01-30_10-03-42.png?1548871533)

## Wiring

Wiring connections are the same as those used for CircuitPython. So go to the **CircuitPython Wiring & Test** page to see how to wire the breakout for your specific board.

## Basic Test

To test things out, try running the demo below. It comes with the library installation, so you can find it by going to:

**File -\> Examples -\>&nbsp; Adafruit Zero I2S Library -\> basic**

Be sure to change this line:

```
Adafruit_ZeroI2S i2s(0, 1, 9, 2);
```

to match the pins used for your setup. If you've wired as shown in this guide, then you can try using the default pins by changing that line to this:

```
Adafruit_ZeroI2S i2s;
```

https://github.com/adafruit/Adafruit_ZeroI2S/blob/master/examples/basic/basic.ino

## DMA Test

The basic test above created the output directly by using the `i2s.write()` function in a loop. Another approach is to use DMA to generate the output. With this approach, you do some initial setup to configure the DMA engine for playback. It can then take care of generating the output in the background allowing you to do other things in your code.

To take this approach, you will need to install the [Zero DMA library](https://github.com/adafruit/Adafruit_ZeroDMA). You can do that through the Library Manager:

![](https://cdn-learn.adafruit.com/assets/assets/000/070/284/medium800/adafruit_products_Screenshot_from_2019-01-30_10-04-17.png?1548872500)

And then you can use the DMA example found in the Zero I2S library:

**File -\> Examples -\>&nbsp; Adafruit Zero I2S Library -\> dma**

https://github.com/adafruit/Adafruit_ZeroI2S/blob/master/examples/dma/dma.ino

# Adafruit MAX98357 I2S Class-D Mono Amp

## CircuitPython Wiring & Test

CircuitPython 3.0 and higher has I2S built in which means you can use this breakout super easily with the supported M0 and M4 Express CircuitPython boards! Supported boards are Feather M0 Express, Feather M4 Express, Metro M0 Express, Metro M4 Express, and ItsyBitsy M0 Express.

Note that Trinket M0, Gemma M0 and ItsyBitsy M4 do not support I2S (the last one is not a typo!)

The M0 boards have multiple I2S pin combinations available. We're going to demonstrate a single pin combination for each board.

## Wiring

The following wiring diagrams show how to connect the MAX98357 breakout to your CircuitPython board. You'll be using voltage in, ground, bit clock, left/right clock and data pins.

- **VIN** is the **red** wire.
- **GND** is the **black** wire.
- **BCLK** is the **blue** wire.
- **LRC** is the **yellow** wire.
- **DIN** is the **green** wire.

 **For Feather M0 Express, ItsyBitsy M0 Express and Metro M0 Express:**

&nbsp;

- Connect **VIN on the breakout** to **3V/3.3 on the board**.
- Connect **GND on the**  **breakout** to **G/GND on the board**.
- Connect **BCLK on the breakout** to **D1/TX on the board**.
- Connect **LRC on the breakout** to **D0/RX on the board**.
- Connect **DIN on the breakout** to **D9 on the board**.

![adafruit_products_FeatherM0MAX98357_bb.jpg](https://cdn-learn.adafruit.com/assets/assets/000/057/793/medium640/adafruit_products_FeatherM0MAX98357_bb.jpg?1532037640)

![adafruit_products_ItsyBitsyM0MAX98357_bb.jpg](https://cdn-learn.adafruit.com/assets/assets/000/057/794/medium640/adafruit_products_ItsyBitsyM0MAX98357_bb.jpg?1532037653)

![adafruit_products_MetroM0MAX98357_bb.jpg](https://cdn-learn.adafruit.com/assets/assets/000/057/795/medium640/adafruit_products_MetroM0MAX98357_bb.jpg?1532037664)

 **For Feather M4 Express:**

&nbsp;

- Connect **VIN on the breakout** to **3V on the board**.
- Connect **GND on the**  **breakout** to **Gnd on the board**.
- Connect **BCLK on the breakout** to **TX on the board**.
- Connect **LRC on the breakout** to **D10 on the board**.
- Connect **DIN on the breakout** to **D11 on the board**.

![adafruit_products_one_one_two.png](https://cdn-learn.adafruit.com/assets/assets/000/127/211/medium640/adafruit_products_one_one_two.png?1706128717)

 **For Metro M4 Express:**

&nbsp;

- Connect **VIN on the breakout** to **3.3 on the board**.
- Connect **GND on the**  **breakout** to **GND on the board**.
- Connect **BCLK on the breakout** to **D3 on the board**.
- Connect **LRC on the breakout** to **D9 on the board**.
- Connect **DIN on the breakout** to **D8 on the board**.

![adafruit_products_MetroM4MAX98357_bb.jpg](https://cdn-learn.adafruit.com/assets/assets/000/057/800/medium640/adafruit_products_MetroM4MAX98357_bb.jpg?1532037742)

## Code Examples

We have two CircuitPython code examples. The first plays a generated tone through the speaker on the breakout. The second plays a wave file. Let's take a look!

## Tone Generation

The first example generates one period of a sine wave and then loops it to generate a tone. You can change the volume and the Hz of the tone by changing the associated variables. Inside the loop, we play the tone for one second and stop it for one second.

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/Adafruit_MAX98357/CircuitPython_I2S_Tone/code.py

For **Feather M0 Express, ItsyBitsy M0 Express** and **Metro M0 Express** , no changes are needed for the code to work.

For **Feather M4 Express** , comment out `audio = audiobusio.I2SOut(board.D1, board.D0, board.D9)` and uncomment `# audio = audiobusio.I2SOut(board.D1, board.D10, board.D11)`.

For **Metro M4 Express** , comment out `audio = audiobusio.I2SOut(board.D1, board.D0, board.D9)` and uncomment `# audio = audiobusio.I2SOut(board.D3, board.D3, board.D8)`.

Now you'll hear one second of a 440Hz tone, and one second of silence.

You can try changing the Hz of the tone to produce different tones. Try changing the number of seconds in `time.sleep()` to produce longer or shorter tones.

## Wave File

The second example plays a wave file. We open the file in a readable format. Then inside the loop, we play the file and tell the code to continue playing the file until it's completed. You can use any [supported wave file](https://learn.adafruit.com/circuitpython-essentials/circuitpython-audio-out#play-a-wave-file). We've included the wave file used in the code.

[StreetChicken.wav](https://cdn-learn.adafruit.com/assets/assets/000/057/801/original/StreetChicken.wav?1532037889)
https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/Adafruit_MAX98357/CircuitPython_I2S_Wave/code.py

The object setup in the code is the same as above.

For **Feather M0 Express, ItsyBitsy M0 Express** and **Metro M0 Express** , no changes are needed for the code to work.

For **Feather M4 Express** , comment out `audio = audiobusio.I2SOut(board.D1, board.D0, board.D9)` and uncomment `# audio = audiobusio.I2SOut(board.D1, board.D10, board.D11)`.

For **Metro M4 Express** , comment out `audio = audiobusio.I2SOut(board.D1, board.D0, board.D9)` and uncomment `# audio = audiobusio.I2SOut(board.D3, board.D3, board.D8)`.

Now you'll hear the wave file play through and loop.

There's plenty you can do with this example. Try playing a different wave file, or, instead of including `while audio.playing: pass`, include a `time.sleep()` to have it play for a specified number of seconds. Check out the [Audio Out page in the CircuitPython Essentials guide](https://learn.adafruit.com/circuitpython-essentials/circuitpython-audio-out) for `pause` and `resume` features.

## Where's my I2S?

We mentioned earlier that the supported M0 boards have multiple I2S pin combinations available to you. The M4 boards have one option. Either way, if you'd like to know what options are available to you, copy the following code into your **code.py** , **connect to the serial console** , and **check out the output**.

These are the results from the ItsyBitsy M0 Express.

![](https://cdn-learn.adafruit.com/assets/assets/000/057/802/medium800/adafruit_products_ItsyI2SPinCombos.png?1532037904)

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/Adafruit_MAX98357/I2S_Test_Script/code.py

# Adafruit MAX98357 I2S Class-D Mono Amp

## I2S Audio FAQ

### 

Try rebooting once after playing some audio. Also make sure you have our latest alsa configuration (check the detailed install page on the Raspberry Pi Setup page for the `/etc/asound.conf`!

If its still not working, you can still change the volume, just use **alsamixer** from a Terminal command prompt.

### 

Yep, this is a known Raspbian Linux thing. Yay Linux! We don't have a fix for it. If it makes you feel better, my fancy Windows development computer does the same thing with my desktop speakers.

You can reduce popping a lot with the '/dev/zero play' option in the i2s setup script. (We added it in October 2018) but you still might get that one initial pop

### 

Make sure you've lowered the volume. The default is 100% which is waaaay too high! Use **alsamixer** to reduce the volume to 50% or so

### 

It will work with _anything_ that has alsa audio support. There's thousands of linux programs so we can't guarantee all of them will work but here's what we found does for sure!

- **PyGame** - see our page on [playing audio with PyGame](../../../../adafruit-speaker-bonnet-for-raspberry-pi/audio-with-pygame) for example code. Volume can be controlled within pygame
- **mpg123** - command line mp3 audio playback. use alsamixer to control the volume
- **aplay** - for playing wav files on the command line
- **Sonic Pi** - tested in the Pixel Desktop. Use the Sonic Pi settings panel to change the volume - it does not seem to care about what global audio volume you set!
- **Scratch 2** - tested in the Pixel Desktop. Works fine but may have a delay and make a popping sound the first time you play audio. You can set volume with alsamixer and also via the app by using the **set volume to nn%** block
- **Scratch 1** - doesn't work, something not set up with Scratch 1 to use alsa?
- **RetroPie/Emulation Station** - audio works within games (we tested NES and MAME libretro) but does not work in the 'main screen' (selecting which game to play interface)

# Adafruit MAX98357 I2S Class-D Mono Amp

## Downloads

- [MAX98357 Datasheet](https://cdn-shop.adafruit.com/product-files/3006/MAX98357A-MAX98357B.pdf)
- [GitHub with EagleCAD PCB Files](https://github.com/adafruit/Adafruit-MAX98357-I2S-Amp-Breakout)
- [3D Models on GitHub](https://github.com/adafruit/Adafruit_CAD_Parts/tree/main/3006%20MAX98357)
- [Fritzing object in the Adafruit Fritzing library](https://github.com/adafruit/Fritzing-Library)

# Schematic

Click to embiggen

![](https://cdn-learn.adafruit.com/assets/assets/000/032/642/medium800/adafruit_products_schem.png?1464034817)

# Fabrication Print

Dimensions in Inches

![](https://cdn-learn.adafruit.com/assets/assets/000/032/641/medium800/adafruit_products_fabprint.png?1464034811)

# 3D Model
![](https://cdn-learn.adafruit.com/assets/assets/000/113/769/medium800/adafruit_products_3006-MAX98357.jpg?1659097530)


## Primary Products

### Adafruit I2S 3W Class D Amplifier Breakout - MAX98357A

[Adafruit I2S 3W Class D Amplifier Breakout - MAX98357A](https://www.adafruit.com/product/3006)
Listen to this good news - we now have an all in one digital audio amp breakout board that works incredibly well with the&nbsp;[Raspberry Pi](https://www.adafruit.com/category/105)! If you're looking for an easy and low cost way to get your digital sound files...

In Stock
[Buy Now](https://www.adafruit.com/product/3006)
[Related Guides to the Product](https://learn.adafruit.com/products/3006/guides)

## Featured Products

### Speaker - 3" Diameter - 8 Ohm 1 Watt

[Speaker - 3" Diameter - 8 Ohm 1 Watt](https://www.adafruit.com/product/1313)
Listen up! This 3" diameter speaker cone is the perfect addition to any audio project where you need an 8 ohm impedance and 1W or less of power. We particularly like this cone as it has 4 handy mounting tabs 60mm apart.  
  
Works great with our <a...></a...>

In Stock
[Buy Now](https://www.adafruit.com/product/1313)
[Related Guides to the Product](https://learn.adafruit.com/products/1313/guides)
### Speaker - 3" Diameter - 4 Ohm 3 Watt

[Speaker - 3" Diameter - 4 Ohm 3 Watt](https://www.adafruit.com/product/1314)
Listen up! This 3" diameter speaker cone is the perfect addition to any audio project where you need an 4 ohm impedance and 3W or less of power. We particularly like this cone as it has 4 handy mounting tabs 60mm apart.  
  
Works great with our <a...></a...>

In Stock
[Buy Now](https://www.adafruit.com/product/1314)
[Related Guides to the Product](https://learn.adafruit.com/products/1314/guides)
### Stereo Enclosed Speaker Set - 3W 4 Ohm

[Stereo Enclosed Speaker Set - 3W 4 Ohm](https://www.adafruit.com/product/1669)
Listen up! This set of two 2.8" x 1.2" speakers are the perfect addition to any audio project where you need 4 ohm impedance and 3W or less of power. We particularly like these speakers as they are small and enclosed for good audio volume and quality. The pair have a handy SPK input...

In Stock
[Buy Now](https://www.adafruit.com/product/1669)
[Related Guides to the Product](https://learn.adafruit.com/products/1669/guides)
### Mini Metal Speaker w/ Wires - 8 ohm 0.5W

[Mini Metal Speaker w/ Wires - 8 ohm 0.5W](https://www.adafruit.com/product/1890)
Listen up! This tiny 1" diameter speaker cone is the perfect addition to any small audio project where you need an 8 Ω impedance and will be using 0.5W or less of power. We particularly like this cone as it's very simple and its metal body is extremely lightweight. <a...></a...>

In Stock
[Buy Now](https://www.adafruit.com/product/1890)
[Related Guides to the Product](https://learn.adafruit.com/products/1890/guides)
### Thin Plastic Speaker w/Wires - 8 ohm 0.25W

[Thin Plastic Speaker w/Wires - 8 ohm 0.25W](https://www.adafruit.com/product/1891)
Listen up! This 1.5" diameter speaker cone is the perfect addition to any audio project where you need an 8Ω impedance and are using 0.25W of power. The speakers are rated at 0.25W, with a maximum input of 0.5W (printed wattage on back of speaker may have either value).

We...

Out of Stock
[Buy Now](https://www.adafruit.com/product/1891)
[Related Guides to the Product](https://learn.adafruit.com/products/1891/guides)

## Related Guides

- [Severence-Inspired Lumon Bluetooth Speaker](https://learn.adafruit.com/bluetooth-speaker.md)
- [RGB Matrix Dreidel Game](https://learn.adafruit.com/rgb-matrix-dreidel-game.md)
- [Robotic AI Bear using ChatGPT](https://learn.adafruit.com/robotic-ai-bear-using-chatgpt.md)
- [Raspberry Pi Zero NPR One Radio](https://learn.adafruit.com/raspberry-pi-zero-npr-one-radio.md)
- [Adafruit Feather RP2040 with DVI Output Port](https://learn.adafruit.com/adafruit-feather-rp2040-dvi.md)
- [Bluefruit Ouija Board](https://learn.adafruit.com/bluefruit-ouija-board.md)
- [Computer Perfection Synthesizer](https://learn.adafruit.com/computer-perfection-synthesizer.md)
- [World's Smallest MAME Arcade Cabinet](https://learn.adafruit.com/worlds-smallest-mame-arcade-cabinet.md)
- [Walkmp3rson: Personal MP3 'Tape' Player](https://learn.adafruit.com/walkmp3rson-personal-mp3-tape-player.md)
- [Magic Band Reader](https://learn.adafruit.com/magic-band-reader.md)
- [ Analog IC Insights On-the-Go by Maxim Integrated](https://learn.adafruit.com/maxim-app.md)
- [Ambient Sound Machine](https://learn.adafruit.com/ambient-machine.md)
- [Circle of Fifths Euclidean Synth with synthio and CircuitPython](https://learn.adafruit.com/circle-of-fifths-euclidean-synth-with-synthio-and-circuitpython.md)
- [See N Say Brain Transplant](https://learn.adafruit.com/see-n-say-brain-transplant.md)
- [Bluetooth Restroom Key Proximity Tracker](https://learn.adafruit.com/bluetooth-restroom-key-proximity-tracker.md)
