Playing Games with Sound

In this project, you will learn how to play online games using a Sound Phidget and pynput!

Prerequisites

This project assumes you are familiar with the following

Setup

Make sure you have all the parts before moving on.

Sound Phidget

USB cable

Phidget cable

Install pynput

In order to use pynput, you first have to install it. You do this in the same way you previously installed the Phidget22 library. Simply navigate to your package manager, search for pynput and press install!

Thonny

If you're using Thonny, select Tools > Manage Packages and search for pynput.

PyCharm

If you're using PyCharm, select File > Settings > Python Interpreter and use the + symbol to install pynput.

PyScripter

If you're using PyScripter, select Tools > Tools > Install Packages with pip and enter pynput.

Write code (Python)

Copy the code below into a new Python project. If you need a reminder of how to do this, revisit the Getting Started Course.

  
#Add Phidgets Library
from Phidget22.Devices import *
from Phidget22.Devices.SoundSensor import *
from pynput.mouse import Button, Controller
#Required for sleep statement
import time
 
#Sound Sensor Event
def onSPLChange(self, dB, dBA, dBC, Octaves):
    if (dB > 70): #modify this value based on how loud the sound is
        mouse.press(Button.left)
    else:
        mouse.release(Button.left)
 
#Create
mouse = Controller() #this is from the pynput library
soundSensor = SoundSensor()

#Subscribe to Events
soundSensor.setOnSPLChangeHandler(onSPLChange)

#Open
soundSensor.openWaitForAttachment(1000)

#Set Data Interval to minimum | This will increase the data rate from the sensor to make your program more responsive
soundSensor.setDataInterval(soundSensor.getMinDataInterval())
 
while True:
    # loop forever
    time.sleep(0.1)
  

Run Your Program

Find a game similar to Flappy Bird that uses the mouse as input:

Run your Python program and move your mouse pointer over the play area. Making a loud noise will start the game. From there continuing to make noise will move the helicopter up, and stopping will cause it to fall.

Practice

  1. Try using specific frequencies from the Sound Phidget to move the helicopter.

What are Phidgets?

Phidgets are programmable USB sensors. Simply plug in your sensor, write code in your favorite language and go!

Phidgets have been used by STEM professionals for over 20 years and are now available to students.

Learn more

Set your preferences

Windows

Mac OS

Raspberry Pi

Java

Python

C#

Swift

NetBeans

Processing

Eclipse

Thonny

PyCharm

PyScripter

Visual Studio

Xcode

Setting your preferred operating system, programming language and environment lets us display relevant code samples for the Getting Started Tutorial, Device Tutorials and Projects

Done