MAKE A PIANO APP
To upload files, please first save the app
import streamlit as st
import numpy as np
import pygame
import time
from io import BytesIO
# Initialize pygame mixer
pygame.mixer.init()
def get_piano_note_freq(note):
# A4 = 440Hz
A4 = 440
notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
octave = int(note[-1])
note_name = note[:-1]
note_index = notes.index(note_name)
# Calculate semitones from A4
semitones_from_a4 = (octave - 4) * 12 + note_index - notes.index('A')
# Calculate frequency using the formula: f = 440 * (2^(n/12))
freq = A4 * (2 ** (semitones_from_a4 / 12))
return freq
def generate_sine_wave(freq, duration=0.5, sample_rate=44100):
t = np.linspace(0, duration, int(sample_rate * duration))
wave = np.sin(2 * np.pi * freq * t)
# Apply fade out
fade = np.linspace(1, 0, len(wave))
wave = wave * fade
# Normalize and convert to 16-bit integer
wave = np.int16(wave * 32767)
return wave
def play_note(note):
freq = get_piano_note_freq(note)
wave = generate_sine_wave(freq)
# Convert wave to bytes
buffer = wave.tobytes()
sound = pygame.mixer.Sound(buffer)
sound.play()
st.title("🎹 Virtual Piano")
st.write("Click on the keys to play!")
# Define piano keys (2 octaves)
white_keys = ['C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'B4',
'C5', 'D5', 'E5', 'F5', 'G5', 'A5', 'B5']
black_keys = ['C#4', 'D#4', 'F#4', 'G#4', 'A#4',
'C#5', 'D#5', 'F#5', 'G#5', 'A#5']
# Create two rows of buttons
col1, col2 = st.columns([4, 1])
with col1:
st.write("White keys:")
cols = st.columns(len(white_keys))
for i, note in enumerate(white_keys):
with cols[i]:
if st.button(note, key=f"white_{note}", use_container_width=True):
play_note(note)
with col2:
st.write("Black keys:")
cols = st.columns(len(black_keys))
for i, note in enumerate(black_keys):
with cols[i]:
if st.button(note, key=f"black_{note}", use_container_width=True):
play_note(note)
st.markdown("""
### How to play:
1. Click on any key to hear its sound
2. White keys are the natural notes (C, D, E, F, G, A, B)
3. Black keys are the sharp notes (C#, D#, F#, G#, A#)
4. The number after each note represents the octave
### Tips:
- Try playing different combinations of notes
- The piano covers two octaves (4 and 5)
- Each key produces a pure sine wave tone
""")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?