QSound在对象内的意外行为

2024-10-01 04:44:56 发布

您现在位置:Python中文网/ 问答频道 /正文

在为我的一个程序测试QSound的过程中,我遇到了一个我无法理解的问题。每当我在另一个对象中实现QSound对象时,play()函数似乎不能调用QSound对象的成员变量。你知道吗

下面是我用来分析问题的例子:

  1. 脚本中带有QSound的示例(与预期一样,重复两次声音)
from PyQt5.Qt import QApplication
from PyQt5.QtMultimedia import QSound
import sys

app=QApplication(sys.argv)

SoundObject=QSound("./path/sound.wav")

SoundObject.play()
SoundObject.play("./path/sound.wav")

sys.exit(app.exec())
  1. 另一个对象内的QSound示例(只重复一次声音)
from PyQt5.Qt import QApplication
from PyQt5.QtMultimedia import QSound
import sys

app=QApplication(sys.argv)

class SoundClass:

   def __init__(self):

        SoundObject = QSound("./path/sound.wav")

        print(SoundObject.fileName())  # output= "./path/sound.wav"

        SoundObject.play()  # this doesn't do anything
        SoundObject.play("./path/sound.wav") 

SoundClass()

sys.exit(app.exec())

在这两种情况下,我都希望声音能连续播放两次。但是,当我在另一个对象中使用QSound对象时,“.play()”函数似乎会忽略对象的设置,而是调用静态函数Q声音播放(). QSound对象的其他成员变量(例如setLoops/loops)也会出现相同的行为。你知道吗

在寻找问题的答案时,我发现了一个与C++和QT相同的问题。虽然有人提到QSound可能会被否决,但没有一个明确的答案。(我想知道为什么4年后它仍然是文档的一部分。)

链接到线程:QSound::play("soundpath") call works but a QSound object doesn't

我使用了以下文档:https://www.riverbankcomputing.com/static/Docs/PyQt5/api/qtmultimedia/qsound.html?highlight=qsound#PyQt5.QtMultimedia.QSound

我的规格:

  • Windows 10.0.17134.706
  • Python 3.7版
  • PyQt 5.12型

我是错过了一些重要的东西还是这只是一个错误?你知道吗


Tags: path对象函数fromimportapp声音play
1条回答
网友
1楼 · 发布于 2024-10-01 04:44:56

在第二段代码中,SoundObject变量是一个局部变量,当构造函数完成执行时,它将被删除,因此如果它是一个不依赖于任何对象的静态方法,则不会执行第一个播放,而是执行第二个播放。你知道吗

在第一个代码中,SoundObject变量将在脚本完成时被删除,因为它的作用域更大。你知道吗

解决方案是通过使SoundObject成为类的成员来增加其范围:

from PyQt5.Qt import QApplication
from PyQt5.QtMultimedia import QSound
import sys

app = QApplication(sys.argv)


class SoundClass:
    def __init__(self):
        self.SoundObject = QSound("./path/sound.wav")
        print(self.SoundObject.fileName())  # output= "./path/sound.wav"
        self.SoundObject.play()  # this doesn't do anything
        self.SoundObject.play("./path/sound.wav")


SoundClass()
sys.exit(app.exec())

相关问题 更多 >