基于qt和sqlite3实现的音乐播放器,接近1000行代码带有详细注释,这里提供主要代码实现,需要全部代码和项目可以评论区@我+V
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
//禁止窗口改变尺寸大小
this->setFixedSize(this->geometry().size());
//去掉标题栏
this->setWindowFlag(Qt::FramelessWindowHint);
//1.判断数据库连接是否存在,存在就得到连接,如果不存在就添加得到链接
if(QSqlDatabase::contains("sql_default_connection"))
{
//根据数据库默认连接名称得到连接
db=QSqlDatabase::database("sql_default_connection");
}
else
{
//添加数据库,得到该数据库的默认连接
db=QSqlDatabase::addDatabase("QSQLITE");
//设置数据库文件名称
db.setDatabaseName("mp3listdatabase.db");
}
//2.打开数据库,打开标识(QSqlQuery类)
if(!db.open())
{
QMessageBox::critical(0,QObject::tr("Open Data Error."),db.lastError().text());
}
else
{
//3.定义query对象,得到打开的数据库标识
QSqlQuery query;
QString sql="create table if not exists searchlist(id integer,songname text,singername text,album_id text,hash text)";
if(!query.exec(sql))
{
QMessageBox::critical(0,QObject::tr("create searchlist Error."),db.lastError().text());
}
//歌曲痕迹数据表
sql="create table if not exists historysong(id integer primary key autoincrement,songname text,singername text,album_id text,hash text)";
if(!query.exec(sql))
{
QMessageBox::critical(0,QObject::tr("create historysong Error."),db.lastError().text());
}
//查询历史数据表中的插入歌曲数据
sql="select * from historysong;";
if(!query.exec(sql))
{
QMessageBox::critical(0,QObject::tr("select historysong Error."),db.lastError().text());
}
while(query.next())
{
QString songname,singername;
QSqlRecord rec=query.record();
int ablumkey=rec.indexOf("songname");
int hashkey=rec.indexOf("singername");
songname=query.value(ablumkey).toString();
singername=query.value(hashkey).toString();
//拼接歌曲名字和歌手名字
QString strshow=songname+"--"+singername;
//显示到列表中
QListWidgetItem *item=new QListWidgetItem(strshow);
ui->listWidget_History->addItem(item);
}
}
//播放操作
player=new QMediaPlayer;
playerlist=new QMediaPlaylist;
//播放就更新播放的进度条和显示的时间
connect(player,SIGNAL(positionChanged(qint64)),this,SLOT(updateDuration(qint64)));
//播放就显示歌词
connect(this,SIGNAL(lyricShow(QString)),this,SLOT(lyricTextShow(QString)));
//搜索的歌曲列表中,双击播放
connect(ui->listWidget_Search,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(playSearchMusic()));
//历史的歌曲列表中,双击播放
connect(ui->listWidget_History,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(playHistoryMusic()));
num=0;
//更换软件皮肤的菜单项
QAction *actionbackgroundtoDefault=new QAction(QIcon(""),u8"Default");
connect(actionbackgroundtoDefault,&QAction::triggered,this,&Widget::backgroundtoDefault);
QAction *actionbackgroundtoSetting=new QAction(QIcon(""),u8"Custom");
connect(actionbackgroundtoSetting,&QAction::triggered,this,&Widget::backgroundtoSetting);
menuchangeSkin=new QMenu(this);
menuchangeSkin->addAction(actionbackgroundtoDefault);
menuchangeSkin->addAction(actionbackgroundtoSetting);
backgroundtoDefault();//更换到默认背景皮肤
//系统托盘初始化
initsystemtrayIcon();
}
void Widget::paintEvent(QPaintEvent *event)
{
//QPainter painter(this);
//painter.drawPixmap(0,0,width(),height(),QPixmap(":/new/prefix1/1.png"));
}
//搜索音乐
void Widget::on_pushButton_Search_clicked()
{
//将原有的歌曲数据清空
ui->listWidget_Search->clear();
//先清理数据库中已经存储的hash等数据
QSqlQuery query;
QString sql="delete from searchlist;";
if(!query.exec(sql))
{
QMessageBox::critical(0,QObject::tr("Delete searchlist Error."),db.lastError().text());
}
//用户输入的音乐MP3音乐的名称,发起请求操作
//这里是向酷狗音乐的音乐库发起请求
QString url=kugouSearchApi+QString("format=json&keyword=%1&page=1&pagesize=20&showtype=1").arg(ui->lineEdit_Search->text());
//请求http协议
httpAccess(url);
QByteArray JsonData;
QEventLoop loop;
auto c=connect(this,finish,[&](const QByteArray &data)
{
JsonData=data;
loop.exit();
});
//执行
loop.exec();
disconnect(c);
//解析网页回复的数据,将搜索得到的音乐hash和album_id与列表的索引值存放到数据库
hashJsonAnalysis(JsonData);
}
//循环播放
//点击后连接信号和槽,监听歌曲的状态-》到末尾时触发槽函数循环播放,循环播放同一首歌曲
void Widget::on_pushButton_Loopplay_clicked()
{
connect(player,SIGNAL(stateChanged(QMediaPlayer::State)),this,SLOT(loopPlayMusic(QMediaPlayer::State)));
}
//读取网络数据的槽函数
void Widget::netReply(QNetworkReply * reply)
{
//获取响应的信息,状态码为200属于正常
QVariant status_code=reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
qDebug()<<status_code;
reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
//没有错误,返回
if(reply->error()==QNetworkReply::NoError)
{
QByteArray data=reply->readAll();
emit finish(data);
}
else
{
qDebug()<<reply->errorString();
}
reply->deleteLater();
}
//音乐歌曲下载和播放
void Widget::downloadPlayer(QString album_id,QString hash)
{
QString url=kugouDownloadApi + QString("r=play/getdata"
"&hash=%1&album_id=%2"
"&dfid=1spkkh3QKS9P0iJupz0oTy5G"
"&mid=de94e92794f31e9cd6ff4cb309d2baa2"
"&platid=4").arg(hash).arg(album_id);
httpAccess(url);
QByteArray JsonData;
QEventLoop loop;
auto d=connect(this,finish,[&](const QByteArray &data)
{
JsonData=data;
loop.exit(1);
});
//执行
loop.exec();
disconnect(d);
//解析将要播放的音乐
QString music=musicJsonAnalysis(JsonData);
player->setMedia(QUrl(music));
//设置音量
player->setVolume(100);
//设置音量的滑动条
ui->VopSlider->setValue(100);
//播放音乐
player->play();
}
//访问HTTP网页
void Widget::httpAccess(QString url)
{
//实例化网络请求操作事项
request=new QNetworkRequest;
//将url网页地址存入request请求当中
request->setUrl(url);
//实例化网络管理(访问)
manager=new QNetworkAccessManager;
//通过get方法,上传具体的请求
manager->get(*request);
//当网页回复消息时,触发finished信号,我们才能够读取数据信息
connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(netReply(QNetworkReply*)));
}
//音乐解析,使用JSON
void Widget::hashJsonAnalysis(QByteArray JsonData)
{
QJsonDocument document=QJsonDocument::fromJson(JsonData);
//判断是否为对象
if(document.isObject())
{
QJsonObject data=document.object();
if(data.contains("data"))
{
QJsonObject objectInfo=data.value("data").toObject();
//判断信息
if(objectInfo.contains("info"))
{
QJsonArray objectHash=objectInfo.value("info").toArray();
for(int i=0;i<objectHash.count();i++)
{
QString songname,singername,album_id,hash;
QJsonObject album=objectHash.at(i).toObject();
if(album.contains("album_id"))
{
album_id=album.value("album_id").toString();
}
if(album.contains("singername"))
{
singername=album.value("singername").toString();
}
if(album.contains("songname"))
{
songname=album.value("songname").toString();
}
if(album.contains("hash"))
{
hash=album.value("hash").toString();
}
QSqlQuery query;
QString sql=QString("insert into searchlist values(%1,'%2','%3','%4','%5')").arg(QString::number(i)).arg(songname).arg(singername).arg(album_id).arg(hash);
if(!query.exec(sql))
{
QMessageBox::critical(0,QObject::tr("insert searchlist Error."),db.lastError().text());
}
//将解析的音乐名称,存入到listWidget_Search控件列表进行显示
QString show=songname+"--"+singername;
QListWidgetItem *item=new QListWidgetItem(show);
ui->listWidget_Search->addItem(item);
}
}
}
}
if(document.isArray())
{
qDebug()<<"Array";
}
}
//搜索的音乐数据信息JSON解析,解析出真正的音乐文件个歌词
QString Widget::musicJsonAnalysis(QByteArray JsonData)
{
QJsonDocument document=QJsonDocument::fromJson(JsonData);
if(document.isObject())
{
QJsonObject data=document.object();
if(data.contains("data"))
{
QJsonObject objectPlayUrl=data.value("data").toObject();
if(objectPlayUrl.contains("lyrics"))
{
emit lyricShow(objectPlayUrl.value("lyrics").toString());
}
if(objectPlayUrl.contains("play_url"))
{
return objectPlayUrl.value("play_url").toString();
}
}
if(document.isArray())
{
qDebug()<<"Array.";
}
}
}
//双击搜索列表,播放音乐
void Widget::playSearchMusic()
{
//获取双击的歌曲对应的索引,数据库当中的ID号
int row=ui->listWidget_Search->currentRow();
qDebug()<<"row-->"<<row;
//查询搜索数据库中的数据库表中存储的音乐的数据信息
QSqlQuery query;
QString sql=QString("select * from searchlist where id=%1;").arg(row);
if(!query.exec(sql))
{
QMessageBox::critical(0,QObject::tr("select searchlist table Error."),db.lastError().text());
}
//将选中的音乐的数据信息存入历史数据表
QString songname,singername,album_id,hash;
while(query.next())
{
QSqlRecord recd=query.record();
int songkey=recd.indexOf("songname");
int singerkey=recd.indexOf("singername");
int ablumkey=recd.indexOf("album_id");
int hashkey=recd.indexOf("hash");
songname=query.value(songkey).toString();
singername=query.value(singerkey).toString();
album_id=query.value(ablumkey).toString();
hash=query.value(hashkey).toString();
sql=QString("select hash from historysong where hash='%1';").arg(hash);
if(!query.exec(sql))
{
QMessageBox::critical(0,QObject::tr("select hash Error."),db.lastError().text());
}
if(query.next()==NULL)
{
sql=QString("insert into historysong values(NULL,'%1','%2','%3','%4')").arg(songname).arg(singername).arg(album_id).arg(hash);
if(!query.exec(sql))
{
QMessageBox::critical(0,QObject::tr("insert historysong Error."),db.lastError().text());
}
//将解析的音乐名称,保存listWidget_History列表控件当中
QString show=songname+"--"+singername;
QListWidgetItem *item=new QListWidgetItem(show);
ui->listWidget_History->addItem(item);
}
}
//播放
downloadPlayer(album_id,hash);
}