I want to play sounds with QtMultimedia
.
In the case of QMediaPlayer
, I could play mp3 file , it is made from gTTS.
(I think it is okay but I don't like the file remains unless I excute codes for deleting it.)
I make a mp3 file with gTTS module and I want to play sounds with the buffer directly.
It seems that I can make a valid object but QAudioOutput
doesn't do anything.
I seriarize the mp3 file into a database and fetch it when I like.
What is short of my code?
Here is the excerpt of my original Code.
In my original code, the buffer data is in Qt.UserRole + x and I can take them whenever.
The playlist is constucted with QTableWidget
and QTableWidgetItem.
from PySide2 import QtCore
from PySide2 import QtWidgets
from PySide2 import QtMultimedia
import os
import PySide2
import sys
dirname = os.path.dirname(PySide2.__file__)
plugin_path = os.path.join(dirname, 'plugins', 'platforms')
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path
import gtts
def main():
if QtWidgets.QApplication.instance() is not None:
app = QtWidgets.QApplication.instance()
else:
app = QtWidgets.QApplication([])
widget = QtWidgets.QTableWidget()
widget.setColumnCount(2)
text = "hello"
lang = "en"
onsei = gtts.gTTS(text=text, lang=lang)
buf = QtCore.QBuffer()
buf.setOpenMode( QtCore.QIODevice.WriteOnly)
onsei.write_to_fp(buf)
buf.close()
if not widget.rowCount():
widget.setRowCount(1)
else:
widget.insertRow(1)
nitem = QtWidgets.QTableWidgetItem()
nitem.setText(str(widget.rowCount()))
item = QtWidgets.QTableWidgetItem()
item.setText("{0}_tts_lang_{1}.mp3".format(text, lang))
item.setData(QtCore.Qt.UserRole+1, buf.data())
variant = item.data(QtCore.Qt.UserRole+1)
format = QtMultimedia.QAudioFormat()
format.setSampleRate(8000)
format.setChannelCount(1)
format.setSampleSize(16)
format.setCodec("audio/pcm")
format.setByteOrder(QtMultimedia.QAudioFormat.LittleEndian)
format.setSampleType(QtMultimedia.QAudioFormat.UnSignedInt)
buf = QtCore.QBuffer()
buf.setData(variant)
buf.open(QtCore.QIODevice.ReadOnly)
buf.seek(0)
audio = QtMultimedia.QAudioOutput(format, app)
audio.setVolume(0.5)
audio.setBufferSize(buf.size())
audio.start(buf)
buf.close()
print(67)
# sys.exit(QtWidgets.QApplication.exec_())
sys.exit()
if __name__ == "__main__":
main()