QMediaPlayer::position() return 零

QMediaPlayer::position() return zero

我试图像这样获取当前媒体的位置:

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;
}

我正试图那样做(因为 Qt 的文档 没有说明这个插槽 QMediaPlayer::setPosition

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

我有两个 class(PlaylistPlayer):

playlistmanager - Playlist class

的对象

playermanager - Player class

的对象

设置播放列表并播放:

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

在此代码之后媒体正在播放但从头开始

这里有两种方法 Player class:

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

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

    return;
}

那么,如何获得当前媒体当前位置

如果我创建这样的对象,则需要使用 this 指针:player = new QMediaPlayer(this);。错误示例:

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

正确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;
    }