Code gets stuck on the last note of the melody after being played

Read the forum guidelines to see how to properly post code.
Use the IDE autoformat tool (ctrl-t or Tools, Auto format) before posting code in code tags.

The way that the code is posted it is very difficult to copy to a text editor or IDE to examine and verify.

Please edit your original post to put the code in code tags.