Domanda

I have trouble using QAudioRecorder without using QMainWindow. It would create a file with 0 bytes, which is not playable by most common media players after running this script here:

int main(int argc, char *argv[]){
    QAudioRecorder q;
    q.setAudioInput(q.audioInputs()[0]);
    q.setOutputLocation(QUrl::fromLocalFile("simon.amr"));
    q.record();
    Sleep(10000);
}

Whereas this works:

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
};

QAudioRecorder q;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    std::cout << "DEFAULT: " << q.defaultAudioInput().toStdString() << std::endl;
    std::cout << "List: " << q.audioInputs().join(',').toStdString() << std::endl;
    std::cout << "STATUS 0: " << q.status() << std::endl;
    std::cout << "Location: " << QUrl::fromLocalFile("simon.amr").path().toStdString() << std::endl;
    q.setAudioInput(q.audioInputs()[0]);
    q.setOutputLocation(QUrl::fromLocalFile("simon.amr"));
    q.record();

    std::cout << "STATUS 1: " << q.status() << std::endl;
}

MainWindow::~MainWindow()
{
    std::cout << "STATUS 2: " << q.status() << std::endl;
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    MainWindow recorder;
    recorder.show();

    return app.exec();
}

How can I use QAudioRecorder without QMainWindow? Am I doing something wrong?

È stato utile?

Soluzione

QAudioRecorder's internal states are managed through signals and slots. This requires a running event loop;

QCoreApplication should be used for console applications.

QApplication should be used for GUI applications.

In your above example, the MainWindow isn't even necessary, it's the app.exec() where the magic is happening.

Altri suggerimenti

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QAudioRecorder q; 
    q.setAudioInput(q.audioInputs()[0]);    
    q.setOutputLocation(QUrl::fromLocalFile("simon.amr"));    
    q.record();

    return app.exec();
}

You need a qt event loop. Sleep does not provide the event and signal processing that QCoreApplication provides.

Please read it up or you won't come far in Qt, since this is a Qt core mechanic.

Good luck with your project!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top