BladeOfLightX
BladeOfLightX

Reputation: 534

Playing sounds with PyQt6

As the PyQt6 module has been released, I have started porting my code from PyQt5 to PyQt6.

In PyQt, there was a module called phonon which was used to play sounds.

In PyQt5, there was a module called QMediaPlayer which was then used to play sounds.

Now, how to play sound in PyQt6?

There was a website which stated that the QMediaPlayer has not been ported yet and shall be done in the PyQt6 version PyQt6.2.

The website is this - https://www.pythonguis.com/faq/pyqt-pyside6-missing-modules/

The website also states that the PyQt6.2 will be released in September 2021.

Is the import renamed?

Upvotes: 1

Views: 5995

Answers (1)

eyllanesc
eyllanesc

Reputation: 243955

It should be noted that:

  • In Qt6 if you want to play a music file then you have 2 options:

    • QSoundEffect

      import sys
      
      from PyQt6.QtCore import QUrl
      from PyQt6.QtGui import QGuiApplication
      from PyQt6.QtMultimedia import QSoundEffect
      
      
      def main():
          app = QGuiApplication(sys.argv)
      
          filename = "sound.wav"
          effect = QSoundEffect()
          effect.setSource(QUrl.fromLocalFile(filename))
          # possible bug: QSoundEffect::Infinite cannot be used in setLoopCount
          effect.setLoopCount(-2)
          effect.play()
      
          sys.exit(app.exec())
      
      
      if __name__ == "__main__":
          main()
      
    • QMediaPlayer.

      import sys
      
      from PyQt6.QtCore import QUrl
      from PyQt6.QtGui import QGuiApplication
      from PyQt6.QtMultimedia import QAudioOutput, QMediaPlayer
      
      
      def main():
          app = QGuiApplication(sys.argv)
      
          filename = "sound.mp3"
          player = QMediaPlayer()
          audio_output = QAudioOutput()
          player.setAudioOutput(audio_output)
          player.setSource(QUrl.fromLocalFile(filename))
          audio_output.setVolume(50)
          player.play()
      
          sys.exit(app.exec())
      
      
      if __name__ == "__main__":
          main()
      
  • The previous classes are available as of Qt 6.2 and at this moment there is no release available in pypi of PyQt6 6.2.0 but you can install it from the Riverbank Computing PyPI Server repositories (see here fore more information):

    python -m pip install --index-url https://riverbankcomputing.com/pypi/simple/ --pre --upgrade PyQt6
    

    Probably in a few days it will already be available in pypi

Upvotes: 8

Related Questions