From f332177034cc1ba74242f65e10e6a7c650a915d4 Mon Sep 17 00:00:00 2001 From: Jordan Sherer Date: Tue, 26 Nov 2019 14:23:39 -0500 Subject: [PATCH] Fixed lag in notifications by added a byte stream cache --- NotificationAudio.cpp | 51 ++++++++++++++++++++++++++++++++++++------- NotificationAudio.h | 9 ++++++++ 2 files changed, 52 insertions(+), 8 deletions(-) diff --git a/NotificationAudio.cpp b/NotificationAudio.cpp index b985a8a..24e73eb 100644 --- a/NotificationAudio.cpp +++ b/NotificationAudio.cpp @@ -14,7 +14,13 @@ NotificationAudio::NotificationAudio(QObject *parent): } NotificationAudio::~NotificationAudio(){ + // stop the audio stop(); + + // clean cache + foreach(auto pair, m_cache){ + delete pair.second; + } } void NotificationAudio::status(QString message){ @@ -36,22 +42,51 @@ void NotificationAudio::setDevice(const QAudioDeviceInfo &device, unsigned chann } void NotificationAudio::play(const QString &filePath){ + if(m_cache.contains(filePath)){ + auto pair = m_cache.value(filePath); + auto format = pair.first; + auto bytes = pair.second; + + qDebug() << "notification: playing" << filePath << "with format" << format << "from cache"; + playBytes(format, bytes); + return; + } + if(m_file->isOpen()){ m_file->close(); } m_file->setFileName(filePath); if(m_file->open(BWFFile::ReadOnly)){ - auto format = m_file->format(); - auto channels = format.channelCount(); - auto bytes = m_file->readAll(); - auto buffer = new QBuffer(new QByteArray(bytes)); - if(buffer->open(QIODevice::ReadOnly)){ - m_stream->setDeviceFormat(m_device, format, channels, m_msBuffer); - m_stream->restart(buffer); - } + QAudioFormat format = m_file->format(); + QByteArray *bytes = new QByteArray(m_file->readAll()); + + qDebug() << "notification: playing" << filePath << "with format" << format << "from disk"; + playBytes(format, bytes); + + // cache the buffer + m_cache.insert(filePath, {format, bytes}); } } +void NotificationAudio::playBytes(const QAudioFormat &format, QByteArray *bytes){ + if(bytes == nullptr){ + return; + } + + if(m_buffer.isOpen()){ + m_buffer.close(); + } + + m_buffer.setBuffer(bytes); + + if(!m_buffer.open(QIODevice::ReadOnly)){ + return; + } + + m_stream->setDeviceFormat(m_device, format, format.channelCount(), m_msBuffer); + m_stream->restart(&m_buffer); +} + void NotificationAudio::stop(){ m_stream->stop(); diff --git a/NotificationAudio.h b/NotificationAudio.h index 921e04b..783024d 100644 --- a/NotificationAudio.h +++ b/NotificationAudio.h @@ -7,7 +7,11 @@ #include #include #include +#include #include +#include +#include +#include #include "AudioDevice.hpp" #include "AudioDecoder.h" @@ -32,10 +36,15 @@ public slots: void stop(); private: + void playBytes(const QAudioFormat &format, QByteArray *bytes); + +private: + QMap> m_cache; QPointer m_stream; QPointer m_decoder; QPointer m_file; QAudioDeviceInfo m_device; + QBuffer m_buffer; unsigned m_channels; unsigned m_msBuffer; };