QT-在线音乐播放

QT之在线音乐播放简易版本

  • 1、效果预览查看
  • 2、歌名搜索
  • 3、音乐本地下载
  • 4、音乐播放与暂停
  • 5、音乐播放进度条
  • 6、本次实例全部代码链接

1、效果预览查看

QT-在线音乐播放_第1张图片

2、歌名搜索

通过使用外部提供的HTTP访问搜索的方式,这里我们用的是网易云的接口,查询获取歌名和相关内容,这里根据显示,我们解析数据的显示的列表有标题,作者、专辑和时长,查询获取的部分代码内容如下:

	QString strSongName = ui.lineEditSearch->text();
	if (strSongName.trimmed().isEmpty())
		return;
// 接口
	QString url = "http://iwxyi.com:3000/search?keywords=" + strSongName.toUtf8().toPercentEncoding();
	QNetworkAccessManager* manager = new QNetworkAccessManager;
	QNetworkRequest* request = new QNetworkRequest(url);

	request->setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded; charset=UTF-8");
	request->setHeader(QNetworkRequest::UserAgentHeader, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36");
	
	// 获取查询的接口返回
	connect(manager, &QNetworkAccessManager::finished, this, [=](QNetworkReply* reply)
	{
		QByteArray data = reply->readAll();
		QJsonParseError error;
		QJsonDocument document = QJsonDocument::fromJson(data, &error);
		if (error.error != QJsonParseError::NoError)
		{
			qDebug() << error.errorString();
			return;
		}

		QJsonObject json = document.object();
		if (json.value("code").toInt() != 200)
		{
			qDebug() << json.value("message").toString();
			return;
		}

		QJsonArray musics = json.value("result").toObject().value("songs").toArray();


		searchResultSongs.clear();
		foreach(QJsonValue val, musics)
			searchResultSongs << Music::fromJson(val.toObject());
			
		// 设置界面显示	
		setSearchResultTable(searchResultSongs);
	});
	manager->get(*request);

3、音乐本地下载

同样的方式,我们通过加载回来的信息数据去下载相应的歌曲,然后保存到本地,接着使用QT的QMediaPlayer类去执行音乐文件的播放即可,关于音乐下载的部分代码如下贴出:

void QtMusic::downloadSong(Music music)
{
	downloadingSong = music;
	QString url = API_DOMAIN + "/song/url?id=" + snum(music.id);
	qDebug() << QString::fromLocal8Bit("获取歌曲信息:") << music.simpleString();
	QNetworkAccessManager* manager = new QNetworkAccessManager;
	QNetworkRequest* request = new QNetworkRequest(url);
	request->setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded; charset=UTF-8");
	request->setHeader(QNetworkRequest::UserAgentHeader, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36");
	connect(manager, &QNetworkAccessManager::finished, this, [=](QNetworkReply* reply)
	{
		QByteArray baData = reply->readAll();
		QJsonParseError error;
		QJsonDocument document = QJsonDocument::fromJson(baData, &error);
		if (error.error != QJsonParseError::NoError)
		{
			qDebug() << error.errorString();
			return;
		}
		QJsonObject json = document.object();
		if (json.value("code").toInt() != 200)
		{
			qDebug() << QString::fromLocal8Bit("返回结果不为200:") << json.value("message").toString();
			return;
		}
		QJsonArray array = json.value("data").toArray();
		if (!array.size())
		{
			qDebug() << QString::fromLocal8Bit("未找到歌曲:") << music.simpleString();
			downloadingSong = Music();  // 清空
			downloadNext();
			return;
		}

		json = array.first().toObject();
		QString url = JVAL_STR(url);
		int br = JVAL_INT(br); // 比率320000
		int size = JVAL_INT(size);
		QString type = JVAL_STR(type); // mp3
		QString encodeType = JVAL_STR(encodeType); // mp3
		qDebug() << QString::fromLocal8Bit(" 信息:" )<< br << size << type << encodeType << url;
		if (size == 0)
		{
			qDebug() << QString::fromLocal8Bit("下载失败, 可能没有版权") << music.simpleString();
			if (playAfterDownloaded == music)
			{
				if (orderSongs.contains(music))
				{
					orderSongs.removeOne(music);
					ui.playingNameLabel->clear();
					// 设置信息
					auto max16 = [=](QString s)
					{
						if (s.length() > 16)
							s = s.left(15) + "...";
						return s;
					};
					ui.playingNameLabel->setText(max16(music.name));
					ui.playingArtistLabel->setText(max16(music.artistNames));
					
					//  设置封面
					if (QFileInfo(coverPath(music)).exists())
					{
						QPixmap pixmap(coverPath(music), "1");
						if (pixmap.isNull())
							qDebug() << QString::fromLocal8Bit("warning: 本地封面是空的") << music.simpleString() << coverPath(music);
						// 自适应高度
						pixmap = pixmap.scaledToHeight(ui.playingCoverLablel->height());
						ui.playingCoverLablel->setPixmap(pixmap);
					}
					else
						downloadSongCover(music);
					player->stop();
				}
			}
			downloadingSong = Music();
			downloadNext();
			return;
		}

		// 下载歌曲本身
		QNetworkAccessManager manager;
		QEventLoop loop;
		QNetworkReply *reply1 = manager.get(QNetworkRequest(QUrl(url)));

		// 请求结束并完成下载后退出子事件循环
		connect(reply1, &QNetworkReply::finished, &loop, &QEventLoop::quit);

		// 开启子事件循环
		loop.exec();
		QByteArray baData1 = reply1->readAll();

		QString strPath = songPath(music);
		QFile file(strPath);
		file.open(QIODevice::WriteOnly);
		file.write(baData1);
		file.flush();
		file.close();

		if (playAfterDownloaded == music)
			playLocalSong(music);

		downloadingSong = Music();
		downloadNext();
	});
	manager->get(*request);

	downloadSongLyric(music);
	downloadSongCover(music);
}

4、音乐播放与暂停

根据QMediaPlayer提供的接口函数调用play()和pause()即可。

	// 开始播放
	playingSong = music;
	player->setMedia(QUrl::fromLocalFile(songPath(music)));
	player->setPosition(0);
	player->play();

5、音乐播放进度条

通过获取音乐的全部时长,设置进度条的全部长度,如下:

	connect(player, &QMediaPlayer::durationChanged, this, [=](qint64 duration)
	{
		ui.playProgressSlider->setMaximum(static_cast<int>(duration));
	});

音乐播放的时候,动态修改进度条值。

void QtMusic::slotPlayerPositionChanged()
{
	qint64 position = player->position();

	QPropertyAnimation* ani = new QPropertyAnimation(this, "lyricScroll");
	ani->setDuration(200);
	connect(ani, &QPropertyAnimation::valueChanged, this, [=] {
	});
	connect(ani, SIGNAL(finished()), ani, SLOT(deleteLater()));
	ani->start();
	ui.playProgressSlider->setSliderPosition(static_cast<int>(position));
	update();
}

6、本次实例全部代码链接

https://download.csdn.net/download/u013083044/15076281

你可能感兴趣的:(Qt,c++)