In our tutorial today, we’ll go through the steps required to get Raspberry Pi to play a sound when a button is pushed. Nothing big, nothing fancy, but it’s a good start to understand how the whole thing works.

Hardware required:

Breadboard

Push button

10 K resistor

3 male/female jumper cables

The circuit looks like this.

I suppose that you have JDK 8 and WiringPi installed on your Raspberry Pi

Install audio

To enable sound on your Raspberry Pi, type the following commands:

sudo apt-get install alsa-utils

sudo apt-get install mpg321

After rebooting the Pi, you can load the sound drivers and specify the interface for audio output using these commands:

sudo modprobe snd_bcm2835

sudo amixer cset numid=3 n

The n parameter can take three values: 0, 1 and 2, each for a specific interface. 0 for auto, 1 for analog and 2 for HDMI.

In order to test if the sound is working fine, let’s get an audio file:

wget http://www.soundjay.com/button/sounds/beep-01a.mp3

Then type the command sudo mpg321 beep-01a.mp3

You should now be able to hear the sound through your headphones if you chose the analog interface.

Let’s now write the code for the push button.

Setting up the development environment – NetBeans



Create a new Java project, click on project-> Properties-> Run ->Manage Platforms-> Add platform. Select Remote Java Standard Edition.

You’ll then be asked to set up the remote platform.

In order for this code to work, you have to add the Pi4J and the JLayer libraries.

package javaapplication1; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; import java.io.BufferedInputStream; import java.io.FileInputStream; import javazoom.jl.decoder.JavaLayerException; import javazoom.jl.player.Player; public class JavaApplication1 { public static void main(String args[]) throws InterruptedException { System.out.println("Start listening."); final GpioController gpio = GpioFactory.getInstance(); final GpioPinDigitalInput myButton = gpio.provisionDigitalInputPin(RaspiPin.GPIO_02, PinPullResistance.PULL_DOWN); myButton.addListener(new GpioPinListenerDigital() { @Override public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) { Player player = null; try { FileInputStream fis = new FileInputStream("/home/pi/beep-01a.mp3"); BufferedInputStream bis = new BufferedInputStream(fis); player = new Player(bis); } catch (Exception e) { System.out.println(e.getMessage()); } try { player.play(); } catch (JavaLayerException e) { System.out.println(e.getMessage()); } } }); // keep program running until user aborts (CTRL-C) for (;;) { Thread.sleep(500); } } }