Pamputt
Pamputt

Reputation: 440

Check if a audio format of a given file is supported in Qt6

There have been many changes in QtMultimedia between Qt5 and Qt6. With QMediaFormat::supportedAudioCodecs, we get a list of QMediaFormat::AudioCodec supported by the system.

Now we should get the QMediaFormat::AudioCodec that is used by a given file.

For that, it seems possible to use QMediaPlayer::metaData but unfortunately, on all the files I tested, the metadata does not contain QMediaFormat::AudioCodec or I don't know how to retrieve this value. In Qt5, it looks QMediaContent was suitable to get media information but it has been removed in Qt6.

Upvotes: 0

Views: 566

Answers (1)

Pamputt
Pamputt

Reputation: 440

There was an issue in Qt that has been fixed in Qt 6.5.0 and the use of FFmpeg.

Here is how I have implemented a verification function:

bool isCodecSupported(QMediaFormat::AudioCodec fileCodec) const
{
    // get supported audio codecs list
    QMediaFormat mediaFormat;
    const QList<QMediaFormat::AudioCodec> supportedAudioCodecs =  mediaFormat.supportedAudioCodecs(QMediaFormat::Decode);

    // check if file codec is supported by the system
    return std::any_of(supportedAudioCodecs.constBegin(), supportedAudioCodecs.constEnd(), [&](QMediaFormat::AudioCodec systemCodec) {
        return fileCodec == systemCodec; });
}

void checkCodec()
{
    const QMediaMetaData fileMetadata = m_mediaPlayer->metaData();
    const QMediaFormat::AudioCodec fileAudioCodec = fileMetadata.value(QMediaMetaData::AudioCodec).value<QMediaFormat::AudioCodec>();
    if(!isCodecSupported(fileAudioCodec)) {
        qWarning() << tr("%1 (%2) is not supported by your system. Please install this codec to be able to play a sound.")
                      .arg(QMediaFormat::audioCodecName(fileAudioCodec),
                           QMediaFormat::audioCodecDescription(fileAudioCodec));
    }
}

m_mediaPlayer = new QMediaPlayer(this); // m_mediaPlayer is defined as a QMediaPlayer* in the header file
connect(m_mediaPlayer, &QMediaPlayer::mediaStatusChanged,
        this, [this](QMediaPlayer::MediaStatus status) {
    if(status == QMediaPlayer::LoadedMedia) {
        checkCodec();
    }
});

m_mediaPlayer->setSource(QUrl("qrc:/audio.wav"));

The codec has to be verified once the file is loaded, otherwise the detection may be incorrect.

Upvotes: 0

Related Questions