c++qtqmediaplayer

QMediaPlayer::position() return zero


I was trying to get position of current media like that:

player->setNotifyInterval(500);

connect(Player::player, &QMediaPlayer::positionChanged, this, &Player::ChangedPosition);

void Player::ChangedPosition(qint64 position)
{
    Player::currentPosition = position; //qint64 variable
    //currentPosition still 0

    qDebug() << "current position: " << currentPosition;

    return;
}

I was trying to make like that (because doc of Qt does not say about this slot QMediaPlayer::setPosition)

connect(Player::player, &QMediaPlayer::positionChanged, this, &QMediaPlayer::setPosition);

I have two class (Playlist and Player):

playlistmanager - object of Playlist class

playermanager - object of Player class

set playlist and play it:

//set current media
playlistmanager->GetCurrentPlayList()->setCurrentIndex(newIndex);
//play this media
playermanager->play();
//set current position
playermanager->SetPositionOfTrack(playermanager->GetPositionOfTrack());

After this code media is playing but from the beginning

Here two methods of Player class:

qint64 Player::GetPositionOfTrack()
{
    return currentPosition; //qint64 variable in class
}

void Player::SetPositionOfTrack(const qint64 position)
{
    player->setPosition(position);

    return;
}

So, How can I get current position of current media?


Solution

  • need to use this pointer if I create object like that: player = new QMediaPlayer(this);. Wrong example:

    connect(Player::player, &QMediaPlayer::positionChanged, this, &QMediaPlayer::setPosition);
    

    Constructor of the correct class:

        Player::Player()
        {
            try
            {
                player = new QMediaPlayer(this);
            }
            catch(std::bad_alloc &exp)
            {
                #ifndef Q_DEBUG
                qCritical() << "Exception caught: " << exp.std::bad_alloc::what();
                #endif
                abort();
            }
            catch(...)
            {
                #ifndef Q_DEBUG
                qCritical() << "Some exception caught";
                #endif
                abort();
            }
        
            player->setNotifyInterval(500);
            
            connect(this, &QMediaPlayer::positionChanged, this, &Player::ChangedPosition);
        
            return;
        }