C# · 12月 21, 2021

QT5:C++实现基于multimedia的音乐播放器(二)

今天接着上一篇来实现播放器的槽函数。

先来实现播放模式,槽函数如下:

(z== playPattern->setStyleSheet( playPattern->setToolTip(tr( playList-> z = (z== playPattern->setStyleSheet( playPattern->setToolTip(tr( playList-> z– playPattern->setStyleSheet( playPattern->setToolTip(tr( playList-> z– }

里面的 Z 是一个静态变量(static),要在music.cpp里进行赋初值:

Music::z = ;

我在播放器界面上创建了一个切换播放模式的按钮,用鼠标点击按钮时,会切换播放模式且按钮背景更换为相应的播放模式图片,Z 的值也会变化,以此让下一次点击按钮时能进行判断该更换哪种播放模式和按钮背景图片。

然后是添加歌曲的槽函数:

QStringList fileNames = QFileDialog::getOpenFileNames(,tr(),,tr( (! add = ( i = ; i addMedia(QUrl::fromLocalFile(fileNames.at(i))); songFileName = info = songName = list ->addItem(songName); message -> setText(tr( playList->setCurrentIndex( (z == playList-> (z == playList-> playList-> player -> BtnPlay->setStyleSheet( connect(timer2,SIGNAL(timeout()),,SLOT(clearMessage())); timer2 ->start( message -> setText( }

在添加歌曲时根据 Z 值设置播放模式是为了解决在没添加歌曲时点击了切换播放模式按钮,导致在添加歌曲后出现按钮背景图片与当前播放模式不一致的问题。

添加完歌曲当然是播放啦,下面是播放按钮和上、下首歌曲的槽函数:

(! QMessage@R_768_2419@::information(,,, (player -> state() == QMediaPlayer::PlayingState) player -> timer -> BtnPlay->setStyleSheet( player -> connect(timer, timer->start( BtnPlay->setStyleSheet( moved = playList -> moved = playList-> }

在上一篇的music的构造函数中(Music::Music(QWidget *parent) : QWidget(parent){ }),设置了add的初始值为false:

-> add = ; moved = timer = QTimer();

然后在添加歌曲的槽函数里进行了判断,如果添加歌曲成功,则add的值变为true:

(! add = ; }

当鼠标点击播放歌曲按钮时,add的值会被用来进行判断播放器有没有添加歌曲,如果值为flase,则弹框提醒还没有添加歌曲,值为true的话,就播放歌曲:

(! QMessage@R_768_2419@::information(, }

调节音量的实现就比较简单了,QT自带了函数:

Music::volumChange( player -> }

静音的槽函数还是要我们自己写的,因为要更换喇叭(静音开关图标)的背景图片:

flag=; muteButton->setStyleSheet( muteButton->setToolTip(tr( player -> setMuted( } muteButton->setStyleSheet( muteButton->setToolTip(tr( player -> setMuted( flag=! }

显示音量进度的滑动条以及音乐已播放时长的实现是我在写这个音乐播放器时花时间比较久的一个地方:

seekSlider->setMaximum(player->duration() / ); seekSlider->setValue(position / ); moved = position; QTime moveTime(,(moved/) % ,(moved / ) % ); showPro ->setText(moveTime.toString()); Music::seekChange( player -> setPosition(position * ); moved = position * ; QTime moveTime(,(moved / ) % ); showPro ->setText(moveTime.toString()); (moved >= player -> moved = Music::showMessage( QString name= player-> QString author= player-> showMge -> setText(+name + + QTime displayTime(,(player -> duration() / ) % ,(player ->duration() / ) % showTime -> setText(displayTime.toString( }

音乐播放器就这样实现完毕了,如果你觉得太简陋的话,可以重写鼠标右键函数来添加选取某一歌曲播放、删除某一歌曲、删除全部歌曲等等功能,还可以添加歌词显示的功能。