File indexing completed on 2024-04-14 03:49:09

0001 /*
0002     SPDX-FileCopyrightText: 2010 Daniel Laidig <d.laidig@gmx.de>
0003     SPDX-License-Identifier: GPL-2.0-or-later
0004 */
0005 
0006 #include "audiobutton.h"
0007 
0008 #include <KLocalizedString>
0009 #include <QAudioOutput>
0010 
0011 using namespace Practice;
0012 
0013 AudioButton::AudioButton(QWidget *parent)
0014     : QToolButton(parent)
0015     , m_player(nullptr)
0016 {
0017     setEnabled(false);
0018     setIcon(QIcon::fromTheme(QStringLiteral("media-playback-start")));
0019     setText(i18n("Play"));
0020     setToolTip(i18n("Play"));
0021     connect(this, &AudioButton::clicked, this, &AudioButton::playAudio);
0022     connect(parent, SIGNAL(stopAudio()), this, SLOT(stopAudio()));
0023 }
0024 
0025 void AudioButton::setSoundFile(const QUrl &soundFile)
0026 {
0027     m_url = soundFile;
0028     setEnabled(!m_url.isEmpty() && m_url.isLocalFile());
0029 }
0030 
0031 void AudioButton::playAudio()
0032 {
0033     if (!m_player) {
0034         m_player = new QMediaPlayer(this);
0035         connect(m_player, &QMediaPlayer::playbackStateChanged, this, &AudioButton::playerStateChanged);
0036         m_player->setAudioOutput(new QAudioOutput);
0037     } else {
0038         if (m_player->playbackState() == QMediaPlayer::PlayingState) {
0039             m_player->stop();
0040         }
0041     }
0042     m_player->setSource(m_url);
0043     m_player->audioOutput()->setVolume(50);
0044     m_player->play();
0045 }
0046 
0047 void AudioButton::stopAudio()
0048 {
0049     if (m_player && m_player->playbackState() == QMediaPlayer::PlayingState) {
0050         m_player->stop();
0051     }
0052 }
0053 
0054 void AudioButton::playerStateChanged(QMediaPlayer::PlaybackState newState)
0055 {
0056     switch (newState) {
0057     case QMediaPlayer::PlayingState:
0058         setIcon(QIcon::fromTheme(QStringLiteral("media-playback-stop")));
0059         setText(i18n("Stop"));
0060         setToolTip(i18n("Stop"));
0061         break;
0062     case QMediaPlayer::StoppedState:
0063     case QMediaPlayer::PausedState:
0064         setIcon(QIcon::fromTheme(QStringLiteral("media-playback-start")));
0065         setToolTip(i18n("Play"));
0066         setText(i18n("Play"));
0067         break;
0068     }
0069 }
0070 
0071 #include "moc_audiobutton.cpp"