简体   繁体   English

在PyQt中使用QAudioOutput播放声音

[英]Play a sound with QAudioOutput in PyQt

My app should work both on Windows and Linux(Ubuntu). 我的应用程序应该适用于Windows和Linux(Ubuntu)。 So I have to reimplement my notification sounds, because QSound does not work under Ubuntu. 所以我必须重新实现我的通知声音,因为QSound在Ubuntu下不起作用。 I am trying with QAudioOutput. 我正在尝试使用QAudioOutput。

I can't get it to run with this code, and I don't understand what I have to do. 我无法使用此代码运行它,我不明白我必须做什么。 Do you have any tips? 你有什么建议吗? Or perhaps another idea that works on both OS? 或者也许另一种适用于两种操作系统的想法?

from PyQt4.QtGui import QApplication
import sys
from PyQt4.QtMultimedia import QAudioOutput, QAudioFormat
from PyQt4.QtCore import QFile, QIODevice


app=QApplication(sys.argv) #1st Edit

output=QAudioOutput()

soundFile=QFile()
soundFile.setFileName("C:\\Users\\delete_2.wav")
soundFile.open(QIODevice.ReadOnly)

output.start(soundFile)

app.exec_()                #1st Edit

I don't know if it's the only issue, but you certainly need to create a QApplication object and start the main event loop. 我不知道这是否是唯一的问题,但你当然需要创建一个QApplication对象并启动主事件循环。 Add this to the beginning of your program: 将其添加到程序的开头:

app = QApplication()

Add this to the end of your program: 将其添加到程序的末尾:

app.exec_()

After the line: 行后:

app = QApplication(sys.argv)

(before definition of 'output') insert these lines: (在'output'定义之前)插入以下行:

format = QAudioFormat()  # 2nd Edit
format.setChannels(1)  # 2nd Edit
format.setFrequency(22050)  # 2nd Edit
format.setSampleSize(16)  # 2nd Edit
format.setCodec("audio/pcm")  # 2nd Edit
format.setByteOrder(QAudioFormat.LittleEndian)  # 2nd Edit
format.setSampleType(QAudioFormat.SignedInt)  # 2nd Edit

and replace 并替换

output = QAudioOutput()

with

output = QAudioOutput(format)  #2nd Edit

This work for me on Windows, but now I have no linux distro installed to test the code in that OS, anyway I hope it works in both OSs. 这对我在Windows上工作,但现在我没有安装linux发行版来测试该操作系统中的代码,无论如何我希望它在两个操作系统中都能正常工作。

There has been changes with these METHODS: 这些方法有所变化:

Change format.setChannels(1) to format.setChannelCount(1) format.setChannels(1)更改为format.setChannelCount(1)

Change format.setFrequency(22050) to format.setSampleRate(22050) format.setFrequency(22050)更改为format.setSampleRate(22050)

See this 看到这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM