Skip to content

Commit

Permalink
歌单,播放列表已可用,提高了软件的可靠性
Browse files Browse the repository at this point in the history
  • Loading branch information
Miaoyww committed Aug 20, 2022
1 parent fd81682 commit 9ca6524
Show file tree
Hide file tree
Showing 13 changed files with 613 additions and 400 deletions.
295 changes: 44 additions & 251 deletions NcmPlayer/CloudMusic/CloudMusic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,247 +7,6 @@

namespace NcmPlayer.CloudMusic
{
/*
public static class CloudMusic
{
public static System.Timers.Timer timer = new System.Timers.Timer();
public static string title;
public static string artist;
public static string albumId;
public static string albumPicUrl;
public static string albumPicPath;
public static string copiedPath;
public static string postMes = "已提交指令:";
public static int pid;
public static IntPtr hwnd;
public static IntPtr maindHwnd;
public static string tempPath = $"{Path.GetTempPath()}alpics\\";
public static byte[] ReadFile(string path)
{
bool _isExist = false;
if (!File.Exists(path))
{
FileStream createSoundsJson = new FileStream(path, FileMode.Create);
createSoundsJson.Flush();
createSoundsJson.Close();
_isExist = false;
}
else
{
_isExist = true;
}
using (FileStream fsSource = new FileStream(path, FileMode.Open, FileAccess.Read))
{
byte[] bytes = new byte[fsSource.Length];
int numBytesToRead = (int)fsSource.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to numBytesToRead.
int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);
// Break when the end of the file is reached.
if (n == 0)
break;
numBytesRead += n;
numBytesToRead -= n;
}
fsSource.Flush();
fsSource.Close();
if (_isExist)
{
return bytes;
}
else
{
return null;
}
}
}
public static string B2S(byte[] bytes)
{
string msg = Encoding.UTF8.GetString(bytes);
if (msg.Equals(""))
{
return string.Empty;
}
byte[] buffer = Encoding.UTF8.GetBytes(msg);
string sResult = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
byte[] bomBuffer = new byte[] { 0xef, 0xbb, 0xbf };
if (buffer[0] == bomBuffer[0] && buffer[1] == bomBuffer[1] && buffer[2] == bomBuffer[2])
{
int copyLength = buffer.Length - 3;
byte[] dataNew = new byte[copyLength];
Buffer.BlockCopy(buffer, 3, dataNew, 0, copyLength);
sResult = Encoding.UTF8.GetString(dataNew);
}
return sResult;
}
public static void GetAlumbInfo(Stream stream, string processedTitle, string processedArtists)
{
StreamReader objReader = new StreamReader(stream);
JObject result = (JObject)JsonConvert.DeserializeObject(objReader.ReadLine());
foreach (JToken token in result["result"]["songs"])
{
string targetTitle = string.Empty;
string targetArtist = string.Empty;
string soundId = string.Empty;
targetTitle = token["name"].ToString().Replace(" ", "");
if (targetTitle.Equals(processedTitle))
{
JToken artists = token["ar"];
foreach (JToken artistItem in artists)
{
targetArtist += artistItem["name"].ToString().Replace(" ", "") + "/";
}
if (targetArtist.Remove(targetArtist.Length - 1).Equals(processedArtists))
{
soundId = token["id"].ToString();
}
if (!soundId.Equals(string.Empty))
{
albumId = token["al"]["id"].ToString();
albumPicUrl = token["al"]["picUrl"].ToString();
break;
}
}
}
}
public static void Download2ApplyAlbumPic(string url, string albumid)
{
albumPicPath = $"./alpics/{albumId}.jpg";
if (!Directory.Exists("./alpics"))
{
Directory.CreateDirectory("./alpics");
}
if (!Directory.Exists(tempPath))
{
Directory.CreateDirectory(tempPath);
}
if (!File.Exists(albumPicPath))
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream responseStream = response.GetResponseStream();
Stream stream = new FileStream(albumPicPath, FileMode.Create);
byte[] bArr = new byte[1024];
int size = responseStream.Read(bArr, 0, bArr.Length);
while (size > 0)
{
stream.Write(bArr, 0, size);
size = responseStream.Read(bArr, 0, bArr.Length);
}
stream.Close();
responseStream.Close();
}
ApplyAlbumPic(albumid);
PostInfo.InputLog("已切换封面, 歌曲名称:", title);
}
public static void ApplyAlbumPic(string albumid)
{
copiedPath = tempPath + $"{albumid}.jpg";
if (!File.Exists(copiedPath))
{
File.Copy(albumPicPath, copiedPath, true);
}
}
public static void GetCover()
{
string sURL = $"http://localhost:3000/cloudsearch?keywords={title} -{artist}&limit=10";
string processedTitle = title.Replace(" ", ""); // 为方便对比, 将所有空格去掉
string processedArtist = artist.Replace(" ", "");
byte[] readResultBytes = ReadFile(Res.res.SoundsPath);
string readResult = B2S(readResultBytes);
string savingContent = $"{title} -{artist}"; // 用于储存在sounds.json followings中的成员
JObject result;
JArray? albumList = new();
if (readResult == string.Empty)
{
JObject? currentSoundInfo = new JObject();
GetAlumbInfo(HttpGet(sURL), processedTitle, processedArtist);
currentSoundInfo.Add("albumId", albumId);
currentSoundInfo.Add("followings", new JArray() { $"{title} -{artist}" });
albumList.Add(currentSoundInfo);
Download2ApplyAlbumPic(albumPicUrl, albumId);
}
else
{
JObject? readResultJObject = JObject.Parse(readResult);
albumList = (JArray)readResultJObject["sounds"];
bool _titleIsExist = false;
foreach (JObject album in albumList)
{
foreach (var sound in album["followings"])
{
if (sound.ToString().Equals(savingContent))
{
albumId = album["albumId"].ToString();
albumPicPath = $"./alpics/{albumId}.jpg";
if (File.Exists(albumPicPath))
{
ApplyAlbumPic(albumId);
}
else
{
GetAlumbInfo(HttpGet(sURL), processedTitle, processedArtist);
Download2ApplyAlbumPic(albumPicUrl, albumId);
}
_titleIsExist = true;
}
}
}
GetAlumbInfo(HttpGet(sURL), processedTitle, processedArtist);
if (!_titleIsExist)
{
JObject? currentSoundInfo = new JObject();
int index = 0;
foreach (JObject album in albumList)
{
if (album["albumId"].ToString().Equals(albumId))
{
JObject currentSoundAlbum = (JObject)albumList[index];
albumId = currentSoundAlbum["albumId"].ToString();
albumPicPath = $"./alpics/{albumId}.jpg";
JArray soundList = (JArray)currentSoundAlbum["followings"];
soundList.Add(savingContent);
albumList.RemoveAt(index);
albumList.Add(currentSoundAlbum);
_titleIsExist = true;
ApplyAlbumPic(albumId);
break;
}
index++;
}
if (!_titleIsExist)
{
currentSoundInfo.Add("albumId", albumId);
currentSoundInfo.Add("followings", new JArray() { savingContent });
albumList.Add(currentSoundInfo);
Download2ApplyAlbumPic(albumPicUrl, albumId);
}
}
}
result = new JObject { { "sounds", albumList } };
try
{
WriteFile(Res.res.SoundsPath, result.ToString());
}
catch (IOException)
{
}
}
}
*/

public static class HttpRequest
{
public static Stream StreamHttpGet(string url)
Expand Down Expand Up @@ -352,6 +111,10 @@ public Stream Cover
{
cover = HttpRequest.StreamHttpGet(coverUrl);
}
if (!cover.CanRead)
{
cover = HttpRequest.StreamHttpGet(coverUrl);
}
return cover;
}
set
Expand Down Expand Up @@ -380,6 +143,8 @@ public class PlayList : CloudMusic
private string[] songsId;
private DateTime createTime;
private string creator = String.Empty;
private Song[] songs;
private bool[] threadDone;

public PlayList(string in_id)
{
Expand Down Expand Up @@ -412,14 +177,42 @@ public PlayList(string in_id)

public Song[] InitArtWorkList(int start, int end)
{
int maxWorkerThreads = 10;
ThreadPool.SetMaxThreads(maxWorkerThreads, maxWorkerThreads);
string[] ids = SongsId[start..end];
Song[] songs = new Song[end - start];
songs = new Song[end - start];
threadDone = new bool[end - start];
for (int index = 0; index < threadDone.Length; index++)
{
threadDone[index] = false;
}
for (int index = 0; index < songs.Length; index++)
{
Song one = new(ids[index]);
songs[index] = one;
ThreadPool.QueueUserWorkItem(new WaitCallback(GetSongDetail), new object[] { ids[index], index });
}
return songs;
while (true)
{
bool isExsit = true;
foreach (bool state in threadDone)
{
if (!state)
{
isExsit = false;
}
}
if (isExsit)
{
return songs;
}
}
}

private void GetSongDetail(object parm)
{
object[] objects = (object[])parm;
Song song = new(objects[0].ToString());
songs[(int)objects[1]] = song;
threadDone[(int)objects[1]] = true;
}

public string[] SongsId
Expand Down Expand Up @@ -481,9 +274,7 @@ public Song(string in_id)
}

TimeSpan timespan = TimeSpan.FromMilliseconds(int.Parse(songDetail["dt"].ToString()));
int min = timespan.Minutes;
int sec = timespan.Seconds;
duartionTime = $"{min}:{sec}";
duartionTime = timespan.ToString(@"mm\:ss");
albumId = songDetail["al"]["id"].ToString();
albumName = songDetail["al"]["name"].ToString();
CoverUrl = songDetail["al"]["picUrl"].ToString();
Expand Down Expand Up @@ -530,7 +321,8 @@ public string GetFile()

public string SongUrl
{
get {
get
{
if (songUrl.Equals(string.Empty))
{
JObject temp = (JObject)HttpRequest.GetJson(Apis.songUrl(Id))["data"][0];
Expand All @@ -543,14 +335,15 @@ public string SongUrl

public string SongType
{
get {
get
{
if (songType.Equals(string.Empty))
{
JObject temp = (JObject)HttpRequest.GetJson(Apis.songUrl(Id))["data"][0];
songUrl = temp["url"].ToString();
songType = temp["type"].ToString();
}
return songType;
return songType;
}
}
}
Expand Down
11 changes: 9 additions & 2 deletions NcmPlayer/Player/MusicPlayer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,15 @@ public static void Musicplayer_MediaEnded(object sender, RoutedEventArgs e)

public static void Musicplayer_MediaOpened(object sender, RoutedEventArgs e)
{
Res.res.CPlayWholeTime = (int)musicplayer.NaturalDuration.TimeSpan.TotalSeconds;
Res.res.IsPlaying = true;
try
{
Res.res.CPlayWholeTime = (int)musicplayer.NaturalDuration.TimeSpan.TotalSeconds;
Res.res.IsPlaying = true;
}
catch (InvalidOperationException)
{

}
}

public static void Musicplayer_MediaFailed(object? sender, ExceptionRoutedEventArgs e)
Expand Down
Loading

0 comments on commit 9ca6524

Please sign in to comment.