87 lines
2.6 KiB
Python
87 lines
2.6 KiB
Python
import serial
|
|
import time
|
|
import pygame
|
|
from pydub import AudioSegment
|
|
import serial.tools.list_ports
|
|
|
|
# Define the paths
|
|
#Short notes
|
|
NOTES_PATH = "pysrc\\notes\\mp3-master\\"
|
|
#Long notes
|
|
#NOTES_PATH = r"C:\Users\Balthazar\Shared\ECAM\Advance Robotique\Project\Player\notes\high-quality-master\renamed\\"
|
|
SERIAL_PORT = "COM5"
|
|
BAUD_RATE = 115200
|
|
|
|
# New Features
|
|
wait_note_finish = False
|
|
keyboard_input = False
|
|
check_com3 = True
|
|
|
|
pygame.mixer.init()
|
|
|
|
notes = ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"]
|
|
|
|
def play_note_with_pygame(note):
|
|
try:
|
|
pygame_sound = pygame.mixer.Sound(f"{NOTES_PATH}{note}.mp3")
|
|
pygame_sound.play()
|
|
if wait_note_finish:
|
|
while pygame.mixer.get_busy():
|
|
pygame.time.Clock().tick(10)
|
|
except Exception as e:
|
|
print(f"Error playing {note}: {e}")
|
|
|
|
# Check if COM port is connected
|
|
if check_com3:
|
|
ports = list(serial.tools.list_ports.comports())
|
|
com3_found = any(port.device == SERIAL_PORT for port in ports)
|
|
if not com3_found:
|
|
print(f"{SERIAL_PORT} not found. Switching to keyboard input mode.")
|
|
keyboard_input = True
|
|
|
|
try:
|
|
ser = serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1)
|
|
time.sleep(2)
|
|
except Exception as e:
|
|
print(f"Error opening {SERIAL_PORT}: {e}")
|
|
keyboard_input = True
|
|
|
|
print("Listening for Arduino input...")
|
|
|
|
while True:
|
|
try:
|
|
# Keyboard input fallback
|
|
if keyboard_input:
|
|
user_input = input("Enter octave; note (e.g., 4; C) or 'q' to quit: ")
|
|
if user_input == 'q':
|
|
break
|
|
try:
|
|
octave_str, note_part = user_input.split(";")
|
|
octave = int(octave_str.strip())
|
|
note = note_part.strip().split()[0] # Get only the first note
|
|
if note in notes:
|
|
play_note_with_pygame(f"{note}{octave}")
|
|
except:
|
|
print("Invalid input format.")
|
|
|
|
# Arduino input
|
|
data = ser.readline().decode('utf-8', errors='ignore').strip()
|
|
if data:
|
|
print("data: " + data)
|
|
try:
|
|
octave_str, note_part = data.split(";")
|
|
octave = int(octave_str.strip())
|
|
note = note_part.strip().split()[0] # Only one note expected
|
|
if note in notes:
|
|
play_note_with_pygame(f"{note}{octave}")
|
|
except Exception as e:
|
|
print(f"Invalid format or error parsing data: {e}")
|
|
|
|
except KeyboardInterrupt:
|
|
print("Exiting...")
|
|
break
|
|
except Exception as e:
|
|
print(f"Error: {e}")
|
|
|
|
ser.close()
|