In this project, we create a text-to-speech (TTS) sound machine. When a button is pressed, we'll say a different phrase for each button.

Your breadboard should still have the circuit we wired in the project. As a reminder, here is what it should look like:

For our sound machine, we will start with the code from the previous piano project , but we'll replace `Note()` with `Speech()`:

from rstem.button import Button from rstem.sound import Speech import time buttons_and_speech = [ [Button(14), Speech("What's brown and sticky? A stick.")], [Button(15), Speech("What do you call cheese that isn't yours? Nacho Cheese.")], [Button(25), Speech("When is a door not a door? When it's ajar.")], [Button(12), Speech("What is red and smells like blue paint? Red paint.")], ] while True: for button, speech in buttons_and_speech: if button.is_pressed(): if not speech.is_playing(): speech.play(duration=None) else: speech.stop() time.sleep(0.01)

Give it a try!

While that works, you probably noticed that unfortunately you have to hold down the button for the entire time that the speech plays. It would be nice if the speech would start playing when the button was pressed, and just play until it finished, regardless if we held down the button or not. We can actually simplify our code to do this — we only need to remove the code that stops the sound from playing when the button is released:

from rstem.button import Button from rstem.sound import Speech import time buttons_and_speech = [ [Button(14), Speech("What's brown and sticky? A stick.")], [Button(15), Speech("What do you call cheese that isn't yours? Nacho Cheese.")], [Button(25), Speech("When is a door not a door? When it's ajar.")], [Button(12), Speech("What is red and smells like blue paint? Red paint.")], ] while True: for button, speech in buttons_and_speech: if button.is_pressed(): if not speech.is_playing(): speech.play(duration=None) time.sleep(0.01)

1. In the last code example above, there are two nested `if` statements that only allow the speech to start playing if the button is pressed and speech is not already playing. Can you combine the two `if` statements into one?

2. Instead of using all four buttons, use only one. However, modify the code so that each time the button is pressed, it plays the next line of speech, and when it gets through all four, it starts over again.

3. The code:

   from random import randrange print(randrange(4))

   uses the function `randrange()` to print a random number between 0 and 3. Can you modify your code to use `randrange()` to speak a random joke when the button is pressed?