qt phonon 制作音乐播放器学习(怎样让播放进度条和音乐播放时长同步)

在播放媒体文件时,媒体对象MediaObject 会在指定的时间间隔发射tick(qint64  time)信号, 这个时间间隔可以使用setTickInterval()来进行设置,tick()中的time参数指定了媒体对象在媒体流中的当前位置,单位是毫秒。

实现代码如下:

构造函数中:

    // 创建媒体图
    mediaObject = new Phonon::MediaObject(this);
    Phonon::AudioOutput *audioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);
    Phonon::createPath(mediaObject, audioOutput);
 
  
    // 关联媒体对象的tick()信号来更新播放时间的显示
    connect(mediaObject, SIGNAL(tick(qint64)), this, SLOT(updateTime(qint64)));
 
  
    // 创建控制播放进度的滑块
    Phonon::SeekSlider *seekSlider = new Phonon::SeekSlider(mediaObject, this);
 
  
 
  
    // 显示播放时间的标签
    timeLabel = new QLabel(tr("00:00 / 00:00"), this);
    timeLabel->setToolTip(tr("当前时间 / 总时间"));
    timeLabel->setAlignment(Qt::AlignCenter);
    timeLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

   
   mediaObject->setCurrentSource(Phonon::MediaSource("../myPlayer/music.mp3"));


// 更新timeLabel标签显示的播放时间
void MyWidget::updateTime(qint64 time)
{
    qint64 totalTimeValue = mediaObject->totalTime();
    QTime totalTime(0, (totalTimeValue / 60000) % 60, (totalTimeValue / 1000) % 60);
    QTime currentTime(0, (time / 60000) % 60, (time / 1000) % 60);
    QString str = currentTime.toString("mm:ss") + " / " + totalTime.toString("mm:ss");
    timeLabel->setText(str);
}

你可能感兴趣的:(QT开发)