0

I am making a digital piano software with PyQt5 and one of the functions of it is to be able to play notes automatically. I have registered several musical notes under a list, and am trying to use QSound to play them, however when I do, they play all at the same time. How would I be able to add a delay between sounds? Thanks for the help

def playSheetMusic(self, Piano):
        sheetmusic = ["A5", "G4", "C4", "C4", "C4"]
        note1 = sheetmusic[0]
        file1 = "pianokeys/" + note1 +".wav"
        note2 = sheetmusic[1]
        file2 = "pianokeys/" + note2 +".wav"
        QSound.play(file1)
        QSound.play(file2)
Jerry Zhao
  • 15
  • 2

1 Answers1

0

You should simply be able to add a delay with qWait() function like so:

from PyQt4 import QtTest

def playSheetMusic(self, Piano):
        sheetmusic = ["A5", "G4", "C4", "C4", "C4"]
        note1 = sheetmusic[0]
        file1 = "pianokeys/" + note1 +".wav"
        note2 = sheetmusic[1]
        file2 = "pianokeys/" + note2 +".wav"
        QSound.play(file1)
        QtTest.QTest.qWait(1000)        # put however many milliseconds delay you want
        QSound.play(file2)

Hope this helps :)

Sahith Kurapati
  • 1,617
  • 10
  • 14
  • Hi Sahith, thanks for the quick response! Unfortunately when I try this method, the software actually just freezes for a second, and then both of the music notes play at the same time. Would you happen to know any reason why this happens? – Jerry Zhao Jun 20 '20 at 06:38
  • Okay I've read the documentation and it's because when you are using `QSound` it uses the same object instantiated by the class, hence it plays both sounds at the same time when `.play()` is called. According to the documentation there is a function called `QSound.isFinished()`. Can you try using that to check when it stops playing the first sound and then play the second sound? – Sahith Kurapati Jun 20 '20 at 06:54
  • I looked a little bit into the isFinished() method and while that didn't seem to work, there was another recommendation with QTimer. I've just coded something with that and my software seems to be working now! Thanks so much for the help. – Jerry Zhao Jun 20 '20 at 07:38