All Classes Namespaces Functions Variables Enumerations Properties Pages
soundplayer.cpp
1 /*
2 
3 Pencil2D - Traditional Animation Software
4 Copyright (C) 2012-2020 Matthew Chiawen Chang
5 
6 This program is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; version 2 of the License.
9 
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14 
15 */
16 
17 #include "soundplayer.h"
18 #include <QMediaPlayer>
19 #include <QFile>
20 #include "soundclip.h"
21 
22 SoundPlayer::SoundPlayer()
23 {
24 }
25 
26 SoundPlayer::~SoundPlayer()
27 {
28 }
29 
30 void SoundPlayer::init(SoundClip* clip)
31 {
32  Q_ASSERT(clip != nullptr);
33  mSoundClip = clip;
34 
35  mMediaPlayer = new QMediaPlayer(this);
36 
37  QFile file(clip->fileName());
39 
40  mBuffer.setData(file.readAll());
41  mBuffer.open(QBuffer::ReadOnly);
42 
43  mMediaPlayer->setMedia(QUrl::fromLocalFile(clip->fileName()), &mBuffer);
44  makeConnections();
45 
46  clip->attachPlayer(this);
47 }
48 
49 void SoundPlayer::onKeyFrameDestroy(KeyFrame* keyFrame)
50 {
51  Q_UNUSED(keyFrame)
52 }
53 
54 bool SoundPlayer::isValid()
55 {
56  if (mMediaPlayer)
57  {
58  return (mMediaPlayer->error() == QMediaPlayer::NoError);
59  }
60  return false;
61 }
62 
63 void SoundPlayer::play()
64 {
65  if (mMediaPlayer)
66  {
67  mMediaPlayer->play();
68  }
69 }
70 
71 void SoundPlayer::pause()
72 {
73  if (mMediaPlayer)
74  {
75  mMediaPlayer->pause();
76  }
77 }
78 
79 void SoundPlayer::stop()
80 {
81  if (mMediaPlayer)
82  {
83  mMediaPlayer->stop();
84  }
85 }
86 
87 int64_t SoundPlayer::duration()
88 {
89  if (mMediaPlayer)
90  {
91  return mMediaPlayer->duration();
92  }
93  return 0;
94 }
95 
96 void SoundPlayer::setMediaPlayerPosition(qint64 pos)
97 {
98  if (mMediaPlayer)
99  {
100  mMediaPlayer->setPosition(pos);
101  }
102 }
103 
104 void SoundPlayer::makeConnections()
105 {
106  auto errorSignal = static_cast<void (QMediaPlayer::*)(QMediaPlayer::Error)>(&QMediaPlayer::error);
107  connect(mMediaPlayer, errorSignal, this, [](QMediaPlayer::Error err)
108  {
109  qDebug() << "MediaPlayer Error: " << err;
110  });
111 
112  connect(mMediaPlayer, &QMediaPlayer::durationChanged, [this](qint64 duration)
113  {
114  qDebug() << "MediaPlayer durationChanged :" << duration;
115  emit durationChanged(this, duration);
116  });
117 }
void setData(const QByteArray &data)
virtual bool open(QIODevice::OpenMode flags) override
virtual bool open(QIODevice::OpenMode mode) override
QMetaObject::Connection connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type)
QUrl fromLocalFile(const QString &localFile)