实现方法:访问酷狗api接口的到json数据,解析json数据
主要类:
QNetworkAccessManager *managerGetSongInfo;
QNetworkAccessManager* managerImportSong;
QNetworkRequest
QNetworkReply
注:使用需要在pro文件中添加
QT += core gui network multimedia script winextras
废话不多话直接上代码
onlinewget.h
#ifndef ONLINEWGET_H
#define ONLINEWGET_H
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
class OnlineWget :public QWidget
{
Q_OBJECT
public:
explicit OnlineWget(QWidget *parent = 0);
~OnlineWget();
QTableWidget * songTableWidget;
QPushButton * m_pButPlayAllSong;
//QPushButton* m_pButInputSong;
QPushButton* m_pButMoreCtor;
private:
//
struct findResult
{
QString hash;
QString songName;
QString singername;
QString album_name;
QString filesize;
QString playPath;
QString timelength;
QImage image;
QString imagePath;
}stResultList;
signals:
void playAllLocalMusic(QList<findResult>);
void addOneSongInLIst(findResult);
private slots:
void importSongs();
void mainWgetplayAllLocalMusic();
void changeMusicPlayList(int);
void slot_get_song_info (QNetworkReply*);
void slot_import_song(QNetworkReply*);
void on_le_find_returnPressed(QString SearchMesg);
private:
void getMusicInfo(QString filename);
QMap<QString,QString> m_InfoMap;
QString initialName;
QStringList lrcFile ;//本目录下的所有歌词文件
//
void initNetwork();
//
void parseSongInfo(QString json);
void parseSongLink(QString json); //解析Json数据 获取歌曲路径
void addItemsToResultList();
//
QNetworkAccessManager *managerGetSongInfo;
QNetworkAccessManager* managerImportSong;
//
QList<findResult> m_listResult;
//
QStringList findFiles(const QString &startDir, QStringList filters);
};
#endif // ONLINEWGET_H
onlinewget…cpp
#include "onlinewget.h"
OnlineWget::OnlineWget(QWidget *parent):
QWidget(parent)
{
setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
setFixedSize(800,500); //819,527
setAutoFillBackground(true);
songTableWidget = new QTableWidget(0, 5, this);
songTableWidget->setStyleSheet("border-color:white;\
border-style:solid;");
songTableWidget->setAutoFillBackground(true);
QStringList TableHeader;
TableHeader << QStringLiteral("歌曲") << QStringLiteral("歌手")<< QStringLiteral("专辑")<< QStringLiteral("大小");
songTableWidget->setHorizontalHeaderLabels(TableHeader);
songTableWidget->setFixedSize(760, 460);
songTableWidget->move(40, 40);
//songTableWidget->setPalette(QPalette(QColor(120, 214, 255, 255)));
songTableWidget->setShowGrid(false);
songTableWidget->setColumnWidth(0, 300);
songTableWidget->setColumnWidth(1, 160);
songTableWidget->setColumnWidth(2, 160);
songTableWidget->setColumnWidth(3, 100);
songTableWidget->setColumnHidden(4,true);
songTableWidget->setEditTriggers(QTableWidget::NoEditTriggers);
songTableWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
// 设置只能选择单行
songTableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
songTableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);//整行选中
// 设置不显示网格
songTableWidget->setFrameShape(QFrame::NoFrame); //设置无边框
songTableWidget->setShowGrid(false);
connect(songTableWidget, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(changeMusicPlayList(int)));
this->setStyleSheet("QPushButton { \
color:black; \
border-radius:12px;\
border-width:1;\
border-color:black;\
border-style:solid;;\
background-color:rgba(0,0,0,0); \
}\
QPushButton:hover { \
color:red; \
border-radius:12px;\
border-width:1;\
border-color:red;\
border-style:solid;;\
background-color:rgba(0,0,0,0); \
}");
//播放列表设置
//m_musicPlayList = new QMediaPlaylist(this);
// m_musicPlayList->setPlaybackMode(QMediaPlaylist::Loop);
//
QLabel *lab = new QLabel(this);
lab->setText("▋ 在线音乐");
lab->setGeometry(40,10,100,28);
//
m_pButPlayAllSong = new QPushButton(this);
m_pButPlayAllSong->setText("►播放全部");
m_pButPlayAllSong->setGeometry(474,10,92,24);
QObject::connect(m_pButPlayAllSong,SIGNAL(clicked(bool)),this,SLOT(mainWgetplayAllLocalMusic()));
//
// m_pButInputSong = new QPushButton(this);
// m_pButInputSong->setText("导入歌曲");
// m_pButInputSong->setGeometry(576,10,92,24);
// QObject::connect(m_pButInputSong,SIGNAL(clicked(bool)),this,SLOT(importSongs()));
//
m_pButMoreCtor= new QPushButton(this);
m_pButMoreCtor->setText("┄ 更多操作");
m_pButMoreCtor->setGeometry(576,10,92,24);
//网络初始化
initNetwork();
//
// lrcFile= findFiles("./Lyrics", QStringList() << "*.lrc"<<"*krc");
// for(int i=0;i
// {
// qDebug() << lrcFile.at(i);
// }
}
OnlineWget::~OnlineWget()
{
delete songTableWidget;
delete m_pButPlayAllSong;
//delete m_pButInputSong;
delete m_pButMoreCtor;
//delete m_musicPlayList;
delete managerGetSongInfo;
delete managerImportSong;
// delete managerDownloadImage;
}
void OnlineWget::importSongs()
{
for(int i =0; i<m_listResult.length();i++ )
{
QString hash = m_listResult.at(i).hash;
//qDebug() << "hash :" <
//获取歌曲链接
QNetworkRequest request;
request.setUrl(QUrl(QString("http://www.kugou.com/yy/index.php?r=play/getdata&hash=%1").arg(hash)));
// QByteArray byteArray;
request.setHeader(QNetworkRequest::ContentTypeHeader,
"application/x-www-form-urlencoded");
request.setRawHeader("Cookie","kg_mid=1001");
// byteArray.append("hash=" + hash);
// byteArray.append("&r=play/getdata");
//managerPlay->post(request, byteArray);
managerImportSong->get(request);
}
}
void OnlineWget::mainWgetplayAllLocalMusic()
{
emit playAllLocalMusic(m_listResult);
}
void OnlineWget::changeMusicPlayList(int row)
{
if (row >= songTableWidget->rowCount())
return;
emit addOneSongInLIst(m_listResult.at(row));
}
void OnlineWget::slot_get_song_info(QNetworkReply *reply)
{
//无错误返回
if(reply->error() == QNetworkReply::NoError)
{
QByteArray bytes = reply->readAll(); //获取字节
QString result(bytes); //转化为字符串
parseSongInfo(result); //解析Json数据
addItemsToResultList(); //添加结果到搜索列表
}
reply->deleteLater();
importSongs(); //解析歌曲路径到播放列表中
}
void OnlineWget::slot_import_song(QNetworkReply *reply)
{
//无错误返回
if(reply->error() == QNetworkReply::NoError)
{
QByteArray bytes = reply->readAll(); //获取字节
QString result(bytes); //转化为字符串
parseSongLink(result); //解析Json数据 获取歌曲路径
}
reply->deleteLater();
}
void OnlineWget::on_le_find_returnPressed(QString SearchMesg)
{
//清空上一个搜索列表
while (songTableWidget->rowCount())
{
songTableWidget->removeRow(0);
//musicPlayList->removeMedia(0);
}
m_listResult.clear();
//m_listResult.clear();
//获取输入的文本
QString strInput = SearchMesg;
//将文本转换为utf-8编码
QTextCodec *codec = QTextCodec::codecForName("utf-8");
QByteArray byteArrayCodec = codec->fromUnicode(strInput);
QByteArray byteArrayPercentEncoded = byteArrayCodec.toPercentEncoding();
QString strSongName = QString(byteArrayPercentEncoded);
//获取歌曲信息
QNetworkRequest request;
QString strUrl =
QString("http://mobilecdn.kugou.com/api/v3/search/song?keyword=%1")
.arg(strSongName);
request.setUrl(QUrl(strUrl));
managerGetSongInfo->get(request);
}
void OnlineWget::initNetwork()
{
managerGetSongInfo = new QNetworkAccessManager(this);
managerImportSong = new QNetworkAccessManager(this);
//managerStartDownload = new QNetworkAccessManager(this);
//managerGetSongLrc = new QNetworkAccessManager(this);
//managerDownloadSongLrc = new QNetworkAccessManager(this);
connect(managerGetSongInfo, SIGNAL(finished(QNetworkReply*)),
this, SLOT(slot_get_song_info(QNetworkReply*)));
connect(managerImportSong, SIGNAL(finished(QNetworkReply*)),
this, SLOT(slot_import_song(QNetworkReply*)));
}
void OnlineWget::parseSongInfo(QString json)
{
//从字符串数据转换为Json数据
QByteArray byte_array;
QJsonParseError json_error;
QJsonDocument parse_doucment =
QJsonDocument::fromJson(byte_array.append(json), &json_error);
//如果没有错误
if(json_error.error == QJsonParseError::NoError)
{
if(parse_doucment.isObject())
{
QJsonObject object = parse_doucment.object();
if(object.contains("data"))
{
QJsonValue value_data = object.take("data");
if(value_data.isObject())
{
QJsonObject object_data = value_data.toObject();
if(object_data.contains("info"))
{
QJsonValue value_info = object_data.take("info");
if(value_info.isArray())
{
QJsonArray array_info = value_info.toArray();
const int size = array_info.size();
for(int i=0; i<size; ++i)
{
QJsonValue value_first = array_info.at(i);
if(value_first.isObject())
{
QString songname;
QString hash;
QString singername;
QString album_name;
int filesize;
QJsonObject object_first = value_first.toObject();
if(object_first.contains("filename"))
{
QJsonValue value_filename = object_first.take("filename");
songname = value_filename.toString();
}
if(object_first.contains("hash"))
{
QJsonValue value_hash = object_first.take("hash");
hash = value_hash.toString();
}
if(object_first.contains("singername"))
{
QJsonValue value_singername = object_first.take("singername");
singername = value_singername.toString();
}
if(object_first.contains("album_name"))
{
QJsonValue value_album_name = object_first.take("album_name");
album_name = value_album_name.toString();
}
if(object_first.contains("filesize"))
{
QJsonValue value_filesize = object_first.take("filesize");
filesize = value_filesize.toInt();
}
stResultList.songName = songname;
stResultList.hash = hash;
stResultList.singername = singername;
stResultList.album_name =album_name;
stResultList.filesize =QString("%1").arg(filesize/1000);
m_listResult.append(stResultList);
}
}
}
}
}
}
}
}
else
{
qDebug() << "error ... ...";
}
}
void OnlineWget::parseSongLink(QString json)
{
QByteArray byte_array;
QJsonParseError json_error;
QJsonDocument parse_doucment = QJsonDocument::fromJson(byte_array.append(json), &json_error);
if(json_error.error == QJsonParseError::NoError)
{
if(parse_doucment.isObject())
{
QJsonObject rootObj = parse_doucment.object();
if(rootObj.contains("data"))
{
QJsonValue valuedata = rootObj.take("data");
if(valuedata.isObject())
{
QJsonObject object_first = valuedata.toObject();
QString play_url;
int timelength;
QString img;
if(object_first.contains("play_url"))
{
QJsonValue value_filename = object_first.take("play_url");
play_url=value_filename.toString();
//m_musicPlayList->addMedia(QUrl(value_filename.toString()));
//qDebug() <
}
if(object_first.contains("timelength"))
{
QJsonValue value_timelength = object_first.take("timelength");
timelength = value_timelength.toInt();
}
if(object_first.contains("img"))
{
QJsonValue value_img = object_first.take("img");
img = value_img.toString();
}
findResult tmpInfo;
if(object_first.contains("hash"))
{
QJsonValue value_filename = object_first.take("hash");
for(int i=0 ;i<m_listResult.length();i++)
{
if(m_listResult.at(i).hash == value_filename.toString() )
{
int time =timelength/1000;
tmpInfo.songName =m_listResult.at(i).songName;
tmpInfo.singername =m_listResult.at(i).singername;
tmpInfo.hash =m_listResult.at(i).hash;
tmpInfo.playPath = play_url;
tmpInfo.timelength =QString("%1:%2").arg(time/60).arg(time%60,2,10,QChar('0'));
tmpInfo.album_name = m_listResult.at(i).album_name ;
tmpInfo.imagePath =img;
m_listResult.replace(i,tmpInfo);
break;
}
}
}
if(object_first.contains("lyrics"))
{
for(int i=0;i<lrcFile.length();i++)
{
if( lrcFile.at(i) == QString("%1.lrc").arg(tmpInfo.songName))
return;
}
QJsonValue value_lyrics= object_first.take("lyrics");
QByteArray byteArray = value_lyrics.toString().toUtf8();
if(byteArray.size() ==0)
return;
QFile *m_fileLrc = new QFile(this);
m_fileLrc->setFileName(QString("./Lyrics/%1.lrc").arg(tmpInfo.songName));
m_fileLrc->open(QIODevice::WriteOnly);
m_fileLrc->write(QString::fromUtf8(byteArray).toStdString().c_str());
m_fileLrc->close();
m_fileLrc->deleteLater();
m_fileLrc = nullptr;
}
}
}
}
}
}
void OnlineWget::addItemsToResultList()
{
if(!m_listResult.isEmpty())
{
const int tableRow = m_listResult.count();
for(int row=0; row<tableRow; row++)
{
findResult info = m_listResult.at(row);
int rownum = songTableWidget->rowCount();
songTableWidget->insertRow(rownum);
songTableWidget->setItem(rownum, 0, new QTableWidgetItem(info.songName));
songTableWidget->setItem(rownum, 1, new QTableWidgetItem(info.singername));
songTableWidget->setItem(rownum, 2, new QTableWidgetItem(info.album_name));
songTableWidget->setItem(rownum, 3, new QTableWidgetItem(info.filesize));
songTableWidget->setItem(rownum, 4, new QTableWidgetItem(info.hash));
}
}
}
QStringList OnlineWget::findFiles(const QString &startDir, QStringList filters)
{
QStringList names;
QDir dir(startDir);
//搜索当前目录符合条件的文件
foreach (QString file, dir.entryList(filters, QDir::Files))
names += file;
//搜索当前目录的子目录符合条件的文件
foreach (QString subdir, dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot))
names += findFiles(startDir + '/' + subdir, filters);
return names;
}