star wars theme in python

To play the Star Wars theme in Python, you can use the winsound module which is built-in to Python. Here is a code example to play the Star Wars theme:

main.py
import winsound
import time

# Star Wars theme as composed by John Williams
star_wars = [
  ("C4", 500), ("C4", 500), ("C4", 500), ("F4", 350), ("A#4", 150),
  ("C5", 500), ("A#4", 350), ("F4", 150), ("C5", 1000), ("F4", 350),
  ("A#4", 150), ("C5", 500), ("A#4", 350), ("F4", 150), ("C5", 1000),
  ("F5", 500), ("F4", 350), ("F4", 150), ("F5", 350), ("A#4", 250),
  ("F5", 500), ("F4", 350), ("F4", 150), ("F5", 350), ("A#4", 250),
  ("F5", 500), ("A#5", 350), ("A5", 150), ("G#5", 250), ("G5", 250),
  ("F#", 250), ("G#5",450), ("invalid", 500),
  ("C4", 500), ("C4", 500), ("C4", 500), ("F4", 350), ("A#4", 150),
  ("C5", 500), ("A#4", 350), ("F4", 150), ("C5", 1000), ("F4", 350),
  ("A#4", 150), ("C5", 500), ("A#4", 350), ("F4", 150), ("C5", 1000),
  ("F5", 500), ("F4", 350), ("F4", 150), ("F5", 350), ("A#4", 250),
  ("F5", 500), ("F4", 350), ("F4", 150), ("F5", 350), ("A#4", 250),
  ("F5", 500), ("A#5", 350), ("A5", 150), ("G#5", 250), ("G5", 250),
  ("F#", 250), ("G#5", 450), ("invalid", 500),
  ("C6", 250), ("C6", 250), ("C6", 250), ("C6", 250), ("C6", 250), ("G5", 250), ("F5", 250), ("E5", 250),
  ("D#5", 250), ("D5", 250), ("C5", 250), ("A#4", 250), ("F5", 250), ("E5", 250), ("D#5", 250), ("D5", 250),
  ("C5", 250), ("A#4", 250), ("F5", 250), ("E5", 250), ("D#5", 250), ("D5", 250), ("C5", 250), ("A#4", 250),
  ("invalid", 350)
]

# define the frequency of each note
notes = {
  "C4": 262,
  "D4": 294,
  "D#": 311,
  "E4": 330,
  "F4": 349,
  "F#": 370,
  "G4": 392,
  "G#": 415,
  "A4": 440,
  "A#": 466,
  "B4": 494,
  "C5": 523,
  "D5": 587,
  "D#5": 622,
  "E5": 659,
  "F5": 698,
  "F#5": 740,
  "G5": 784,
  "G#5": 831,
  "A5": 880,
  "A#5": 932,
  "B5": 988,
  "C6": 1047
}

# loop through each note in the song, convert the note name to a frequency,
# and play the note for its specified duration using winsound.Beep()
for note in star_wars:
    if note[0] != "invalid":
        frequency = notes[note[0]]
        duration = note[1]
        winsound.Beep(frequency, duration)
        time.sleep(0.01) # add a small delay between each note to create space between them
    else:
        time.sleep(note[1]/1000)
2142 chars
63 lines

Note that the code may not work correctly on Mac or Linux operating systems as winsound is a Windows-specific module.

related categories

gistlibby LogSnag