KisSyncedAudioPlayback.cpp 2.13 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
#include "KisSyncedAudioPlayback.h"

#include "config-qtmultimedia.h"

#ifdef HAVE_QT_MULTIMEDIA
#include <QtMultimedia/QMediaPlayer>
#else
class QIODevice;

#include <QUrl>

namespace {

struct QMediaPlayer {
    enum State
    {
        StoppedState,
        PlayingState,
        PausedState
    };

    State state() const { return StoppedState; }

    void play() {}
    void stop() {}

    qint64 position() const { return 0; }
    qreal playbackRate() const { return 1.0; }
    void setPosition(qint64) {}
    void setPlaybackRate(qreal) {}
    void setVolume(int) {}
    void setMedia(const QUrl&, QIODevice * device = 0) { Q_UNUSED(device);}
};
}
#endif



#include <QFileInfo>



struct KisSyncedAudioPlayback::Private
{
    QMediaPlayer player;
    qint64 tolerance = 40;
};


KisSyncedAudioPlayback::KisSyncedAudioPlayback(const QString &fileName)
    : QObject(0),
      m_d(new Private)
{
    QFileInfo fileInfo(fileName);
    Q_ASSERT(fileInfo.exists());

    m_d->player.setMedia(QUrl::fromLocalFile(fileInfo.absoluteFilePath()));
    m_d->player.setVolume(50);
}

KisSyncedAudioPlayback::~KisSyncedAudioPlayback()
{
}

void KisSyncedAudioPlayback::setSoundOffsetTolerance(qint64 value)
{
    m_d->tolerance = value;
}

void KisSyncedAudioPlayback::syncWithVideo(qint64 position)
{
    if (qAbs(position - m_d->player.position()) > m_d->tolerance) {
        m_d->player.setPosition(position);
    }
}

bool KisSyncedAudioPlayback::isPlaying() const
{
    return m_d->player.state() == QMediaPlayer::PlayingState;
}

void KisSyncedAudioPlayback::setSpeed(qreal value)
{
    if (qFuzzyCompare(value, m_d->player.playbackRate())) return;

    if (m_d->player.state() == QMediaPlayer::PlayingState) {
        const qint64 oldPosition = m_d->player.position();

        m_d->player.stop();
        m_d->player.setPlaybackRate(value);
        m_d->player.setPosition(oldPosition);
        m_d->player.play();
    } else {
        m_d->player.setPlaybackRate(value);
    }
}

void KisSyncedAudioPlayback::play(qint64 startPosition)
{
    m_d->player.setPosition(startPosition);
    m_d->player.play();
}

void KisSyncedAudioPlayback::stop()
{
    m_d->player.stop();
}