如何录制无限长度的音轨并将其保存到文件中?

How do I record an audio track of unlimited length and save it to a file?

如何录制无限长度的音轨并将其保存到 PySide/PyQt 文件?

我需要在 PySide 中录制不限长度的音轨。将来,按下按钮即可停止录制。我尝试了 运行ning 官方文档中的代码 QMediaRecorder.

from PySide6.QtCore import QUrl, QDir
from PySide6.QtMultimedia import QMediaCaptureSession, QAudioInput, QMediaRecorder, QMediaFormat

session = QMediaCaptureSession()
audioInput = QAudioInput()
session.setAudioInput(audioInput)
recorder = QMediaRecorder()
session.setRecorder(recorder)
recorder.setMediaFormat(QMediaFormat.MP3)
recorder.setQuality(QMediaRecorder.HighQuality)
file_location = QUrl(QDir.currentPath() + '/test.mp3')
recorder.setOutputLocation(file_location)
recorder.record()

程序 运行s 大约 2-3 秒,之后它以代码 0 终止。该文件没有出现在当前目录中。我在 Windows.

上尝试 运行 这个

您必须 运行 Qt 事件循环中的脚本:

import os
from pathlib import Path

from PySide6.QtCore import QDir, QUrl 
from PySide6.QtMultimedia import (
    QMediaCaptureSession,
    QAudioInput,
    QMediaRecorder,
    QMediaFormat,
)
from PySide6.QtWidgets import QApplication, QPushButton


def main():
    app = QApplication([])

    session = QMediaCaptureSession()
    audioInput = QAudioInput()
    session.setAudioInput(audioInput)
    recorder = QMediaRecorder()
    session.setRecorder(recorder)
    recorder.setMediaFormat(QMediaFormat.MP3)
    recorder.setQuality(QMediaRecorder.HighQuality)
    filename = Path(QDir.currentPath()) / "test.mp3"
    url = QUrl.fromLocalFile(os.fspath(filename))
    recorder.setOutputLocation(url)
    recorder.record()

    button = QPushButton("Stop")
    button.show()
    button.clicked.connect(recorder.stop)

    app.exec()


if __name__ == "__main__":
    main()