QT5 音乐播放器基本功能
QT5实现音乐播放器是十分简单的,因为内部已经封装好了 QMediaPlayer 和 QMediaPlaylist。通过QMediaPlaylist加入歌曲,形成歌曲列表,再把列表加入到QMediaPlayer 中去。然后直接通过QMediaPlayer 的函数来实现对音乐的基本操作。QMediaPlayer 还提供了一些信号,比如进度和音量,可以直接获取并做其他操作。
- 创建播放器对象和加入播放列表。
QMediaPlayer *player; //音乐播放器
QMediaPlaylist *playList; //音乐播放列表
playList=new QMediaPlaylist;
playList->setPlaybackMode(QMediaPlaylist::Random);
player=new QMediaPlayer;
player->setPlaylist(playList);
-
添加本地音乐。
connect(ui->pushButton_add, SIGNAL(clicked()), this, SLOT(slot_importLocalSongs()));
void Body::slot_importLocalSongs()
{
QString initialName=QDir::homePath();
QStringList pathList=QFileDialog::getOpenFileNames(this, tr("选择文件"), initialName, tr("*.mp3"));
for(int i=0; i<pathList.size(); ++i) {
QString path=QDir::toNativeSeparators(pathList.at(i));
if(!path.isEmpty()) {
playList->addMedia(QUrl::fromLocalFile(path));
QString fileName=path.split("\").last();
int rownum=ui->tableWidget_music->rowCount();
ui->tableWidget_music->insertRow(rownum);
ui->tableWidget_music->setItem(rownum, 0, new QTableWidgetItem(fileName.split(".").front()));
}
}
} -
播放或暂停音乐。
connect(ui->pushButton_play, SIGNAL(clicked()), this, SLOT(slot_playOrPause()));
void Body::slot_playOrPause()
{
if(ui->pushButton_play->text()==tr(">"))
{
player->play();
ui->pushButton_play->setText(tr("||"));
}
else
{
player->pause();
ui->pushButton_play->setText(tr(">"));
}
} -
播放上一首。
connect(ui->pushButton_pre, SIGNAL(clicked()), this, SLOT(slot_playPrev()));
void Body::slot_playPrev()
{
int currentIndex = playList->currentIndex();
if(--currentIndex<0)
currentIndex = ui->tableWidget_music->rowCount() - 1;
playList->setCurrentIndex(currentIndex);
player->play();//高亮 ui->tableWidget_music->selectRow(currentIndex); ui->tableWidget_music->setFocus(Qt::MouseFocusReason); }
-
播放下一首。
connect(ui->pushButton_next, SIGNAL(clicked()), this, SLOT(slot_playNext()));
void Body::slot_playNext()
{
int currentIndex=playList->currentIndex();
if(++currentIndex==playList->mediaCount())
currentIndex=0;
playList->setCurrentIndex(currentIndex);
player->play();//高亮 ui->tableWidget_music->selectRow(currentIndex); ui->tableWidget_music->setFocus(Qt::MouseFocusReason); }
-
进度条设置
connect(ui->slider_duration, SIGNAL(sliderMoved(int)), this, SLOT(slot_setPosition_duration(int)));
void Body::slot_setPosition_duration(int position)
{
player->setPosition(position);
} -
音量设置
connect(ui->slider_volume, SIGNAL(valueChanged(int)), this, SLOT(slot_setPosition_volume(int)));
void Body::slot_setPosition_volume(int volume)
{
if(flag_slience) //如果是静音的
{
ui->pushButton_silence->setText("off"); //标识设为静音
flag_slience = false; //标识设为非静音
}
player->setVolume(volume); //设置播放器的
ui->slider_volume->setValue(volume);
}