Qt 6.x
The Qt SDK
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
audio.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4/* Audio related snippets */
5#include <QFile>
6#include <QTimer>
7#include <QDebug>
8#include <qobject.h>
9#include <qfile.h>
10
11#include "qaudiodevice.h"
12#include "qaudiosource.h"
13#include "qaudiooutput.h"
14#include "qaudiodecoder.h"
15#include "qmediaplayer.h"
16#include "qmediadevices.h"
17
18class AudioInputExample : public QObject {
20public:
21 void setup();
22
23
24public Q_SLOTS:
25 void stopRecording();
27
28private:
30 QFile destinationFile; // Class member
31 QAudioSource* audio; // Class member
33};
34
35
38{
39 destinationFile.setFileName("/tmp/test.raw");
41
43 // Set up the desired format, for example:
44 format.setSampleRate(8000);
45 format.setChannelCount(1);
46 format.setSampleFormat(QAudioFormat::UInt8);
47
49 if (!info.isFormatSupported(format)) {
50 qWarning() << "Default format not supported, trying to use the nearest.";
51 }
52
53 audio = new QAudioSource(format, this);
55
57 audio->start(&destinationFile);
58 // Records audio for 3000ms
59}
61
64{
65 audio->stop();
66 destinationFile.close();
67 delete audio;
68}
70
73{
74 switch (newState) {
76 if (audio->error() != QAudio::NoError) {
77 // Error handling
78 } else {
79 // Finished recording
80 }
81 break;
82
84 // Started recording - read from IO device
85 break;
86
87 default:
88 // ... other cases as appropriate
89 break;
90 }
91}
93
94
97public:
98 void setup();
99
100public Q_SLOTS:
102
103private:
105 QFile sourceFile; // class member.
106 QAudioSink* audio; // class member.
108};
109
110
113{
114 sourceFile.setFileName("/tmp/test.raw");
115 sourceFile.open(QIODevice::ReadOnly);
116
118 // Set up the format, eg.
119 format.setSampleRate(8000);
120 format.setChannelCount(1);
121 format.setSampleFormat(QAudioFormat::UInt8);
122
124 if (!info.isFormatSupported(format)) {
125 qWarning() << "Raw audio format not supported by backend, cannot play audio.";
126 return;
127 }
128
129 audio = new QAudioSink(format, this);
131 audio->start(&sourceFile);
132}
134
137{
138 switch (newState) {
140 // Finished playing (no more data)
141 audio->stop();
142 sourceFile.close();
143 delete audio;
144 break;
145
147 // Stopped for other reasons
148 if (audio->error() != QAudio::NoError) {
149 // Error handling
150 }
151 break;
152
153 default:
154 // ... other cases as appropriate
155 break;
156 }
157}
159
161{
164 format.setSampleRate(44100);
165 // ... other format parameters
166 format.setSampleFormat(QAudioFormat::Int16);
168
171 for (const QAudioDevice &device : devices)
172 qDebug() << "Device: " << device.description();
174}
175
178public:
179 void decode();
180
181public Q_SLOTS:
184};
185
187{
189 QAudioFormat desiredFormat;
190 desiredFormat.setChannelCount(2);
192 desiredFormat.setSampleRate(48000);
193
194 QAudioDecoder *decoder = new QAudioDecoder(this);
195 decoder->setAudioFormat(desiredFormat);
196 decoder->setSource("level1.mp3");
197
199 decoder->start();
200
201 // Now wait for bufferReady() signal and call decoder->read()
203}
204
206
208void applyVolume(int volumeSliderValue)
209{
210 // volumeSliderValue is in the range [0..100]
211
212 qreal linearVolume = QAudio::convertVolume(volumeSliderValue / qreal(100.0),
215
216 player.setVolume(qRound(linearVolume * 100));
217}
void applyVolume(int volumeSliderValue)
[Volume conversion]
Definition audio.cpp:208
void AudioDeviceInfo()
[Audio output state changed]
Definition audio.cpp:160
QMediaPlayer player
Definition audio.cpp:205
IOBluetoothDevice * device
void handleStateChanged(QAudio::State newState)
void handleStateChanged(QAudio::State newState)
[Audio input stop recording]
Definition audio.cpp:72
void setup()
[Audio input setup]
Definition audio.cpp:36
void stopRecording()
[Audio input setup]
Definition audio.cpp:63
[Audio input state changed]
Definition audio.cpp:95
void setup()
[Audio output setup]
Definition audio.cpp:111
void handleStateChanged(QAudio::State newState)
[Audio output setup]
Definition audio.cpp:136
The QAudioDecoder class implements decoding audio.
void start()
Starts decoding the audio resource.
void setSource(const QUrl &fileName)
Sets the current audio file name to fileName.
void setAudioFormat(const QAudioFormat &format)
Set the desired audio format for decoded samples to format.
void bufferReady()
Signals that a new decoded audio buffer is available to be read.
The QAudioDevice class provides an information about audio devices and their functionality.
The QAudioFormat class stores audio stream parameter information.
constexpr void setSampleRate(int sampleRate) noexcept
Sets the sample rate to samplerate in Hertz.
constexpr void setSampleFormat(SampleFormat f) noexcept
Sets the sample format to format.
constexpr void setChannelCount(int channelCount) noexcept
Sets the channel count to channels.
The QAudioSink class provides an interface for sending audio data to an audio output device.
Definition qaudiosink.h:24
void stop()
Stops the audio output, detaching from the system resource.
void stateChanged(QAudio::State state)
This signal is emitted when the device state has changed.
void start(QIODevice *device)
Starts transferring audio data from the device to the system's audio output.
QAudio::Error error() const
Returns the error state.
The QAudioSource class provides an interface for receiving audio data from an audio input device.
QAudio::Error error() const
Returns the error state.
void stop()
Stops the audio input, detaching from the system resource.
void start(QIODevice *device)
Starts transferring audio data from the system's audio input to the device.
void stateChanged(QAudio::State state)
This signal is emitted when the device state has changed.
void close() override
Calls QFileDevice::flush() and closes the file.
\inmodule QtCore
Definition qfile.h:93
bool open(OpenMode flags) override
Opens the file using OpenMode mode, returning true if successful; otherwise false.
Definition qfile.cpp:881
void setFileName(const QString &name)
Sets the name of the file.
Definition qfile.cpp:302
QList< QAudioDevice > audioOutputs
\qmlproperty list<audioDevice> QtMultimedia::MediaDevices::audioOutputs Contains a list of available ...
QAudioDevice defaultAudioOutput
\qmlproperty audioDevice QtMultimedia::MediaDevices::defaultAudioOutput Returns the default audio out...
QAudioDevice defaultAudioInput
\qmlproperty audioDevice QtMultimedia::MediaDevices::defaultAudioInput Returns the default audio inpu...
The QMediaPlayer class allows the playing of a media files.
\inmodule QtCore
Definition qobject.h:90
static QMetaObject::Connection connect(const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
\threadsafe
Definition qobject.cpp:2823
bool singleShot
whether the timer is a single-shot timer
Definition qtimer.h:22
void newState(QList< State > &states, const char *token, const char *lexem, bool pre)
State
\value ActiveState Audio data is being processed, this state is set after start() is called and while...
Definition qaudio.h:25
@ StoppedState
Definition qaudio.h:25
@ IdleState
Definition qaudio.h:25
@ ActiveState
Definition qaudio.h:25
@ NoError
Definition qaudio.h:24
float convertVolume(float volume, VolumeScale from, VolumeScale to)
Converts an audio volume from a volume scale to another, and returns the result.
Definition qaudio.cpp:91
@ LogarithmicVolumeScale
Definition qaudio.h:30
@ LinearVolumeScale
Definition qaudio.h:28
EGLDeviceEXT * devices
int qRound(qfloat16 d) noexcept
Definition qfloat16.h:281
#define qDebug
[1]
Definition qlogging.h:160
#define qWarning
Definition qlogging.h:162
GLint GLsizei GLsizei GLenum format
#define Q_OBJECT
#define Q_SLOTS
double qreal
Definition qtypes.h:92
QFileInfo info(fileName)
[8]