User:Wordfa/oldphonehack/code14nov
< User:Wordfa | oldphonehack
#!/usr/bin/env python
import sys, os, time, random, pygame
import RPi.GPIO as GPIO
import argparse
import tempfile
import queue
import sys
from os import walk
import random
import numpy # Make sure NumPy is loaded before it is used in the callback
assert numpy # avoid "imported but unused" message (W0611)
import datetime
## Folder Config
folder = 'recordings/'
processedFolder = 'processed/'
rawFolder = 'raw/'
## Recently Recorded File
fileForProcessing = ''
## Varible to detect is Launch Sequence has happened
launched = True
# Name pins
dialPIN = 25
numberPIN = 23
handsetPIN = 24
# Set Up Pins
GPIO.setmode(GPIO.BCM)
GPIO.setup(dialPIN, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(handsetPIN, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(numberPIN, GPIO.IN, pull_up_down = GPIO.PUD_UP)
# Start audio mixer
pygame.mixer.init()
def getNumber():
print('Listening for Number Presses')
# number of Pulses
nPulsen = 0
# Watch Dail or Button
DialContact = GPIO.input(dialPIN)
NumberContact = GPIO.input(numberPIN) # Low if pressed
while DialContact == False and NumberContact == True:
DialContact = GPIO.input(dialPIN)
NumberContact = GPIO.input(numberPIN)
# Number Pressed (Selected)
if NumberContact == False:
return -1
# Handle Pulses
done = False
while done == False and DialContact == True:
nPulsen = nPulsen + 1
startTime = time.time()
time.sleep(0.1)
DialContact = GPIO.input(dialPIN)
# Check time between Pulses
while done == False and DialContact == False:
if time.time() - startTime >= 0.2:
done = True
DialContact = GPIO.input(dialPIN)
# Return number
number = nPulsen % 10
# Play number on Tone
playAudio(f'tones/{number}.mp3', True)
return number
## Process Recently Recorded File
def handleRecording(fileName):
global folder, processedFolder, rawFolder, fileForProcessing
## Removes Noise
os.system(f"sox '{folder + rawFolder + fileName}.mp3' '{folder + rawFolder + fileName}-Clean.mp3' noisered noise.prof 0.10")
## Normalises Volume
os.system(f"sox '{folder + rawFolder + fileName}-Clean.mp3' '{folder + rawFolder + fileName}-Clean-Louder.mp3' gain +6")
## Normalises Volume
os.system(f"sox --norm '{folder + rawFolder + fileName}-Clean-Louder.mp3' '{folder + processedFolder + fileName}-Clean-Louder.mp3'")
## Resets fileForProcessing so it doenst run again until new recording
fileForProcessing = ''
print('recording processed')
## Tell you when handset is picked up/ Put Down
def handsetCallback(channel):
global launched
global fileForProcessing
print('handset State Change')
handsetContact = GPIO.input(handsetPIN)
## Checks if someone was recording on hang up
if fileForProcessing != '':
# Stop Recording if recording
os.system('killall rec')
print('Recoridng stopped')
# Send file for processing
print("file for processing", fileForProcessing)
handleRecording(fileForProcessing)
# Restart Script
launched = False
GPIO.cleanup()
python = sys.executable
os.execl(python, python, * sys.argv)
# Use an interrupt for the handset, because it can be put down at any time
GPIO.add_event_detect(handsetPIN, GPIO.BOTH, callback = handsetCallback)
def playAudio(fileName, playthrough = False):
print('Play Audio: ', fileName)
pygame.mixer.music.load(fileName)
pygame.mixer.music.set_volume(1)
pygame.mixer.music.play()
if(playthrough):
while pygame.mixer.music.get_busy() == True:
continue
time.sleep(1)
def startRecording():
global fileForProcessing, rawFolder,folder
## TODO: INSERT 'Please leave a msg after tone etc'
#play Tone
playAudio('tones/machineBeep.wav', True)
##Assign File name based on time
fileName = datetime.datetime.now().strftime("%m-%d-%Y, %H:%M:%S")
fileFolder = folder + rawFolder + fileName
fileForProcessing = fileName
print('Started recording: ', fileForProcessing)
os.system(f"rec '{fileFolder}.mp3'")
## Keeps it recording and not going to menu || not sure if this done anything
handsetContact = GPIO.input(handsetPIN)
while handsetContact == False:
print('recording')
handsetContact = GPIO.input(handsetPIN)
time.sleep(1)
# print('Recoridng stopped')
def runFunc(number):
global folder, processedFolder
print('running Func ' , number)
## Check if a file is playing, stop it if it is
if pygame.mixer.music.get_busy() == True:
pygame.mixer.music.stop()
## Do a function based on number
if number == 1:
## Playing Sound from proccessed folder
## Give it a file
file = random.choice(filenames)
file = folder + processedFolder + file
playAudio(file, True)
elif number == 2:
## Start recording
startRecording()
elif number == 3:
print('Playing in Random Order')
# Play each file in random order
for file in random.sample(filenames, len(filenames)):
print(file)
file = folder + processedFolder + file
playAudio(file, True)
time.sleep(1)
### TODO: PLAY A TONE IN BETWEEN
else:
print('No Function for number ', number)
# Main Loop of the code
while True:
try:
# Compile a list of audio files to play
filenames = next(walk(folder + processedFolder), (None, None, []))[2]
print('Number of Audio Files:', len(filenames))
# Wait for pick up
print("Wait for pick up...")
handsetContact = GPIO.input(handsetPIN)
while handsetContact == True:
handsetContact = GPIO.input(handsetPIN)
# If handset up do this
time.sleep(1)
while True:
# Check if we are launching for the first time
if launched == False:
# Play dail tone
dailTone = "Ringing_3rings.mp3"
playAudio(dailTone,True)
# Play greating
greeting = "testIntro.mp3"
playAudio(greeting,True)
# Main menu
# Play greating
menuAudio = "testIntro.mp3"
playAudio(menuAudio)
print("Press a number")
launched = True
# Wait for number press
number = getNumber()
print("number is: ", number)
runFunc(number)
time.sleep(1)
except KeyboardInterrupt: # Ctrl+C
print('disconnecting aggressivly')
GPIO.cleanup()