File indexing completed on 2024-11-17 05:15:20

0001 /*
0002  * Copyright 2020 Han Young <hanyoung@protonmail.com>
0003  * Copyright 2020-2021 Devin Lin <devin@kde.org>
0004  *
0005  * SPDX-License-Identifier: GPL-2.0-or-later
0006  */
0007 
0008 #include "alarmplayer.h"
0009 
0010 #include <QDateTime>
0011 #include <QFile>
0012 #include <QStandardPaths>
0013 
0014 AlarmPlayer &AlarmPlayer::instance()
0015 {
0016     static AlarmPlayer singleton;
0017     return singleton;
0018 }
0019 
0020 AlarmPlayer::AlarmPlayer(QObject *parent)
0021     : QObject{parent}
0022     , m_player(new QMediaPlayer(this))
0023     , m_audio(new QAudioOutput)
0024 {
0025     m_player->setAudioOutput(m_audio);
0026     connect(m_player, &QMediaPlayer::playbackStateChanged, this, &AlarmPlayer::loopAudio);
0027 }
0028 
0029 void AlarmPlayer::loopAudio(QMediaPlayer::PlaybackState state)
0030 {
0031     if (!userStop
0032         && state == QMediaPlayer::StoppedState /* && static_cast<int>(QDateTime::currentSecsSinceEpoch() - startPlayingTime) < settings.alarmSilenceAfter()*/) {
0033         m_player->play();
0034     }
0035 }
0036 
0037 void AlarmPlayer::play()
0038 {
0039     if (m_player->playbackState() == QMediaPlayer::PlayingState) {
0040         return;
0041     }
0042 
0043     startPlayingTime = QDateTime::currentSecsSinceEpoch();
0044     userStop = false;
0045     m_player->play();
0046 }
0047 
0048 void AlarmPlayer::stop()
0049 {
0050     userStop = true;
0051     m_player->stop();
0052 }
0053 
0054 int AlarmPlayer::volume()
0055 {
0056     return m_audio->volume() * 100;
0057 }
0058 
0059 void AlarmPlayer::setVolume(int volume)
0060 {
0061     m_audio->setVolume(static_cast<float>(volume) / 100);
0062     Q_EMIT volumeChanged();
0063 }
0064 
0065 void AlarmPlayer::setSource(const QUrl &path)
0066 {
0067     // if user set a invalid audio path or doesn't even specified a path, resort to default
0068     if (!path.isValid() || !QFile::exists(path.toLocalFile())) {
0069         const QUrl url = QUrl::fromLocalFile(
0070             QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("sounds/freedesktop/stereo/alarm-clock-elapsed.oga")));
0071         m_player->setSource(url);
0072     } else {
0073         m_player->setSource(path);
0074     }
0075 }