简体   繁体   中英

Play a sound with QAudioOutput in PyQt

My app should work both on Windows and Linux(Ubuntu). So I have to reimplement my notification sounds, because QSound does not work under Ubuntu. I am trying with 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. 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:

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.

There has been changes with these METHODS:

Change format.setChannels(1) to format.setChannelCount(1)

Change format.setFrequency(22050) to format.setSampleRate(22050)

See this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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