Skip to content

Commit d9ab947

Browse files
committed
fix: Fixes a crash when no audio device is connected
1 parent 87528d9 commit d9ab947

2 files changed

Lines changed: 59 additions & 1 deletion

File tree

src/core/afv/audio/input.cpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,21 @@ namespace swift::core::afv::audio
9696
inputFormat.setSampleFormat(QAudioFormat::Int16);
9797

9898
QAudioDevice selectedDevice = getLowestLatencyDevice(inputDevice, inputFormat);
99+
100+
if (selectedDevice.isNull())
101+
{
102+
CLogMessage(this).error(u"No suitable audio input device found for '%1'. Required format: %2")
103+
<< inputDevice.getName() << toQString(inputFormat);
104+
return;
105+
}
106+
107+
if (!selectedDevice.isFormatSupported(inputFormat))
108+
{
109+
CLogMessage(this).error(u"Selected device '%1' does not support required format: %2")
110+
<< selectedDevice.description() << toQString(inputFormat);
111+
return;
112+
}
113+
99114
m_inputFormat = inputFormat;
100115
m_audioInput.reset(new QAudioSource(selectedDevice, m_inputFormat));
101116
if (!m_audioInputBuffer) { m_audioInputBuffer = new CAudioInputBuffer(this); }

src/sound/audioutilities.cpp

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,50 @@ namespace swift::sound
7373
{
7474
const QAudioDevice defDevice =
7575
device.isInputDevice() ? QMediaDevices::defaultAudioInput() : QMediaDevices::defaultAudioOutput();
76-
Q_ASSERT_X(defDevice.isFormatSupported(format), Q_FUNC_INFO, "Device does not support format");
76+
77+
if (defDevice.isNull())
78+
{
79+
// No default device available
80+
return {};
81+
}
82+
83+
if (!defDevice.isFormatSupported(format))
84+
{
85+
// Try to find a supported format
86+
QAudioFormat adjustedFormat = defDevice.preferredFormat();
87+
88+
// Try to keep as many original settings as possible
89+
adjustedFormat.setSampleRate(format.sampleRate());
90+
adjustedFormat.setChannelCount(format.channelCount());
91+
adjustedFormat.setSampleFormat(format.sampleFormat());
92+
93+
if (defDevice.isFormatSupported(adjustedFormat))
94+
{
95+
format = adjustedFormat;
96+
return defDevice;
97+
}
98+
99+
// Fallback: Try with preferred format's sample rate but keep other settings
100+
adjustedFormat = defDevice.preferredFormat();
101+
adjustedFormat.setChannelCount(format.channelCount());
102+
adjustedFormat.setSampleFormat(format.sampleFormat());
103+
104+
if (defDevice.isFormatSupported(adjustedFormat))
105+
{
106+
format = adjustedFormat;
107+
return defDevice;
108+
}
109+
110+
// Last resort: Use the device's preferred format entirely
111+
if (defDevice.isFormatSupported(defDevice.preferredFormat()))
112+
{
113+
format = defDevice.preferredFormat();
114+
return defDevice;
115+
}
116+
117+
// Device doesn't support any reasonable format
118+
return {};
119+
}
77120
return defDevice;
78121
}
79122

0 commit comments

Comments
 (0)