Fundamentals 7 min read

Automated Piano Playing with Python: Simulating Keyboard Input and Multithreaded Melody Control

This article demonstrates how to use Python to create an automated piano script that simulates keyboard presses, employs multithreading to play multiple hands simultaneously, and controls a web‑based piano interface, providing complete code examples and step‑by‑step instructions.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Automated Piano Playing with Python: Simulating Keyboard Input and Multithreaded Melody Control

The author describes a personal project to help a friend fulfill a piano‑playing dream by writing a Python script that can automatically play piano pieces without any real piano skills.

Effect demonstration – an animated GIF shows the final result of the script playing on an online piano.

Implementation steps – the solution is broken down into four main tasks:

Implement a play function that simulates key presses and timing for each note.

Add separate threads for melody, chords, and individual fingers to achieve a two‑hand effect.

Define the musical score, specifying main melody, chords, and finger assignments.

Automatically open the autopiano web page and send keyboard events to trigger the simulated performance.

Play function code

<code>def play_piano(music, keytime):
    for n in music:
        if n.isupper():
            keyboard.press(Key.shift)
            time.sleep(0.001)
            keyboard.press(n.lower())
            time.sleep(keytime - 0.001)
            keyboard.release(n.lower())
            keyboard.release(Key.shift)
        elif n == "|" or n == ")":
            pass
        elif n in "!@$%^*(":
            keyboard.press(Key.shift)
            time.sleep(0.001)
            keyboard.press("1245689"["!@$%^*(".index(n)])
            time.sleep(keytime - 0.001)
            keyboard.release("1245689"["!@$%^*(".index(n)])
            keyboard.release(Key.shift)
        elif n != " " and n != "-":
            keyboard.press(n)
            if music.index(n) != len(music) - 1 and music[music.index(n) + 1] == ")":
                time.sleep(keytime / 2)
            else:
                time.sleep(keytime)
            keyboard.release(n)
        elif n == "-":
            time.sleep(2 * keytime)
        else:
            time.sleep(keytime)
</code>

Adding melody threads – the script defines strings for right‑hand and left‑hand parts (including thumb and index finger patterns) and launches them with a helper thread_play function to run play_piano concurrently.

<code>right = "s-as f |a --u |p -ops |" \
        "o --uu|i-uis-|u - sss|a-Ii a |" \
        "a --|"
left = "etu --|0wr --|qet --|" \
       "80w --|9qe --|80w --|7Qr --|" \
       "370Wr |"
thread_play(play_piano, 0.3, right, left)
</code>

More complex examples show how to split the score into separate tracks for thumbs and index fingers, adjusting the timing parameter to achieve realistic articulation.

Preparing the performance – the script installs the Chrome driver, launches the autopiano website, and uses webbrowser to open the page.

<code>if __name__ == '__main__':
    keyboard = Controller()
    chromePath = r'C:\Program Files\Google\Chrome\Application\chrome.exe'
    webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(chromePath))
    webbrowser.get('chrome').open('https://www.autopiano.cn', new=1, autoraise=True)
</code>

Finally, the author notes that by modifying the note strings according to any sheet music, the same framework can be used to automate the playback of different piano pieces.

PythonAutomationmultithreadingkeyboardscriptingpiano
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.