There are several ways to generate audio on the Raspberry Pi. Most rely on the ALSA (Advanced Linux Sound Architecture) API.
This utilizes either the standard 3.5mm audio jack or the HDMI connector and can be accessed as an ALSA device.
The audio jack is only suitable for driving headphones. Regular speakers will not be loud enough unless additional amplification is used. Note, the Pi Zero does not have an audio jack.
The Pi will automatically route audio through HDMI if the attached monitor advertises audio capabilities. This behavior can be controlled with
sudo raspi-config
Advanced Options → Audio
These come in many shapes and forms and will also be accessed as ALSA devices. Biggest drawback is that they be rather large in comparison to a Raspberry Pi and may stick out of one of the USB ports.
This is the recommended way of playing back sound on a Pi and also utilizes ALSA. I2S is a digital interface and the most convenient boards do both digital to analog conversion (DAC) and amplification. Boards range in price from under $10 for mono audio to well over $100 for an almost audiophile experience. Find out more about I2S for the Pi here.
This is the only non-ALSA solution described here. Using PWM sound requires some programming and the result will only be suitable for simple melodies - think greeting cards that play a simple song.
The Pytorinox Python Library provides a tool for extracting simple melodies from midi files and playing them via buzzer.py back.
To play sound on the default ALSA device run aplay
1 like so:
aplay <wave-file>
If you do not have a wave file, the following speaker-test
2 command can be used for testing
speaker-test
To adjust the volume use the interactive alasamixer
3
alsamixer
If multiple sound devices exists, programs can get confused as to which device to use. The easiest way to avoid these problems is to only have only a single device visible to the software. This can be accomplished by black-listing the device drivers for the unused devices. For example to disable the built-in audio either edit /etc/modprobe.d/alsa-blacklist.conf
and add the line
blacklist snd_bcm2835
or edit /boot/config.txt
and remove the line
dtparam=audio=on