Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

Can't record audio in mp3 or wav format using PyQt6.QtMultimedia.QMediaRecorder

I need a voice recorder as part of the program. Below is the test part for voice recorder

import os
import sys
from PyQt6.QtMultimedia import QMediaRecorder, QMediaCaptureSession, QAudioInput, QMediaFormat
from PyQt6.QtWidgets import QMainWindow, QApplication, QPushButton
from PyQt6 import QtCore


# Для тестирования
class MainForm(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.audio_recorder_init('files/pretest')
        self.button_start.clicked.connect(self.start_record)
        self.button_stop.clicked.connect(self.stop_record)

    def initUI(self):
        self.setGeometry(100, 100, 1000, 500)
        self.setFixedSize(self.width(), self.height())
        self.button_start = QPushButton('Start', self)
        self.button_stop = QPushButton('Stop', self)
        self.button_stop.move(0, 50)

    def audio_recorder_init(self, filename):
        mcs = QMediaCaptureSession(self)
        self.inp = QAudioInput(self)
        self.inp.setVolume(1.0)
        mcs.setAudioInput(self.inp)
        self.ardRecorder = QMediaRecorder(self)
        mcs.setRecorder(self.ardRecorder)
        self.ardRecorder.setOutputLocation(QtCore.QUrl.fromLocalFile(os.path.abspath(filename)))
        # media_format = QMediaFormat(QMediaFormat.FileFormat.MP3)
        # media_format.setAudioCodec(QMediaFormat.AudioCodec.MP3)
        # self.ardRecorder.setMediaFormat(media_format)
        self.ardRecorder.setQuality(QMediaRecorder.Quality.LowQuality)
        self.ardRecorder.setEncodingMode(QMediaRecorder.EncodingMode.ConstantQualityEncoding)
        self.ardRecorder.setAudioChannelCount(1)
        self.ardRecorder.setAudioSampleRate(-1)

    def start_record(self):
        self.ardRecorder.record()

    def stop_record(self):
        self.ardRecorder.stop()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    MF = MainForm()
    MF.show()
    sys.exit(app.exec())

The program works and records sound in .m4a format. But I want to get .mp3 or .wav files.

If you uncomment the lines

        # media_format = QMediaFormat(QMediaFormat.FileFormat.MP3)
        # media_format.setAudioCodec(QMediaFormat.AudioCodec.MP3)
        # self.ardRecorder.setMediaFormat(media_format)

then on startup it outputs to the console [mp3_mf @ 0000024738C00AC0] MFT name: 'MP3 Encoder ACM Wrapper MFT'. This creates a file with the .m4a extension, but the player refuses to play it (but the sound is still recorded, I tried to convert this file through an online converter to mp3 and I managed to play it). If you change the file format and audio codec from MP3 to Wave, then the program generally hangs. What could be the problem? And how can you solve it?

❌
❌