xref: /OK3568_Linux_fs/app/forlinx/forlinx_qt/musicplayer/musicplayer.cpp (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1 /****************************************************************************
2 **
3 ** Copyright (C) 2015 The Qt Company Ltd.
4 ** Contact: http://www.qt.io/licensing/
5 **
6 ** This file is part of the examples of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** You may use this file under the terms of the BSD license as follows:
10 **
11 ** "Redistribution and use in source and binary forms, with or without
12 ** modification, are permitted provided that the following conditions are
13 ** met:
14 **   * Redistributions of source code must retain the above copyright
15 **     notice, this list of conditions and the following disclaimer.
16 **   * Redistributions in binary form must reproduce the above copyright
17 **     notice, this list of conditions and the following disclaimer in
18 **     the documentation and/or other materials provided with the
19 **     distribution.
20 **   * Neither the name of The Qt Company Ltd nor the names of its
21 **     contributors may be used to endorse or promote products derived
22 **     from this software without specific prior written permission.
23 **
24 **
25 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
36 **
37 ** $QT_END_LICENSE$
38 **
39 ****************************************************************************/
40 
41 #include "musicplayer.h"
42 #include "volumebutton.h"
43 #include <QDebug>
44 #include <QtWidgets>
45 #include <QApplication>
46 #include <QSlider>
47 #include <QPainter>
48 
49 
50 
MusicPlayer(QWidget * parent)51 MusicPlayer::MusicPlayer(QWidget *parent) : QWidget(parent)
52 {
53 	setWindowState(Qt::WindowMaximized);
54     setWindowFlags(Qt::FramelessWindowHint);
55 
56     createWidgets();
57     createShortcuts();
58 
59     connect(&mediaPlayer, &QMediaPlayer::positionChanged, this, &MusicPlayer::updatePosition);
60     connect(&mediaPlayer, &QMediaPlayer::durationChanged, this, &MusicPlayer::updateDuration);
61     connect(&mediaPlayer, &QMediaObject::metaDataAvailableChanged, this, &MusicPlayer::updateInfo);
62 
63     typedef void(QMediaPlayer::*ErrorSignal)(QMediaPlayer::Error);
64     connect(&mediaPlayer, static_cast<ErrorSignal>(&QMediaPlayer::error),
65             this, &MusicPlayer::handleError);
66     connect(&mediaPlayer, &QMediaPlayer::stateChanged,
67             this, &MusicPlayer::updateState);
68 
69     setAcceptDrops(true);
70 }
71 
supportedMimeTypes()72 QStringList MusicPlayer::supportedMimeTypes()
73 {
74     QStringList result = QMediaPlayer::supportedMimeTypes();
75     if (result.isEmpty())
76         result.append(QStringLiteral("audio/mpeg"));
77     return result;
78 }
79 
openFile()80 void MusicPlayer::openFile()
81 {
82     QFileDialog fileDialog(this);
83     fileDialog.setAcceptMode(QFileDialog::AcceptOpen);
84     fileDialog.setWindowTitle(tr("Open File"));
85     fileDialog.setMimeTypeFilters(MusicPlayer::supportedMimeTypes());
86     fileDialog.setDirectory(QStandardPaths::standardLocations(QStandardPaths::MusicLocation).value(0, QDir::homePath()));
87     if (fileDialog.exec() == QDialog::Accepted)
88     {
89          playUrl(fileDialog.selectedUrls().constFirst());
90     }
91 
92 }
93 
playUrl(const QUrl & url)94 void MusicPlayer::playUrl(const QUrl &url)
95 {
96     playButton->setEnabled(true);
97     if (url.isLocalFile()) {
98         const QString filePath = url.toLocalFile();
99         setWindowFilePath(filePath);
100         infoLabel->setText(QDir::toNativeSeparators(filePath));
101         fileName = QFileInfo(filePath).fileName();
102     } else {
103         setWindowFilePath(QString());
104         infoLabel->setText(url.toString());
105         fileName.clear();
106     }
107     mediaPlayer.setMedia(url);
108     mediaPlayer.play();
109 }
110 
togglePlayback()111 void MusicPlayer::togglePlayback()
112 {
113     if (mediaPlayer.mediaStatus() == QMediaPlayer::NoMedia)
114         openFile();
115     else if (mediaPlayer.state() == QMediaPlayer::PlayingState)
116         mediaPlayer.pause();
117     else
118         mediaPlayer.play();
119 }
120 
seekForward()121 void MusicPlayer::seekForward()
122 {
123     positionSlider->triggerAction(QSlider::SliderPageStepAdd);
124 }
125 
seekBackward()126 void MusicPlayer::seekBackward()
127 {
128     positionSlider->triggerAction(QSlider::SliderPageStepSub);
129 }
130 
131 //! [0]
event(QEvent * event)132 bool MusicPlayer::event(QEvent *event)
133 {
134     return QWidget::event(event);
135 }
136 //! [0]
137 
canHandleDrop(const QDropEvent * event)138 static bool canHandleDrop(const QDropEvent *event)
139 {
140     const QList<QUrl> urls = event->mimeData()->urls();
141     if (urls.size() != 1)
142         return false;
143     QMimeDatabase mimeDatabase;
144     return MusicPlayer::supportedMimeTypes().
145         contains(mimeDatabase.mimeTypeForUrl(urls.constFirst()).name());
146 }
147 
dragEnterEvent(QDragEnterEvent * event)148 void MusicPlayer::dragEnterEvent(QDragEnterEvent *event)
149 {
150     event->setAccepted(canHandleDrop(event));
151 }
152 
dropEvent(QDropEvent * event)153 void MusicPlayer::dropEvent(QDropEvent *event)
154 {
155     event->accept();
156    // playUrl(event->mimeData()->urls().constFirst());
157 }
158 
mousePressEvent(QMouseEvent * event)159 void MusicPlayer::mousePressEvent(QMouseEvent *event)
160 {
161     offset = event->globalPos() - pos();
162     event->accept();
163 }
164 
mouseMoveEvent(QMouseEvent * event)165 void MusicPlayer::mouseMoveEvent(QMouseEvent *event)
166 {
167     //move(event->globalPos() - offset);
168     event->accept();
169 }
170 
mouseReleaseEvent(QMouseEvent * event)171 void MusicPlayer::mouseReleaseEvent(QMouseEvent *event)
172 {
173     offset = QPoint();
174     event->accept();
175 }
176 
updateState(QMediaPlayer::State state)177 void MusicPlayer::updateState(QMediaPlayer::State state)
178 {
179     if (state == QMediaPlayer::PlayingState) {
180         playButton->setToolTip(tr("Pause"));
181         playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPause));
182     } else {
183         playButton->setToolTip(tr("Play"));
184         playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
185     }
186 }
187 
formatTime(qint64 timeMilliSeconds)188 static QString formatTime(qint64 timeMilliSeconds)
189 {
190     qint64 seconds = timeMilliSeconds / 1000;
191     const qint64 minutes = seconds / 60;
192     seconds -= minutes * 60;
193     return QStringLiteral("%1:%2")
194         .arg(minutes, 2, 10, QLatin1Char('0'))
195         .arg(seconds, 2, 10, QLatin1Char('0'));
196 }
197 
updatePosition(qint64 position)198 void MusicPlayer::updatePosition(qint64 position)
199 
200 {
201     positionSlider->setValue(position);
202     positionLabel->setText(formatTime(position));
203 }
204 
updateDuration(qint64 duration)205 void MusicPlayer::updateDuration(qint64 duration)
206 {
207     positionSlider->setRange(0, duration);
208     positionSlider->setEnabled(duration > 0);
209     positionSlider->setPageStep(duration / 10);
210     updateInfo();
211 }
212 
213 
setPosition(int position)214 void MusicPlayer::setPosition(int position)
215 {
216     // avoid seeking when the slider value change is triggered from updatePosition()
217     if (qAbs(mediaPlayer.position() - position) > 99)
218     {
219         mediaPlayer.setPosition(position);
220     }
221 }
222 
updateInfo()223 void MusicPlayer::updateInfo()
224 {
225     QStringList info;
226     if (!fileName.isEmpty())
227         info.append(fileName);
228     if (mediaPlayer.isMetaDataAvailable()) {
229         QString author = mediaPlayer.metaData(QStringLiteral("Author")).toString();
230         if (!author.isEmpty())
231             info.append(author);
232         QString title = mediaPlayer.metaData(QStringLiteral("Title")).toString();
233         if (!title.isEmpty())
234             info.append(title);
235     }
236     info.append(formatTime(mediaPlayer.duration()));
237     infoLabel->setText(info.join(tr(" - ")));
238 }
239 
handleError()240 void MusicPlayer::handleError()
241 {
242     playButton->setEnabled(false);
243     const QString errorString = mediaPlayer.errorString();
244     infoLabel->setText(errorString.isEmpty()
245                        ? tr("Unknown error #%1").arg(int(mediaPlayer.error()))
246                        : tr("Error: %1").arg(errorString));
247 }
248 
createWidgets()249 void MusicPlayer::createWidgets()
250 {
251     playButton = new QToolButton(this);
252     playButton->setEnabled(false);
253     playButton->setToolTip(tr("Play"));
254     playButton->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
255     playButton->setFixedSize(55,35);
256     connect(playButton, &QAbstractButton::clicked, this, &MusicPlayer::togglePlayback);
257 
258     QAbstractButton *openButton = new QToolButton(this);
259     openButton->setText(tr("..."));
260     openButton->setToolTip(tr("Open a file..."));
261     openButton->setFixedSize(55,35);
262     connect(openButton, &QAbstractButton::clicked, this, &MusicPlayer::openFile);
263 
264 	QPushButton *exitBtn = new QPushButton(this);
265 	exitBtn->setText(tr("Exit"));
266 	exitBtn->setFixedSize(55,35);
267 	connect(exitBtn, &QPushButton::clicked, this, [=](){
268     close();
269     });
270 
271 
272     volumeButton = new VolumeButton(this);
273     volumeButton->setToolTip(tr("Adjust volume"));
274     volumeButton->setVolume(mediaPlayer.volume());
275     volumeButton->setFixedSize(55,35);
276     connect(volumeButton, &VolumeButton::volumeChanged, &mediaPlayer, &QMediaPlayer::setVolume);
277 
278     positionSlider = new QSlider(Qt::Horizontal, this);
279     positionSlider->setEnabled(false);
280     positionSlider->setToolTip(tr("Seek"));
281     positionSlider->setMaximum(1000000);
282     positionSlider->setMinimum(0);
283     positionSlider->setValue(0);
284     positionSlider->setMinimumWidth(120);
285     connect(positionSlider, &QSlider::valueChanged, this, &MusicPlayer::setPosition);
286 
287     infoLabel = new QLabel(this);
288     QFont font;
289     font.setPointSize(14);
290     infoLabel->setFont(font);
291 
292     positionLabel = new QLabel(tr("00:00"), this);
293     positionLabel->setMinimumWidth(positionLabel->sizeHint().width());
294 
295     QGridLayout *controlLayout = new QGridLayout(this);
296     controlLayout->addWidget(openButton,1,0);
297     controlLayout->addWidget(playButton,1,1);
298     controlLayout->addWidget(positionSlider,1,2);
299     controlLayout->addWidget(positionLabel,1,3);
300     controlLayout->addWidget(volumeButton,1,4);
301 	controlLayout->addWidget(exitBtn, 1, 5);
302     controlLayout->addWidget(infoLabel,0,2);
303     controlLayout->setSpacing(25);
304 
305 }
306 
createShortcuts()307 void MusicPlayer::createShortcuts()
308 {
309     QShortcut *quitShortcut = new QShortcut(QKeySequence::Quit, this);
310     connect(quitShortcut, &QShortcut::activated, QCoreApplication::quit);
311 
312     QShortcut *openShortcut = new QShortcut(QKeySequence::Open, this);
313     connect(openShortcut, &QShortcut::activated, this, &MusicPlayer::openFile);
314 
315     QShortcut *toggleShortcut = new QShortcut(Qt::Key_Space, this);
316     connect(toggleShortcut, &QShortcut::activated, this, &MusicPlayer::togglePlayback);
317 
318     QShortcut *forwardShortcut = new QShortcut(Qt::Key_Right, this);
319     connect(forwardShortcut, &QShortcut::activated, this, &MusicPlayer::seekForward);
320 
321     QShortcut *backwardShortcut = new QShortcut(Qt::Key_Left, this);
322     connect(backwardShortcut, &QShortcut::activated, this, &MusicPlayer::seekBackward);
323 
324     QShortcut *increaseShortcut = new QShortcut(Qt::Key_Up, this);
325     connect(increaseShortcut, &QShortcut::activated, volumeButton, &VolumeButton::increaseVolume);
326 
327     QShortcut *decreaseShortcut = new QShortcut(Qt::Key_Down, this);
328     connect(decreaseShortcut, &QShortcut::activated, volumeButton, &VolumeButton::descreaseVolume);
329 }
330 
331