Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c88b54af6c | |||
| 80713319e0 | |||
| 870a106594 | |||
| f6e59defb8 | |||
| 0e7c4b3e87 | |||
| 683f08693c | |||
| 80e8a8f379 | |||
| 3c9ec9dc18 | |||
| cbfbda649b | |||
| 5e42f726f7 | |||
|
|
48ac066238 | ||
|
|
3d7485b2a1 | ||
|
|
6173155509 | ||
|
|
767a1d8043 | ||
| e981f57660 | |||
| 6fa6292d48 | |||
|
|
3d3c7c1197 | ||
|
|
895b6fcdad | ||
| 55683f69c5 | |||
| c0f275cc9d | |||
|
|
ca4e086a66 | ||
|
|
91f9048755 | ||
| d69a4b6def | |||
|
|
62b95e38b0 |
117
LICENSE
Normal file
117
LICENSE
Normal file
@@ -0,0 +1,117 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author
|
||||
|
||||
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice
|
||||
521
MusicLyrics.lua
Normal file
521
MusicLyrics.lua
Normal file
@@ -0,0 +1,521 @@
|
||||
-- 歌词显示软件
|
||||
local function loadRemoteFont(url)
|
||||
local response = http.get(url)
|
||||
if not response then
|
||||
error("无法连接到字体服务器")
|
||||
end
|
||||
|
||||
if response.getResponseCode() ~= 200 then
|
||||
error("字体服务器返回错误: " .. response.getResponseCode())
|
||||
end
|
||||
|
||||
local content = response.readAll()
|
||||
response.close()
|
||||
|
||||
local sandbox = {}
|
||||
local chunk, err = load(content, "=remoteFont", "t", sandbox)
|
||||
if not chunk then
|
||||
error("加载字体失败: " .. err)
|
||||
end
|
||||
|
||||
local success, result = pcall(chunk)
|
||||
if not success then
|
||||
error("执行字体脚本失败: " .. result)
|
||||
end
|
||||
|
||||
return sandbox.font or sandbox[1] or result
|
||||
end
|
||||
|
||||
-- 显示单个字符的函数
|
||||
local function displayChar(charMap, x, y, textColor, backgroundColor)
|
||||
local origTextColor = term.getTextColor()
|
||||
local origBackgroundColor = term.getBackgroundColor()
|
||||
|
||||
term.setTextColor(textColor)
|
||||
term.setBackgroundColor(backgroundColor)
|
||||
|
||||
for row = 1, #charMap do
|
||||
term.setCursorPos(x, y + row - 1)
|
||||
local line = charMap[row]
|
||||
|
||||
for col = 1, #line do
|
||||
local byte = string.byte(line, col)
|
||||
|
||||
if byte < 128 then
|
||||
term.setTextColor(backgroundColor)
|
||||
term.setBackgroundColor(textColor)
|
||||
term.write(string.char(byte + 128))
|
||||
else
|
||||
term.setTextColor(textColor)
|
||||
term.setBackgroundColor(backgroundColor)
|
||||
term.write(string.char(byte))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
term.setTextColor(origTextColor)
|
||||
term.setBackgroundColor(origBackgroundColor)
|
||||
end
|
||||
|
||||
-- 显示UTF-8字符串的函数
|
||||
local function displayUtf8String(str, font, x, y, textColor, backgroundColor)
|
||||
local function utf8codes(str)
|
||||
local i = 1
|
||||
return function()
|
||||
if i > #str then return end
|
||||
|
||||
local b1 = string.byte(str, i)
|
||||
i = i + 1
|
||||
|
||||
if b1 < 0x80 then
|
||||
return b1
|
||||
elseif b1 >= 0xC0 and b1 < 0xE0 then
|
||||
local b2 = string.byte(str, i) or 0
|
||||
i = i + 1
|
||||
return (b1 - 0xC0) * 64 + (b2 - 0x80)
|
||||
elseif b1 >= 0xE0 and b1 < 0xF0 then
|
||||
local b2 = string.byte(str, i) or 0
|
||||
i = i + 1
|
||||
local b3 = string.byte(str, i) or 0
|
||||
i = i + 1
|
||||
return (b1 - 0xE0) * 4096 + (b2 - 0x80) * 64 + (b3 - 0x80)
|
||||
else
|
||||
return 32
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local cursorX = x
|
||||
|
||||
for code in utf8codes(str) do
|
||||
local charMap = font[code]
|
||||
if not charMap then
|
||||
charMap = font[32] or {{"\x80"}}
|
||||
end
|
||||
|
||||
displayChar(charMap, cursorX, y, textColor, backgroundColor)
|
||||
cursorX = cursorX + #charMap[1]
|
||||
end
|
||||
end
|
||||
|
||||
-- 解析歌词时间
|
||||
local function parseTime(timeStr)
|
||||
local minutes, seconds, milliseconds = timeStr:match("(%d+):(%d+)%.(%d+)")
|
||||
if minutes and seconds and milliseconds then
|
||||
return tonumber(minutes) * 60 + tonumber(seconds) + tonumber(milliseconds) / 1000
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- 解析歌词内容
|
||||
local function parseLyrics(lyricStr)
|
||||
local lyrics = {}
|
||||
if not lyricStr or lyricStr == "" then return lyrics end
|
||||
|
||||
for line in lyricStr:gmatch("[^\r\n]+") do
|
||||
if line:match("%[.+%]") then
|
||||
local timeStr = line:match("%[(.+)%]")
|
||||
local text = line:match("%].*$")
|
||||
if text then text = text:sub(2) else text = "" end
|
||||
|
||||
-- 过滤掉作词、作曲等元信息
|
||||
if timeStr and not timeStr:match("by:") and not timeStr:match("offset:") and not text:match("作词") and not text:match("作曲") then
|
||||
local time = parseTime(timeStr)
|
||||
table.insert(lyrics, {time = time, text = text})
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- 按时间排序
|
||||
table.sort(lyrics, function(a, b) return a.time < b.time end)
|
||||
return lyrics
|
||||
end
|
||||
|
||||
-- 计算字符串宽度
|
||||
local function getStringWidth(str, font)
|
||||
local width = 0
|
||||
local function utf8codes(s)
|
||||
local i = 1
|
||||
return function()
|
||||
if i > #s then return end
|
||||
local b1 = string.byte(s, i)
|
||||
i = i + 1
|
||||
if b1 < 0x80 then
|
||||
return b1
|
||||
elseif b1 >= 0xC0 and b1 < 0xE0 then
|
||||
local b2 = string.byte(s, i) or 0
|
||||
i = i + 1
|
||||
return (b1 - 0xC0) * 64 + (b2 - 0x80)
|
||||
elseif b1 >= 0xE0 and b1 < 0xF0 then
|
||||
local b2 = string.byte(s, i) or 0
|
||||
i = i + 1
|
||||
local b3 = string.byte(s, i) or 0
|
||||
i = i + 1
|
||||
return (b1 - 0xE0) * 4096 + (b2 - 0x80) * 64 + (b3 - 0x80)
|
||||
else
|
||||
return 32
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
for code in utf8codes(str) do
|
||||
local charMap = font[code] or font[32]
|
||||
width = width + #charMap[1]
|
||||
end
|
||||
return width
|
||||
end
|
||||
|
||||
-- 获取当前应该显示的歌词索引
|
||||
local function getCurrentLyricIndex(lyricPairs, currentTime)
|
||||
local currentIndex = 1
|
||||
for i = 1, #lyricPairs do
|
||||
if lyricPairs[i].time <= currentTime then
|
||||
currentIndex = i
|
||||
else
|
||||
break
|
||||
end
|
||||
end
|
||||
return currentIndex
|
||||
end
|
||||
|
||||
-- 解析颜色参数
|
||||
local function parseColor(colorStr)
|
||||
local colorsMap = {
|
||||
white = colors.white,
|
||||
orange = colors.orange,
|
||||
magenta = colors.magenta,
|
||||
lightBlue = colors.lightBlue,
|
||||
yellow = colors.yellow,
|
||||
lime = colors.lime,
|
||||
pink = colors.pink,
|
||||
gray = colors.gray,
|
||||
lightGray = colors.lightGray,
|
||||
cyan = colors.cyan,
|
||||
purple = colors.purple,
|
||||
blue = colors.blue,
|
||||
brown = colors.brown,
|
||||
green = colors.green,
|
||||
red = colors.red,
|
||||
black = colors.black
|
||||
}
|
||||
|
||||
return colorsMap[colorStr] or colors.white
|
||||
end
|
||||
|
||||
-- 主显示函数
|
||||
local function displayLyrics(url, notzh, fontType, colorsConfig)
|
||||
-- 选择字体
|
||||
local fontUrl
|
||||
if fontType == "12px" then
|
||||
fontUrl = "https://git.liulikeji.cn/xingluo/ComputerCraft-Utf8/raw/branch/main/fonts/fusion-pixel-12px-proportional-zh_hans.lua"
|
||||
else
|
||||
fontUrl = "https://git.liulikeji.cn/xingluo/ComputerCraft-Utf8/raw/branch/main/fonts/fusion-pixel-8px-proportional-zh_hans.lua"
|
||||
end
|
||||
|
||||
local font = loadRemoteFont(fontUrl)
|
||||
|
||||
-- 获取歌词数据
|
||||
local response = http.get(url)
|
||||
if not response then
|
||||
print("1 无法连接到服务器 URL: "..url)
|
||||
return
|
||||
end
|
||||
|
||||
if response.getResponseCode() ~= 200 then
|
||||
print("服务器返回错误: " .. response.getResponseCode())
|
||||
response.close()
|
||||
return
|
||||
end
|
||||
|
||||
local content = response.readAll()
|
||||
response.close()
|
||||
|
||||
-- 解析JSON数据
|
||||
local data = textutils.unserialiseJSON(content)
|
||||
if not data or not data.lrc or not data.lrc.lyric then
|
||||
print("2 无法解析歌词数据 URL: "..url)
|
||||
return
|
||||
end
|
||||
|
||||
-- 解析歌词
|
||||
local lyrics = parseLyrics(data.lrc.lyric)
|
||||
local tlyrics = {}
|
||||
if not notzh and data.tlyric and data.tlyric.lyric then
|
||||
tlyrics = parseLyrics(data.tlyric.lyric)
|
||||
end
|
||||
|
||||
if #lyrics == 0 and #tlyrics == 0 then
|
||||
print("3 没有找到有效歌词 URL: "..url)
|
||||
print(textutils.serialiseJSON(data))
|
||||
return
|
||||
end
|
||||
|
||||
-- 构建时间索引映射
|
||||
local timeIndexMap = {}
|
||||
for i, lyric in ipairs(lyrics) do
|
||||
local timeKey = string.format("%.3f", lyric.time)
|
||||
timeIndexMap[timeKey] = {original = i}
|
||||
end
|
||||
|
||||
for i, lyric in ipairs(tlyrics) do
|
||||
local timeKey = string.format("%.3f", lyric.time)
|
||||
if timeIndexMap[timeKey] then
|
||||
timeIndexMap[timeKey].translation = i
|
||||
else
|
||||
timeIndexMap[timeKey] = {translation = i}
|
||||
end
|
||||
end
|
||||
|
||||
-- 构建歌词对数组
|
||||
local lyricPairs = {}
|
||||
local allTimes = {}
|
||||
for timeKey, _ in pairs(timeIndexMap) do
|
||||
table.insert(allTimes, tonumber(timeKey))
|
||||
end
|
||||
table.sort(allTimes)
|
||||
|
||||
for _, time in ipairs(allTimes) do
|
||||
local timeKey = string.format("%.3f", time)
|
||||
local indices = timeIndexMap[timeKey]
|
||||
|
||||
local originalText = ""
|
||||
local translationText = ""
|
||||
|
||||
if indices.original then
|
||||
originalText = lyrics[indices.original].text or ""
|
||||
end
|
||||
|
||||
if indices.translation then
|
||||
translationText = tlyrics[indices.translation].text or ""
|
||||
end
|
||||
|
||||
table.insert(lyricPairs, {
|
||||
time = time,
|
||||
original = originalText,
|
||||
translation = translationText
|
||||
})
|
||||
end
|
||||
|
||||
if #lyricPairs == 0 then
|
||||
print("没有找到匹配的歌词对 URL: "..url)
|
||||
return
|
||||
end
|
||||
|
||||
-- 计算显示参数
|
||||
local screenWidth, screenHeight = term.getSize()
|
||||
local fontHeight = #font[32] -- 使用空格字符获取字体高度
|
||||
|
||||
-- 检查是否有翻译歌词
|
||||
local hasTranslation = false
|
||||
if not notzh then
|
||||
for _, pair in ipairs(lyricPairs) do
|
||||
if pair.translation and pair.translation ~= "" then
|
||||
hasTranslation = true
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- 根据是否显示翻译来计算行高
|
||||
local lyricPairHeight
|
||||
if notzh or not hasTranslation then
|
||||
lyricPairHeight = fontHeight + 1 -- 只有原文的高度
|
||||
else
|
||||
lyricPairHeight = fontHeight * 2 + 1 -- 原文+翻译的高度
|
||||
end
|
||||
|
||||
local maxLyricPairs = math.floor(screenHeight / lyricPairHeight)
|
||||
local visibleLyricPairs = math.max(1, maxLyricPairs) -- 确保至少显示1对
|
||||
|
||||
-- 显示循环
|
||||
while true do
|
||||
-- 获取当前播放时间
|
||||
local currentTime = _G.getPlay - 1 or 0 -- 直接获取_G.getPlay的值
|
||||
|
||||
-- 获取当前歌词索引
|
||||
local currentIndex = getCurrentLyricIndex(lyricPairs, currentTime)
|
||||
term.setBackgroundColor(colorsConfig.background)
|
||||
-- 清屏
|
||||
term.clear()
|
||||
|
||||
-- 计算显示范围 - 真正的居中显示策略
|
||||
local startPairIndex, endPairIndex
|
||||
|
||||
if visibleLyricPairs < 3 then
|
||||
-- 当可显示歌词少于3个时,优先显示当前和下一个歌词
|
||||
startPairIndex = currentIndex
|
||||
endPairIndex = math.min(#lyricPairs, startPairIndex + visibleLyricPairs - 1)
|
||||
|
||||
-- 如果显示空间还有剩余,尝试向前补充显示前面的歌词
|
||||
if endPairIndex - startPairIndex + 1 < visibleLyricPairs then
|
||||
local remainingSpace = visibleLyricPairs - (endPairIndex - startPairIndex + 1)
|
||||
startPairIndex = math.max(1, startPairIndex - remainingSpace)
|
||||
endPairIndex = math.min(#lyricPairs, startPairIndex + visibleLyricPairs - 1)
|
||||
end
|
||||
else
|
||||
-- 当可显示歌词3个或更多时,采用真正的居中显示策略
|
||||
-- 计算当前歌词上方和下方应该显示的歌词数量
|
||||
local aboveCount, belowCount
|
||||
if visibleLyricPairs % 2 == 1 then
|
||||
-- 奇数个显示位置:上下数量相等
|
||||
local halfCount = math.floor(visibleLyricPairs / 2)
|
||||
aboveCount = halfCount
|
||||
belowCount = halfCount
|
||||
else
|
||||
-- 偶数个显示位置:上面少一个,下面多一个(如你要求的4个和5个)
|
||||
aboveCount = math.floor(visibleLyricPairs / 2) - 1
|
||||
belowCount = math.floor(visibleLyricPairs / 2)
|
||||
end
|
||||
|
||||
-- 计算起始和结束索引
|
||||
startPairIndex = math.max(1, currentIndex - aboveCount)
|
||||
endPairIndex = math.min(#lyricPairs, currentIndex + belowCount)
|
||||
|
||||
-- 边界调整:如果前面不够显示,向后补充
|
||||
if currentIndex - startPairIndex < aboveCount then
|
||||
local needMore = aboveCount - (currentIndex - startPairIndex)
|
||||
endPairIndex = math.min(#lyricPairs, endPairIndex + needMore)
|
||||
end
|
||||
|
||||
-- 边界调整:如果后面不够显示,向前补充
|
||||
if endPairIndex - currentIndex < belowCount then
|
||||
local needMore = belowCount - (endPairIndex - currentIndex)
|
||||
startPairIndex = math.max(1, startPairIndex - needMore)
|
||||
end
|
||||
|
||||
-- 最终调整确保显示足够的行数
|
||||
if endPairIndex - startPairIndex + 1 < visibleLyricPairs then
|
||||
if startPairIndex > 1 then
|
||||
startPairIndex = math.max(1, endPairIndex - visibleLyricPairs + 1)
|
||||
else
|
||||
endPairIndex = math.min(#lyricPairs, startPairIndex + visibleLyricPairs - 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
local startY = 2
|
||||
|
||||
-- 显示歌词对
|
||||
for i = startPairIndex, endPairIndex do
|
||||
local lyricPair = lyricPairs[i]
|
||||
|
||||
-- 计算Y坐标 - 根据是否显示翻译动态计算
|
||||
local pairY
|
||||
if notzh or not hasTranslation then
|
||||
-- 不显示翻译时,每行只占一个字体高度
|
||||
pairY = startY + (i - startPairIndex) * (fontHeight + 1)
|
||||
else
|
||||
-- 显示翻译时,每对歌词占两个字体高度
|
||||
pairY = startY + (i - startPairIndex) * (fontHeight * 2 + 1)
|
||||
end
|
||||
|
||||
-- 设置颜色
|
||||
local textColor = colorsConfig.normalMain
|
||||
local translationColor = colorsConfig.normalSub
|
||||
local bgColor = colorsConfig.background
|
||||
|
||||
if i == currentIndex then
|
||||
textColor = colorsConfig.selectedMain
|
||||
translationColor = colorsConfig.selectedSub
|
||||
bgColor = colorsConfig.selectedBackground
|
||||
end
|
||||
|
||||
-- 显示原文(第一行)
|
||||
if lyricPair.original and lyricPair.original ~= "" then
|
||||
local x = math.floor((screenWidth - getStringWidth(lyricPair.original, font)) / 2)
|
||||
displayUtf8String(lyricPair.original, font, x, pairY, textColor, bgColor)
|
||||
end
|
||||
|
||||
-- 显示翻译(第二行)- 只有当notzh为false且有翻译时才显示
|
||||
if not notzh and hasTranslation and lyricPair.translation and lyricPair.translation ~= "" then
|
||||
local x = math.floor((screenWidth - getStringWidth(lyricPair.translation, font)) / 2)
|
||||
displayUtf8String(lyricPair.translation, font, x, pairY + fontHeight, translationColor, bgColor)
|
||||
end
|
||||
end
|
||||
|
||||
sleep(0.5)
|
||||
end
|
||||
|
||||
term.clear()
|
||||
term.setCursorPos(1, 1)
|
||||
print("歌词显示已退出")
|
||||
end
|
||||
|
||||
|
||||
-- 解析命令行参数
|
||||
local function parseArgs(args)
|
||||
local url = nil
|
||||
local notzh = false
|
||||
local fontType = "8px" -- 默认8px
|
||||
|
||||
-- 默认颜色配置
|
||||
local colorsConfig = {
|
||||
background = colors.black, -- 背景颜色
|
||||
normalMain = colors.gray, -- 歌词主颜色
|
||||
normalSub = colors.gray, -- 歌词辅颜色
|
||||
selectedMain = colors.white, -- 歌词选中主颜色
|
||||
selectedSub = colors.lightGray, -- 选中辅颜色
|
||||
selectedBackground = colors.black -- 选中背景色
|
||||
}
|
||||
|
||||
for i = 1, #args do
|
||||
local arg = args[i]
|
||||
|
||||
-- 处理颜色参数
|
||||
if arg:match("--normabg=") then
|
||||
local colorName = arg:sub(6)
|
||||
colorsConfig.background = parseColor(colorName)
|
||||
elseif arg:match("--normalmain=") then
|
||||
local colorName = arg:sub(14)
|
||||
colorsConfig.normalMain = parseColor(colorName)
|
||||
elseif arg:match("--normalsub=") then
|
||||
local colorName = arg:sub(13)
|
||||
colorsConfig.normalSub = parseColor(colorName)
|
||||
elseif arg:match("--selectedmain=") then
|
||||
local colorName = arg:sub(16)
|
||||
colorsConfig.selectedMain = parseColor(colorName)
|
||||
elseif arg:match("--selectedsub=") then
|
||||
local colorName = arg:sub(15)
|
||||
colorsConfig.selectedSub = parseColor(colorName)
|
||||
elseif arg:match("--selectedbg=") then
|
||||
local colorName = arg:sub(14)
|
||||
colorsConfig.selectedBackground = parseColor(colorName)
|
||||
elseif arg == "--notzh" then
|
||||
notzh = true
|
||||
elseif arg == "--8px" then
|
||||
fontType = "8px"
|
||||
elseif arg == "--12px" then
|
||||
fontType = "12px"
|
||||
elseif not url and arg:sub(1, 4) == "http" then
|
||||
url = arg
|
||||
end
|
||||
end
|
||||
|
||||
return url, notzh, fontType, colorsConfig
|
||||
end
|
||||
|
||||
-- 主程序
|
||||
local function main(...)
|
||||
local args = {...}
|
||||
local url, notzh, fontType, colorsConfig = parseArgs(args)
|
||||
|
||||
-- 如果没有通过参数提供URL,则要求用户输入
|
||||
if not url then
|
||||
term.clear()
|
||||
term.setCursorPos(1, 1)
|
||||
write("请输入歌词URL: ")
|
||||
url = read()
|
||||
|
||||
if not url or url == "" then
|
||||
print("URL不能为空")
|
||||
return
|
||||
end
|
||||
end
|
||||
|
||||
displayLyrics(url, notzh, fontType, colorsConfig)
|
||||
end
|
||||
|
||||
-- 运行主程序
|
||||
main(...)
|
||||
|
||||
153
README.md
Normal file
153
README.md
Normal file
@@ -0,0 +1,153 @@
|
||||
# ComputerCraft 网易云音乐播放器
|
||||
|
||||
|
||||
## 📌 简介
|
||||
|
||||
本程序是一个基于 **ComputerCraft**(Minecraft 模组)的网易云音乐播放器,使用 **Lua** 编写,调用了第三方网易云 API、DFPWM 音频转码 API,结合 [Basalt GUI库](https://github.com/PyPyl/Basalt) 构建图形界面,支持搜索/播放网易云音乐,并支持歌单播放、歌词同步等功能。
|
||||
|
||||
此版本支持中文音乐名称显示(搜索出来的列表),但搜索只能使用英文或中文拼音
|
||||
|
||||
支持歌词显示,且会根据显示大小变更文字分辨率,但在默认的终端使用会显示不全,所以此功能建议使用屏幕显示(monitor 方向 music168.lua)
|
||||
|
||||
此软件使用触控交互,所以不支持石头电脑
|
||||
---
|
||||
|
||||
### 🖼️ 展示图
|
||||
|
||||
#### 🔍 中文搜索展示
|
||||
支持中文音乐名称显示(搜索建议使用拼音或英文)
|
||||

|
||||
|
||||
#### 📄 播放列表展示
|
||||
点击播放后可查看当前播放列表并切换歌曲
|
||||

|
||||
|
||||
#### 📂 歌单搜索展示
|
||||
支持通过歌单 ID 搜索并播放整个歌单
|
||||

|
||||
|
||||
#### 🎙️ 歌词展示
|
||||
播放时可同步显示歌词
|
||||

|
||||
|
||||
#### 🖥️ 屏幕显示歌词展示(适配大屏显示)
|
||||
适用于使用 Monitor(monitor)外设播放时的歌词同步显示
|
||||

|
||||
|
||||
---
|
||||
|
||||
## 🚀 安装方法
|
||||
|
||||
在 Minecraft 中安装好 [ComputerCraft](https://www.mcmod.cn/class/1681.html) 模组后在电脑终端:
|
||||
|
||||
```bash
|
||||
wget https://git.liulikeji.cn/xingluo/ComputerCraft-Music168-Player/raw/branch/main/music168.lua
|
||||
```
|
||||
|
||||
运行:
|
||||
|
||||
```bash
|
||||
music168
|
||||
```
|
||||
|
||||
即可启动播放器。
|
||||
并自动补全运行库
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ 使用方法
|
||||
|
||||
### 🔍 搜索音乐
|
||||
|
||||
1. 在顶部输入框中输入歌曲名(拼音或英文均可,空格隔开)或网易云音乐 ID(需要多试几次)。
|
||||
2. 点击输入框右侧的 `Q` 按钮开始搜索。
|
||||
3. 下方列表中点击歌曲即可播放。
|
||||
|
||||
### 📂 歌单播放
|
||||
|
||||
1. 底部菜单栏点击 `{G}` 按钮,进入歌单搜索界面。
|
||||
2. 输入歌单 ID(可通过复制粘贴)并点击 `Q` 搜索。
|
||||
3. 点击歌单中的音乐可播放。
|
||||
|
||||
### 🎵 播放控制
|
||||
|
||||
- 点击播放界面中的按钮可控制播放暂停。
|
||||
- 点击 `T` 可打开播放列表,点击列表内歌曲切换歌曲。
|
||||
- 点击播放界面左上角的 `V` 退出播放界面到搜索。
|
||||
- 通过点击下方播放栏回到播放页面
|
||||
- 点击进度条可以切换播放进度
|
||||
|
||||
|
||||
### 多通道音频
|
||||
|
||||
- 默认为全部单通道播放,如使用双声道音频请按以下操作
|
||||
|
||||
编辑文件 speaker_groups.cfg
|
||||
```bash
|
||||
edit speaker_groups.cfg
|
||||
```
|
||||
在内部写入例如:
|
||||
```json
|
||||
{
|
||||
main = {}, --混合通道扬声器列表
|
||||
left = {"speaker_0","speaker_1"}, --左声道扬声器列表
|
||||
right = {"speaker_5","speaker_6"} --右声道扬声器列表
|
||||
}
|
||||
```
|
||||
这里的"speaker_0","speaker_1"等数量不限制,但多了会导致音频不同步或超出最大上限
|
||||
"speaker_0","speaker_1"等为扬声器名称,如果使用网线链接则是打开时聊天栏的名称,如果直接放在旁边则为方向名例如(top,left,right)
|
||||
|
||||
|
||||
---
|
||||
|
||||
## 📦 使用技术栈
|
||||
|
||||
- **语言**:Lua
|
||||
- **GUI 库**:[Basalt GUI](https://git.liulikeji.cn/GitHub/Basalt)
|
||||
- **网易云 API**:[liulikeji.cn](http://music168.liulikeji.cn:15843/)
|
||||
- **DFPWM 音频转码接口**:[GMapiServer-ffmpeg](https://git.liulikeji.cn/xingluo/GMapiServer/)
|
||||
- **歌词支持**:通过 `MusicLyrics.lua` 加载歌词
|
||||
- **播放和格式转换**:通过`speakerlib.lua` 转换格式和处理播放
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 注意事项
|
||||
|
||||
- 本程序为半成品,部分按钮仅作装饰。
|
||||
- 若播放无声音,请检查播放界面左下角时间是否为 `00:00`,如果长时间无变化,请稍等或重试。
|
||||
- 因为网络延迟或 API 崩溃,可能导致播放失败。
|
||||
- 播放效果依赖于 ComputerCraft 中的 **speaker** 外设(扬声器)。
|
||||
|
||||
---
|
||||
|
||||
## 🗂️ 更新历史
|
||||
|
||||
- **新增歌单播放功能**
|
||||
- 修复部分播放逻辑与 UI 显示错误
|
||||
|
||||
- **新增中文音乐名,歌词显示,多通道音频**
|
||||
- 使用了新版GMApi接口
|
||||
|
||||
---
|
||||
|
||||
|
||||
## 🛑 声明
|
||||
|
||||
> 本项目仅供学习交流使用,API 来源于第三方网易云api,音乐内容的版权属于原权利人。请勿用于商业用途。
|
||||
|
||||
---
|
||||
|
||||
## 🧑💻 项目作者
|
||||
|
||||
项目为个人开发,目前处于“咕咕咕”状态,更新不确定。
|
||||
|
||||
---
|
||||
|
||||
## 📬 反馈与支持
|
||||
|
||||
如有建议或问题,请联系项目原作者。
|
||||
|
||||
---
|
||||
|
||||
> 祝你享受愉快的音乐时光 🎶
|
||||
在 ComputerCraft 世界中聆听你的网易云音乐❤
|
||||
BIN
READMEImage/中文搜索展示.png
Normal file
BIN
READMEImage/中文搜索展示.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 94 KiB |
BIN
READMEImage/屏幕显示歌词展示.png
Normal file
BIN
READMEImage/屏幕显示歌词展示.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 595 KiB |
BIN
READMEImage/播放列表展示.png
Normal file
BIN
READMEImage/播放列表展示.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 110 KiB |
BIN
READMEImage/播放栏展示.png
Normal file
BIN
READMEImage/播放栏展示.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 100 KiB |
BIN
READMEImage/歌单搜索展示.png
Normal file
BIN
READMEImage/歌单搜索展示.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 123 KiB |
BIN
READMEImage/歌词展示.png
Normal file
BIN
READMEImage/歌词展示.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 108 KiB |
190
music168.lua
190
music168.lua
@@ -1,10 +1,10 @@
|
||||
-----------------------------------------------------------------系统启动阶段-------------------------------------------------------------------------------------------------
|
||||
|
||||
--*获取程序所在目录
|
||||
local mypath = "/"..fs.getDir(shell.getRunningProgram())
|
||||
|
||||
if not fs.exists(mypath.."/lib/basalt.lua") then shell.run("wget https://git.liulikeji.cn/GitHub/Basalt/releases/download/v1.6.3/basalt.lua lib/basalt.lua") end
|
||||
if not fs.exists(mypath.."/speaker.lua") then shell.run("wget https://git.liulikeji.cn/xingluo/ComputerCraft-Music168-Player/releases/download/v1.0.0/speaker.lua") end
|
||||
local mypath = "/"..fs.getDir(shell.getRunningProgram())
|
||||
if not fs.exists(mypath.."/lib/basalt.lua") then shell.run("wget https://git.liulikeji.cn/GitHub/Basalt/releases/download/v1.6.6/basalt.lua "..mypath.."/lib/basalt.lua") end
|
||||
if not fs.exists(mypath.."/speakerlib.lua") then shell.run("wget https://git.liulikeji.cn/xingluo/ComputerCraft-Music168-Player/raw/branch/main/speakerlib.lua "..mypath.."/speakerlib.lua") end
|
||||
if not fs.exists(mypath.."/MusicLyrics.lua") then shell.run("wget https://git.liulikeji.cn/xingluo/ComputerCraft-Music168-Player/raw/branch/main/MusicLyrics.lua "..mypath.."/MusicLyrics.lua") end
|
||||
|
||||
--*GUI库导入
|
||||
basalt = require(mypath.."/lib/basalt")
|
||||
@@ -15,7 +15,6 @@ main = {
|
||||
}
|
||||
_G.Playprint = false
|
||||
_G.Playopen =false
|
||||
|
||||
--*GUI框架配置表
|
||||
local sub = {
|
||||
["UI"] = {
|
||||
@@ -36,7 +35,6 @@ local sub = {
|
||||
mainf:addFrame():setPosition(2, "parent.h + 1"):setSize("parent.w-2", 13):setBackground(colors.orange),
|
||||
}
|
||||
}
|
||||
|
||||
--创建动画
|
||||
play_Gui_UP = mainf:addAnimation():setObject(sub["BF"][1]):move(1,1,0.3)
|
||||
play_Gui_DO = mainf:addAnimation():setObject(sub["BF"][1]):move(1,mainf:getHeight()+1,1)
|
||||
@@ -52,21 +50,21 @@ play_Gui = {
|
||||
sub["BF"][1]:addButton():setPosition(1,1):setSize(3, 1):setText("V"):onClick(function() play_Gui_DO:play() play_GUI_state=false main[1]:enable() end):setBackground(colors.red):setForeground(colors.white),
|
||||
sub["BF"][1]:addLabel():setText("NO Music"):setPosition(sub["BF"][1]:getWidth()/2 - #play_name/2,1):setBackground(colors.red):setForeground(colors.white),
|
||||
sub["BF"][1]:addLabel():setText("NO Music"):setPosition(sub["BF"][1]:getWidth()/2 - #play_id/2,2):setBackground(colors.red):setForeground(colors.white),
|
||||
sub["BF"][1]:addLabel():setText(" "):setPosition(3,4):setSize("parent.w-4", "parent.h-10"):setBackground(colors.white):setForeground(colors.red),
|
||||
sub["BF"][1]:addButton():setPosition(3,"parent.h-5"):setSize(1, 1):setText("\3"):onClick(function() end):setForeground(colors.white):setBackground(colors.red),
|
||||
sub["BF"][1]:addButton():setPosition(8,"parent.h-5"):setSize(1, 1):setText("\25"):onClick(function() end):setForeground(colors.white):setBackground(colors.red),
|
||||
sub["BF"][1]:addButton():setPosition("parent.w/2","parent.h-5"):setSize(2, 1):setText("+-"):onClick(function() end):setForeground(colors.white):setBackground(colors.red),
|
||||
sub["BF"][1]:addButton():setPosition("parent.w-3","parent.h-5"):setSize(1, 1):setText("@"):onClick(function() end):setForeground(colors.white):setBackground(colors.red),
|
||||
sub["BF"][1]:addButton():setPosition("parent.w-8","parent.h-5"):setSize(1, 1):setText("E"):onClick(function() end):setForeground(colors.white):setBackground(colors.red),
|
||||
sub["BF"][1]:addProgressbar():setPosition(3, "parent.h - 4"):setSize("parent.w - 4", 1):setProgressBar(colors.red, "=", colors.white):setBackground(colors.red):setBackgroundSymbol("-"):setForeground(colors.white),
|
||||
sub["BF"][1]:addLabel():setText("00:00"):setPosition("3", "parent.h - 3"):setSize(5, 1):setForeground(colors.white),
|
||||
sub["BF"][1]:addLabel():setText("00:00"):setPosition("parent.w - 6", "parent.h - 3"):setSize(5, 1):setForeground(colors.white),
|
||||
sub["BF"][1]:addButton():setPosition(3, "parent.h - 2"):setSize(3, 1):setText("=O="):onClick(function() end):setForeground(colors.white):setBackground(colors.red),
|
||||
sub["BF"][1]:addButton():setPosition("parent.w /2 - 4","parent.h - 2"):setSize(2, 1):setText("|\17"):onClick(function() play_set_1() end):setForeground(colors.white):setBackground(colors.red),
|
||||
sub["BF"][1]:addButton():setPosition("parent.w / 2 ", "parent.h - 2"):setSize(2, 1):setText("I>"):onClick(function() if play_data_table["play"] then _G.Playstop = true play_data_table["play"]=false else play_data_table["play"]=true end end):setForeground(colors.white):setBackground(colors.red),
|
||||
sub["BF"][1]:addButton():setPosition("parent.w / 2 +4", "parent.h - 2"):setSize(2, 1):setText("\16|"):onClick(function() play_set_0() end):setForeground(colors.white):setBackground(colors.red),
|
||||
sub["BF"][1]:addButton():setPosition("parent.w - 4", "parent.h - 2"):setSize(3, 1):setText("=T="):onClick(function() play_table_Gui_UP:play() main[1]:disable() sub["BF"][1]:disable() end):setForeground(colors.white):setBackground(colors.red),
|
||||
sub["BF"][1]:addSlider():setPosition(3, "parent.h - 4"):setSize("parent.w - 4", 1):setMaxValue(100):setBackground(colors.red):setForeground(colors.white),--:setBackgroundSymbol("\x8c"):setSymbol(" "),
|
||||
sub["BF"][1]:addProgram():setPosition(2,2):setSize("parent.w-2", "parent.h-4"),
|
||||
1,--sub["BF"][1]:addButton():setPosition(3,"parent.h-5"):setSize(1, 1):setText("\3"):onClick(function() end):setForeground(colors.white):setBackground(colors.red),
|
||||
1,--sub["BF"][1]:addButton():setPosition(8,"parent.h-5"):setSize(1, 1):setText("\25"):onClick(function() end):setForeground(colors.white):setBackground(colors.red),
|
||||
1,--sub["BF"][1]:addButton():setPosition("parent.w/2","parent.h-5"):setSize(2, 1):setText("+-"):onClick(function() end):setForeground(colors.white):setBackground(colors.red),
|
||||
1,--sub["BF"][1]:addButton():setPosition("parent.w-3","parent.h-5"):setSize(1, 1):setText("@"):onClick(function() end):setForeground(colors.white):setBackground(colors.red),
|
||||
1,--sub["BF"][1]:addButton():setPosition("parent.w-8","parent.h-5"):setSize(1, 1):setText("E"):onClick(function() end):setForeground(colors.white):setBackground(colors.red),
|
||||
sub["BF"][1]:addProgressbar():setPosition(3, "parent.h - 2"):setSize("parent.w - 4", 1):setProgressBar(colors.red, "=", colors.white):setBackground(colors.red):setBackgroundSymbol("-"):setForeground(colors.white),
|
||||
sub["BF"][1]:addLabel():setText("00:00"):setPosition("3", "parent.h - 1"):setSize(5, 1):setForeground(colors.white),
|
||||
sub["BF"][1]:addLabel():setText("00:00"):setPosition("parent.w - 6", "parent.h - 1"):setSize(5, 1):setForeground(colors.white),
|
||||
sub["BF"][1]:addButton():setPosition(3, "parent.h - 0"):setSize(3, 1):setText("=O="):onClick(function() end):setForeground(colors.white):setBackground(colors.red),
|
||||
sub["BF"][1]:addButton():setPosition("parent.w /2 - 4","parent.h - 0"):setSize(2, 1):setText("|\17"):onClick(function() play_set_1() end):setForeground(colors.white):setBackground(colors.red),
|
||||
sub["BF"][1]:addButton():setPosition("parent.w / 2 ", "parent.h - 0"):setSize(2, 1):setText("I>"):onClick(function() if play_data_table["play"] then _G.Playstop = true play_data_table["play"]=false else play_data_table["play"]=true end end):setForeground(colors.white):setBackground(colors.red),
|
||||
sub["BF"][1]:addButton():setPosition("parent.w / 2 +4", "parent.h - 0"):setSize(2, 1):setText("\16|"):onClick(function() play_set_0() end):setForeground(colors.white):setBackground(colors.red),
|
||||
sub["BF"][1]:addButton():setPosition("parent.w - 4", "parent.h - 0"):setSize(3, 1):setText("=T="):onClick(function() play_table_Gui_UP:play() main[1]:disable() sub["BF"][1]:disable() end):setForeground(colors.white):setBackground(colors.red),
|
||||
sub["BF"][1]:addSlider():setPosition(3, "parent.h - 2"):setSize("parent.w - 4", 1):setMaxValue(100):setBackground(colors.red):setForeground(colors.white),--:setBackgroundSymbol("\x8c"):setSymbol(" "),
|
||||
}
|
||||
--创建播放UI
|
||||
play_column_Gui = {
|
||||
@@ -75,13 +73,11 @@ play_column_Gui = {
|
||||
sub["BF"][2]:addButton():setPosition("parent.w-1", 1):setSize(1, 1):setText("T"):onClick(function() play_table_Gui_UP:play() main[1]:disable() end):setForeground(colors.white):setBackground(colors.lightGray),
|
||||
sub["BF"][2]:addButton():setPosition(1, 1):setSize("parent.w -5", 1):setText(""):onClick(function() play_Gui_UP:play() play_GUI_state=true main[1]:disable() end):setBackground(colors.lights),
|
||||
}
|
||||
|
||||
play_table_Gui = {
|
||||
sub["play_table"][1]:addButton():setPosition("parent.w-3",1):setSize(3, 1):setText("V"):onClick(function() if not play_GUI_state then main[1]:enable() end sub["BF"][1]:enable() play_table_Gui_DO:play() end):setBackground(colors.no):setForeground(colors.white),
|
||||
sub["play_table"][1]:addLabel():setText("PlyaTable"):setPosition(1,1):setForeground(colors.white),
|
||||
sub["play_table"][1]:addList():setPosition(2,3):setSize("parent.w-2", "parent.h-2"):setScrollable(true),
|
||||
}
|
||||
|
||||
--创建菜单栏
|
||||
menuBut = {
|
||||
sub["menu"][1]:addButton():setPosition(3,1):setSize(3, 1):setText("{Q}"):onClick(function() for index, value in ipairs(menuBut) do value:setBackground(colors.lightGray) end menuBut[1]:setBackground(colors.red) for index, value in ipairs(sub["UI"]) do value:hide() end sub["UI"][1]:show() end):setForeground(colors.white):setBackground(colors.red),
|
||||
@@ -93,19 +89,14 @@ menuBut = {
|
||||
-----------------------------------------------------------------DATA---------------------------------------------------------------------------------------------------------
|
||||
play_data_table = { ["music"] = {} , ["play"] = false ,["play_table"] = {}, ["play_table_index"] = 0, ["mode"] = "" , }
|
||||
_G.Playopen = false
|
||||
_G.getPlay = 0
|
||||
_G.getPlaymax = 0
|
||||
_G.setPlay = nil
|
||||
-----------------------------------------------------------------模块---------------------------------------------------------------------------------------------------------
|
||||
--多线程
|
||||
thread_table = {}
|
||||
function AddThread(funct)
|
||||
thread1 = mainf:addThread()
|
||||
thread1:start(funct)
|
||||
table.insert(thread_table,thread1)
|
||||
return #thread_table
|
||||
end
|
||||
|
||||
--音乐+
|
||||
function play_set_1()
|
||||
_G.music168_playopen = false
|
||||
_G.music168_playopen = false os.queueEvent("music168_play_stop")
|
||||
_G.getPlay = 0
|
||||
_G.Playopen = false
|
||||
_G.Playstop = false
|
||||
@@ -118,7 +109,7 @@ function play_set_1()
|
||||
end
|
||||
--音乐-
|
||||
function play_set_0()
|
||||
_G.music168_playopen = false
|
||||
_G.music168_playopen = false os.queueEvent("music168_play_stop")
|
||||
_G.getPlay = 0
|
||||
_G.Playopen = false
|
||||
_G.Playstop = false
|
||||
@@ -129,8 +120,6 @@ function play_set_0()
|
||||
play_table_Gui[3]:selectItem(table_index+1)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
--获取URL
|
||||
function GetmusicUrl(music_id)
|
||||
while true do
|
||||
@@ -144,14 +133,14 @@ function GetmusicUrl(music_id)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--dfpwm转码
|
||||
|
||||
--播放
|
||||
function playmusic(music_name,music_id,play_table,index)
|
||||
_G.getPlay = 0
|
||||
_G.getPlaymax = 0
|
||||
_G.Playopen = false
|
||||
_G.Playstop = false
|
||||
_G.music168_playopen = false os.queueEvent("music168_play_stop")
|
||||
|
||||
play_Gui[2]:setText(music_name):setPosition(sub["BF"][1]:getWidth()/2 +1 - #music_name/2,1)
|
||||
play_Gui[3]:setText(music_id):setPosition(sub["BF"][1]:getWidth()/2 +1 - #tostring(music_id)/2,2)
|
||||
play_column_Gui[1]:setText(music_name.." | "..tostring(music_id))
|
||||
@@ -159,11 +148,12 @@ function playmusic(music_name,music_id,play_table,index)
|
||||
play_data_table["play_table"] = play_table
|
||||
play_data_table["play_table_index"] = index
|
||||
play_data_table["play"] = true
|
||||
|
||||
play_table_Gui[3]:clear()
|
||||
for index, value in ipairs(play_table) do
|
||||
play_table_Gui[3]:addItem(value["name"].." | "..tostring(value["id"]))
|
||||
end
|
||||
|
||||
|
||||
play_table_Gui[3]:selectItem(index)
|
||||
_G.music168_music_id = music_id
|
||||
|
||||
@@ -171,12 +161,10 @@ function playmusic(music_name,music_id,play_table,index)
|
||||
--basalt.debug("true")
|
||||
--play_thread_id = AddThread(function ()
|
||||
--
|
||||
|
||||
|
||||
--end)
|
||||
|
||||
end
|
||||
|
||||
printUtf8 = load(http.get("https://git.liulikeji.cn/xingluo/ComputerCraft-Utf8/raw/branch/main/utf8ptrint.lua").readAll())()
|
||||
--搜索
|
||||
server_url = "http://music168.liulikeji.cn:15843/"
|
||||
function Search(input_str,GUI_in,api)
|
||||
@@ -194,7 +182,6 @@ function Search(input_str,GUI_in,api)
|
||||
table_get = textutils.unserialiseJSON(json_str)
|
||||
if table_get["code"] ~= 404 then kg_a=true end
|
||||
end
|
||||
|
||||
if http1 then
|
||||
if kg_a then
|
||||
if api=="search" then
|
||||
@@ -208,18 +195,24 @@ function Search(input_str,GUI_in,api)
|
||||
Search_table[index]=out_table
|
||||
end
|
||||
end
|
||||
|
||||
a=2
|
||||
if play_lib_F then play_lib_F:remove() end
|
||||
play_lib_F = GUI_in[3]:addFrame():setPosition(1, 1):setSize("parent.w", "parent.h"):setBackground(colors.white):setScrollable()
|
||||
|
||||
for index, value in ipairs(Search_table) do
|
||||
frame = play_lib_F:addFrame():setPosition(2, a):setSize("parent.w-2", 3):setBackground(colors.lightBlue):onClick(function() if play_data_table["play"] then shell.run(mypath.."/speaker.lua stop") if _G.Playopen then end _G.music168_playopen = false play_data_table["play"]=false end play_Gui_UP:play() play_GUI_state = true main[1]:disable() playmusic(value["name"],value["id"],Search_table,index) end)
|
||||
frame:addLabel():setText(value["name"]):setPosition(1, 1)
|
||||
frame:addLabel():setText("id: "..value["id"]):setPosition(1, 2)
|
||||
frame:addLabel():setText("artists: "..value["artists_name"]):setPosition(1, 3)
|
||||
a=a+4
|
||||
id = value["id"]
|
||||
local frame = play_lib_F:addFrame():setPosition(2, a):setSize("parent.w-2", 4):setBackground(colors.lightBlue):onClick(function() if play_data_table["play"] then shell.run(mypath.."/speakerlib.lua stop") if _G.Playopen then end _G.music168_playopen = false os.queueEvent("music168_play_stop") play_data_table["play"]=false end play_Gui_UP:play() play_GUI_state = true main[1]:disable() _G.music168_playopen = false os.queueEvent("music168_play_stop") playmusic(value["name"],value["id"],Search_table,index) end)
|
||||
local textf = frame:addFrame():setPosition(1, 1):setSize("parent.w", 3)
|
||||
textf:addProgram():setPosition(1, 1):setSize("parent.w + 200", 4):execute(function ()
|
||||
term.setBackgroundColor(colors.lightGray)
|
||||
term.clear()
|
||||
printUtf8(value["name"],colors.white,colors.lightGray)
|
||||
end):injectEvent("char", false, "w"):disable()
|
||||
--frame:addLabel():setText(value["name"]):setPosition(1, 1)
|
||||
frame:addLabel():setText("name:"..value["name"].." id:"..value["id"].." artists:"..value["artists_name"]):setPosition(1, 4)
|
||||
--frame:addLabel():setText("artists: "..value["artists_name"]):setPosition(1, 3)
|
||||
a=a+5
|
||||
end
|
||||
|
||||
break;
|
||||
else
|
||||
frame = GUI_in[3]:addFrame():setPosition(2, 2):setSize("parent.w-2", 3):setBackground(colors.lightBlue)
|
||||
@@ -231,6 +224,13 @@ function Search(input_str,GUI_in,api)
|
||||
end
|
||||
end
|
||||
|
||||
play_Gui[4]:onError(function(self, event, err)
|
||||
|
||||
end)
|
||||
|
||||
play_Gui[4]:onDone(function()
|
||||
|
||||
end)
|
||||
|
||||
-----------------------------------------------------------------渲染界面阶段-------------------------------------------------------------------------------------------------
|
||||
GUI = {
|
||||
@@ -246,18 +246,38 @@ GUI = {
|
||||
},
|
||||
}
|
||||
|
||||
_G.getPlay = nil
|
||||
|
||||
function thread2()
|
||||
while true do
|
||||
--basalt.debug(_G.music168_playopen)
|
||||
--basalt.debug(_G.music168_playopen = false os.queueEvent("music168_play_stop"))
|
||||
local screenWidth, _ = term.getSize()
|
||||
if play_Gui[18]:getIndex() ~=1 then _G.setPlay = (play_Gui[18]:getIndex() / (screenWidth-2)) * 100 play_Gui[18]:setIndex(1) end
|
||||
sleep(0.1)
|
||||
--
|
||||
if _G.getPlay ~= nil then
|
||||
play_Gui[10]:setProgress(_G.getPlay*100)
|
||||
|
||||
-- 处理用户拖动进度条设置播放位置
|
||||
|
||||
w,h = term.getSize()
|
||||
if w >= 100 and h >= 30 then px = "--12px" else px = "--8px" end
|
||||
|
||||
if play_Gui[18]:getIndex() ~=1 then
|
||||
local sliderValue = play_Gui[18]:getValue() or 0
|
||||
_G.setPlay = _G.getPlaymax * (sliderValue / 100)
|
||||
play_Gui[18]:setIndex(1)
|
||||
end
|
||||
|
||||
sleep(0.1)
|
||||
|
||||
-- 更新播放进度条
|
||||
if _G.getPlay ~= nil and _G.getPlaymax ~= nil and _G.getPlaymax > 0 then
|
||||
play_Gui[10]:setProgress((_G.getPlay / _G.getPlaymax) * 100)
|
||||
|
||||
-- 更新当前播放时间显示
|
||||
local current = _G.getPlay or 0
|
||||
local total = _G.getPlaymax or 0
|
||||
local currentTimeStr = string.format("%02d:%02d", math.floor(current / 60), current % 60)
|
||||
local totalTimeStr = string.format("%02d:%02d", math.floor(total / 60), total % 60)
|
||||
|
||||
play_Gui[11]:setText(currentTimeStr) -- 当前播放时间
|
||||
play_Gui[12]:setText(totalTimeStr) -- 总时间
|
||||
end
|
||||
|
||||
if play_data_table["play"]== true then
|
||||
_G.Playstop = false
|
||||
play_Gui[15]:setText("II")
|
||||
@@ -274,13 +294,13 @@ function thread2()
|
||||
index = play_table_Gui[3]:getItemIndex()
|
||||
if play_data_table["play"] then
|
||||
|
||||
shell.run(mypath.."/speaker.lua stop")
|
||||
shell.run(mypath.."/speakerlib.lua stop")
|
||||
if _G.Playopen then
|
||||
|
||||
end
|
||||
play_data_table["play"]=false
|
||||
end
|
||||
_G.music168_playopen = false
|
||||
_G.music168_playopen = false os.queueEvent("music168_play_stop")
|
||||
sleep(0.1)
|
||||
playmusic(play_data_table["play_table"][index]["name"],play_data_table["play_table"][index]["id"],play_data_table["play_table"],index)
|
||||
|
||||
@@ -299,31 +319,55 @@ end
|
||||
|
||||
function speakerp()
|
||||
function speaker_thread()
|
||||
local startTime = os.clock()
|
||||
|
||||
|
||||
--play_time_thread_id = AddThread(function() local time_f = os.date("%M%S") while true do while _G.Playopen do time_f = os.date("%M%S") sleep(0.1) end time_F = os.date("%M%S") play_Gui[11]:setText(string.format("%02d", os.date("*t",time_F-time_f).min or 00)..":"..string.format("%02d", os.date("*t",time_F-time_f).sec or 00) or "00:00") sleep(1) end end)
|
||||
--basalt.debug(mypath)
|
||||
--shell.run(mypath.."/speaker play "..dfpwmURL.readAll())
|
||||
if _G.music168_music_id then
|
||||
--basalt.debug(music168_music_id)
|
||||
|
||||
|
||||
_G.Playopen = true
|
||||
dfpwmURL = http.post("http://gmapi.liulikeji.cn:15842/dfpwm",textutils.serialiseJSON({ ["url"] = GetmusicUrl(_G.music168_music_id) } ))
|
||||
shell.run(mypath.."/speaker play "..dfpwmURL.readAll())
|
||||
play_Gui[4]:stop()
|
||||
|
||||
play_Gui[4]:execute(function ()
|
||||
shell.run(mypath.."/MusicLyrics.lua http://music168.liulikeji.cn:15843/api/song/lyric?id=".._G.music168_music_id.." "..px)
|
||||
end)
|
||||
play_Gui[4]:injectEvent("char","w")
|
||||
sleep(0.1)
|
||||
|
||||
--dfpwmURL = http.post("http://gmapi.liulikeji.cn:15842/dfpwm",textutils.serialiseJSON({ ["url"] = GetmusicUrl(_G.music168_music_id) } ))
|
||||
shell.run(mypath.."/speakerlib.lua play "..GetmusicUrl(_G.music168_music_id))
|
||||
-- 检查是否播放完成自动跳转下一首
|
||||
if _G.music168_playopen then
|
||||
play_set_0()
|
||||
end
|
||||
|
||||
play_Gui[4]:stop()
|
||||
|
||||
end
|
||||
function while_thread() while _G.music168_playopen do sleep(0.01) end end
|
||||
end
|
||||
end
|
||||
|
||||
function while_thread()
|
||||
os.pullEvent("music168_play_stop")
|
||||
_G.getPlay = 0
|
||||
_G.getPlaymax = 0
|
||||
play_Gui[4]:stop()
|
||||
end
|
||||
|
||||
while true do
|
||||
|
||||
if _G.music168_playopen then parallel.waitForAny(speaker_thread, while_thread) end
|
||||
if _G.music168_playopen then
|
||||
parallel.waitForAny(speaker_thread, while_thread)
|
||||
sleep(0.1)
|
||||
end
|
||||
sleep(0.01)
|
||||
end
|
||||
end
|
||||
|
||||
_G.music168_playopen = false
|
||||
function gc()
|
||||
while true do
|
||||
play_Gui[4]:injectEvent(os.pullEvent())
|
||||
end
|
||||
|
||||
end
|
||||
_G.music168_playopen = false os.queueEvent("music168_play_stop")
|
||||
-----------------------------------------------------------------启动循环渲染器-----------------------------------------------------------------------------------------------
|
||||
parallel.waitForAll(basalt.autoUpdate, thread2, paste, speakerp)
|
||||
parallel.waitForAll(basalt.autoUpdate, thread2, paste, speakerp,gc)
|
||||
-----------------------------------------------------------------以下结束-----------------------------------------------------------------------------------------------------
|
||||
254
speaker.lua
254
speaker.lua
@@ -1,254 +0,0 @@
|
||||
if _G.Playprint == nil then _G.Playprint = true end
|
||||
local function get_speakers(name)
|
||||
if name then
|
||||
local speaker = peripheral.wrap(name)
|
||||
if speaker == nil then
|
||||
error(("Speaker %q does not exist"):format(name), 0)
|
||||
return
|
||||
elseif not peripheral.hasType(name, "speaker") then
|
||||
error(("%q is not a speaker"):format(name), 0)
|
||||
end
|
||||
|
||||
return { speaker }
|
||||
else
|
||||
local speakers = { peripheral.find("speaker") }
|
||||
if #speakers == 0 then
|
||||
error("No speakers attached", 0)
|
||||
end
|
||||
return speakers
|
||||
end
|
||||
end
|
||||
function spekerStop()
|
||||
local speakers = { peripheral.find("speaker") }
|
||||
for _, speaker in pairs(speakers) do
|
||||
speaker.stop()
|
||||
end
|
||||
end
|
||||
|
||||
function speakerPlay(buffer)
|
||||
local speakers = { peripheral.find("speaker") }
|
||||
for _, speaker in pairs(speakers) do
|
||||
a = speaker.playAudio(buffer)
|
||||
end
|
||||
return a
|
||||
end
|
||||
|
||||
|
||||
local function pcm_decoder(chunk)
|
||||
local buffer = {}
|
||||
for i = 1, #chunk do
|
||||
buffer[i] = chunk:byte(i) - 128
|
||||
end
|
||||
return buffer
|
||||
end
|
||||
|
||||
|
||||
function displayProgressBar(percent)
|
||||
term.setCursorPos(1, 1)
|
||||
local screenWidth, _ = term.getSize() -- 获取终端的宽度和高度
|
||||
local barLength = math.floor(screenWidth - 8) -- 进度条长度为屏幕宽度减去固定长度(用于百分比显示)
|
||||
|
||||
local numBars = math.floor(percent / (100 / barLength))
|
||||
|
||||
-- 构建进度条字符串
|
||||
local progressBar = "["
|
||||
for i = 1, barLength do
|
||||
if i <= numBars then
|
||||
progressBar = progressBar .. "="
|
||||
else
|
||||
progressBar = progressBar .. " "
|
||||
end
|
||||
end
|
||||
progressBar = progressBar .. "] " .. math.floor(percent) .. "%" -- 百分比不显示小数点
|
||||
|
||||
-- 清空屏幕并输出进度条到屏幕顶部
|
||||
|
||||
term.setCursorPos(1, 3)
|
||||
print(progressBar)
|
||||
end
|
||||
|
||||
-- 测试函数
|
||||
|
||||
|
||||
|
||||
|
||||
local cmd = ...
|
||||
if cmd == "stop" then
|
||||
_G.Playopen = false
|
||||
local speakers = { peripheral.find("speaker") }
|
||||
for _, speaker in pairs(speakers) do
|
||||
speaker.stop()
|
||||
end
|
||||
spekerStop()
|
||||
elseif cmd == "play" then
|
||||
local _, file, type = ...
|
||||
|
||||
local handle, err
|
||||
if http and file:match("^https?://") then
|
||||
if type == "mp3" then
|
||||
if _G.Playprint then print("mp3 > dfpwm.....") end
|
||||
local json = textutils.serialiseJSON({ ["url"] = file } )
|
||||
handle, err = http.get{ url = http.post("http://gmapi.liulikeji.cn:15842/dfpwm",json).readAll(), binary = true }
|
||||
else
|
||||
handle, err = http.get{ url = file, binary = true }
|
||||
end
|
||||
else
|
||||
handle, err = fs.open(file, "rb")
|
||||
end
|
||||
|
||||
if not handle then
|
||||
error(err, 0)
|
||||
end
|
||||
|
||||
local start = handle.read(4)
|
||||
local pcm = false
|
||||
local size = 16 * 1024 - 4
|
||||
if start == "RIFF" then
|
||||
handle.read(4)
|
||||
if handle.read(8) ~= "WAVEfmt " then
|
||||
handle.close()
|
||||
error("Could not play audio: Unsupported WAV file", 0)
|
||||
end
|
||||
|
||||
local fmtsize = ("<I4"):unpack(handle.read(4))
|
||||
local fmt = handle.read(fmtsize)
|
||||
local format, channels, rate, _, _, bits = ("<I2I2I4I4I2I2"):unpack(fmt)
|
||||
if not ((format == 1 and bits == 8) or (format == 0xFFFE and bits == 1)) then
|
||||
handle.close()
|
||||
error("Could not play audio: Unsupported WAV file", 0)
|
||||
end
|
||||
if channels ~= 1 or rate ~= 48000 then
|
||||
end
|
||||
if format == 0xFFFE then
|
||||
local guid = fmt:sub(25)
|
||||
if guid ~= "\x3A\xC1\xFA\x38\x81\x1D\x43\x61\xA4\x0D\xCE\x53\xCA\x60\x7C\xD1" then -- DFPWM format GUID
|
||||
handle.close()
|
||||
error("Could not play audio: Unsupported WAV file", 0)
|
||||
end
|
||||
size = size + 4
|
||||
else
|
||||
pcm = true
|
||||
size = 16 * 1024 * 8
|
||||
end
|
||||
|
||||
repeat
|
||||
local chunk = handle.read(4)
|
||||
if chunk == nil then
|
||||
handle.close()
|
||||
error("Could not play audio: Invalid WAV file", 0)
|
||||
elseif chunk ~= "data" then -- Ignore extra chunks
|
||||
local size = ("<I4"):unpack(handle.read(4))
|
||||
handle.read(size)
|
||||
end
|
||||
until chunk == "data"
|
||||
|
||||
handle.read(4)
|
||||
start = nil
|
||||
end
|
||||
|
||||
|
||||
local decoder = pcm and pcm_decoder or require "cc.audio.dfpwm".make_decoder()
|
||||
local b1=true
|
||||
achunk_1 = handle.readAll()
|
||||
local achunk_s = achunk_1
|
||||
local achunk_K = #achunk_1
|
||||
whilecs_1 = 0
|
||||
_G.setPlay = nil
|
||||
|
||||
function play1()
|
||||
_G.Playopen = true
|
||||
|
||||
_G.Playstop = false
|
||||
c1=true
|
||||
|
||||
while _G.Playopen do
|
||||
|
||||
if _G.Playstop then
|
||||
local speakers = { peripheral.find("speaker") }
|
||||
for _, speaker in pairs(speakers) do
|
||||
speaker.stop()
|
||||
end
|
||||
|
||||
if _G.Playprint then print("play stop....") end
|
||||
while _G.Playstop do sleep(0.1) end
|
||||
b1=true
|
||||
c1=false
|
||||
end
|
||||
|
||||
--local chunk = handle.read(size)
|
||||
if c1 then
|
||||
chunk = achunk_1:sub(0,size)
|
||||
achunk_1 = achunk_1:sub(size+1,-1)
|
||||
|
||||
local achunk_ZK = achunk_K / size
|
||||
|
||||
if _G.setPlay ~= nil then
|
||||
local speakers = { peripheral.find("speaker") }
|
||||
for _, speaker in pairs(speakers) do
|
||||
speaker.stop()
|
||||
end
|
||||
whilecs_1 = math.floor((setPlay / 100) * achunk_ZK)
|
||||
|
||||
achunk_1 = achunk_s:sub(size*whilecs_1,-1)
|
||||
chunk = achunk_1:sub(0,size)
|
||||
achunk_1 = achunk_1:sub(size+1,-1)
|
||||
_G.setPlay = nil
|
||||
b1 = true
|
||||
end
|
||||
|
||||
local f = whilecs_1 / achunk_ZK
|
||||
_G.getPlay = f
|
||||
if _G.Playprint then
|
||||
term.clear()
|
||||
displayProgressBar(f*100)
|
||||
print(whilecs_1)
|
||||
print(achunk_ZK)
|
||||
print(f)
|
||||
end
|
||||
|
||||
whilecs_1 = whilecs_1+1
|
||||
|
||||
if f >= 1 then break end
|
||||
|
||||
if chunk == nil then break end
|
||||
|
||||
if start then
|
||||
chunk, start = start .. chunk, nil
|
||||
size = size + 4
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
local buffer = decoder(chunk)
|
||||
if b1 then
|
||||
speakerPlay(buffer)
|
||||
b1=false
|
||||
c1 = true
|
||||
|
||||
else
|
||||
|
||||
while setPlay==nil and _G.Playstop==false do
|
||||
local speakers = { peripheral.find("speaker") }
|
||||
for i,speaker in pairs(speakers) do
|
||||
os.pullEvent("speaker_audio_empty")
|
||||
end
|
||||
speakerPlay(buffer)
|
||||
break
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
_G.getPlay=nil
|
||||
end
|
||||
|
||||
|
||||
play1()
|
||||
|
||||
|
||||
spekerStop()
|
||||
|
||||
handle.close()
|
||||
else
|
||||
local programName = arg[0] or fs.getName(shell.getRunningProgram())
|
||||
end
|
||||
383
speakerlib.lua
Normal file
383
speakerlib.lua
Normal file
@@ -0,0 +1,383 @@
|
||||
-- SPDX-FileCopyrightText: 2021 The CC: Tweaked Developers
|
||||
--
|
||||
-- SPDX-License-Identifier: MPL-2.0
|
||||
|
||||
-- 全局控制变量
|
||||
_G.getPlaymax = 0 -- 总时间(秒)
|
||||
_G.getPlay = 0 -- 当前播放时间(秒)
|
||||
_G.setPlay = 0 -- 设置播放进度(秒)
|
||||
_G.Playopen = true -- 播放开关(false停止)
|
||||
_G.Playstop = false -- 暂停控制(true暂停,false恢复)
|
||||
_G.Playprint = false -- 信息输出开关(true开,false关)
|
||||
_G.setVolume = 1 -- 音量控制(0-3)
|
||||
|
||||
local API_URL = "http://newgmapi.liulikeji.cn/api/ffmpeg"
|
||||
local mypath = "/"..fs.getDir(shell.getRunningProgram())
|
||||
|
||||
-- 扬声器配置
|
||||
local speakerlist = {
|
||||
main = {},
|
||||
left = {},
|
||||
right = {}
|
||||
}
|
||||
|
||||
local function printlog(...)
|
||||
if _G.Playprint then
|
||||
print(...)
|
||||
end
|
||||
end
|
||||
|
||||
local function loadSpeakerConfig()
|
||||
local speaker_groups = fs.open(mypath.."/speaker_groups.cfg","r")
|
||||
if speaker_groups then
|
||||
local content = speaker_groups.readAll()
|
||||
speaker_groups.close()
|
||||
if content then
|
||||
local success, tableData = pcall(textutils.unserialise, content)
|
||||
if success and type(tableData) == "table" then
|
||||
speakerlist = { main = {}, left = {}, right = {} }
|
||||
for group_name, speakers in pairs(tableData) do
|
||||
if speakerlist[group_name] then
|
||||
for _, speaker_name in ipairs(speakers) do
|
||||
local speaker = peripheral.wrap(speaker_name)
|
||||
if speaker and peripheral.hasType(speaker_name, "speaker") then
|
||||
table.insert(speakerlist[group_name], speaker)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- 默认配置:所有扬声器都在main组
|
||||
speakerlist = {
|
||||
main = { peripheral.find("speaker") },
|
||||
left = {},
|
||||
right = {}
|
||||
}
|
||||
end
|
||||
|
||||
local function Get_dfpwm_url(INPUT_URL, args)
|
||||
local requestData = {
|
||||
input_url = INPUT_URL,
|
||||
args = args,
|
||||
output_format = "dfpwm"
|
||||
}
|
||||
|
||||
local response, err = http.post(
|
||||
API_URL,
|
||||
textutils.serializeJSON(requestData),
|
||||
{ ["Content-Type"] = "application/json" }
|
||||
)
|
||||
|
||||
if not response then
|
||||
error("HTTP Request Failure: "..(err or "Unknown error"))
|
||||
end
|
||||
|
||||
local responseData = textutils.unserializeJSON(response.readAll())
|
||||
response.close()
|
||||
|
||||
if responseData.status ~= "success" then
|
||||
error("Conversion failed: "..(responseData.error or "Unknown error"))
|
||||
end
|
||||
|
||||
return responseData.download_url
|
||||
end
|
||||
|
||||
local function get_total_duration(url)
|
||||
if _G.Playprint then printlog("Calculating duration...") end
|
||||
local handle, err = http.get(url)
|
||||
if not handle then
|
||||
error("Could not get duration: " .. (err or "Unknown error"))
|
||||
end
|
||||
|
||||
local data = handle.readAll()
|
||||
handle.close()
|
||||
|
||||
-- DFPWM: 每字节8个样本,48000采样率
|
||||
local total_length = (#data * 8) / 48000
|
||||
return total_length, #data
|
||||
end
|
||||
|
||||
local function play_audio_chunk(speakers, buffer)
|
||||
if #speakers > 0 and buffer and #buffer > 0 then
|
||||
for _, speaker in pairs(speakers) do
|
||||
local success = false
|
||||
while not success and _G.Playopen do
|
||||
success = speaker.playAudio(buffer, _G.setVolume)
|
||||
if not success then
|
||||
os.pullEvent("speaker_audio_empty")
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local cmd = ...
|
||||
|
||||
if cmd == "stop" then
|
||||
local all_speakers = {}
|
||||
for _, group in pairs(speakerlist) do
|
||||
for _, speaker in pairs(group) do
|
||||
table.insert(all_speakers, speaker)
|
||||
end
|
||||
end
|
||||
|
||||
for _, speaker in pairs(all_speakers) do
|
||||
speaker.stop()
|
||||
end
|
||||
elseif cmd == "play" then
|
||||
local _, file = ...
|
||||
if not file then
|
||||
error("Usage: speaker play <url>", 0)
|
||||
end
|
||||
|
||||
if not http or not file:match("^https?://") then
|
||||
error("Only HTTP/HTTPS URLs are supported", 0)
|
||||
end
|
||||
|
||||
-- 加载扬声器配置
|
||||
loadSpeakerConfig()
|
||||
|
||||
-- 检查是否有扬声器
|
||||
local has_speakers = false
|
||||
for _, group in pairs(speakerlist) do
|
||||
if #group > 0 then
|
||||
has_speakers = true
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
if not has_speakers then
|
||||
error("No speakers attached", 0)
|
||||
end
|
||||
|
||||
-- 获取DFPWM转换URL
|
||||
local main_dfpwm_url, left_dfpwm_url, right_dfpwm_url
|
||||
local main_httpfile, left_httpfile, right_httpfile
|
||||
|
||||
if _G.Playprint then printlog("Converting audio...") end
|
||||
|
||||
if #speakerlist.main > 0 then
|
||||
main_dfpwm_url = Get_dfpwm_url(file, { "-vn", "-ar", "48000", "-ac", "1" })
|
||||
end
|
||||
|
||||
if #speakerlist.left > 0 then
|
||||
left_dfpwm_url = Get_dfpwm_url(file, { "-vn", "-ar", "48000", "-filter_complex", "pan=mono|c0=FL" })
|
||||
end
|
||||
|
||||
if #speakerlist.right > 0 then
|
||||
right_dfpwm_url = Get_dfpwm_url(file, { "-vn", "-ar", "48000", "-filter_complex", "pan=mono|c0=FR" })
|
||||
end
|
||||
|
||||
-- 计算总时长(使用任意一个通道)
|
||||
local total_length, total_size
|
||||
if main_dfpwm_url then
|
||||
total_length, total_size = get_total_duration(main_dfpwm_url)
|
||||
elseif left_dfpwm_url then
|
||||
total_length, total_size = get_total_duration(left_dfpwm_url)
|
||||
elseif right_dfpwm_url then
|
||||
total_length, total_size = get_total_duration(right_dfpwm_url)
|
||||
else
|
||||
error("No audio channels available", 0)
|
||||
end
|
||||
|
||||
-- 设置总时间
|
||||
_G.getPlaymax = total_length
|
||||
_G.getPlay = 0
|
||||
|
||||
if _G.Playprint then
|
||||
printlog("Playing " .. file .. " (" .. math.ceil(total_length) .. "s)")
|
||||
end
|
||||
|
||||
-- 创建HTTP连接
|
||||
if main_dfpwm_url then
|
||||
main_httpfile = http.get(main_dfpwm_url)
|
||||
if not main_httpfile then
|
||||
error("Could not open main audio stream")
|
||||
end
|
||||
end
|
||||
|
||||
if left_dfpwm_url then
|
||||
left_httpfile = http.get(left_dfpwm_url)
|
||||
if not left_httpfile then
|
||||
error("Could not open left audio stream")
|
||||
end
|
||||
end
|
||||
|
||||
if right_dfpwm_url then
|
||||
right_httpfile = http.get(right_dfpwm_url)
|
||||
if not right_httpfile then
|
||||
error("Could not open right audio stream")
|
||||
end
|
||||
end
|
||||
|
||||
-- 初始化DFPWM解码器
|
||||
local decoder = require "cc.audio.dfpwm".make_decoder()
|
||||
local left_decoder = require "cc.audio.dfpwm".make_decoder()
|
||||
local right_decoder = require "cc.audio.dfpwm".make_decoder()
|
||||
|
||||
-- 每次读取的字节数(DFPWM: 每秒6000字节)
|
||||
local chunk_size = 6000
|
||||
local bytes_read = 0
|
||||
|
||||
-- 初始化播放位置
|
||||
if _G.setPlay > 0 then
|
||||
local skip_bytes = math.floor(_G.setPlay * 6000)
|
||||
if skip_bytes < total_size then
|
||||
-- 跳过指定字节数
|
||||
local skipped = 0
|
||||
while skipped < skip_bytes and _G.Playopen do
|
||||
local to_skip = math.min(8192, skip_bytes - skipped)
|
||||
if main_httpfile then main_httpfile.read(to_skip) end
|
||||
if left_httpfile then left_httpfile.read(to_skip) end
|
||||
if right_httpfile then right_httpfile.read(to_skip) end
|
||||
skipped = skipped + to_skip
|
||||
bytes_read = bytes_read + to_skip
|
||||
end
|
||||
_G.getPlay = _G.setPlay
|
||||
_G.setPlay = 0
|
||||
end
|
||||
end
|
||||
|
||||
-- 主播放循环
|
||||
while bytes_read < total_size and _G.Playopen do
|
||||
-- 检查是否需要设置播放位置
|
||||
if _G.setPlay > 0 then
|
||||
-- 重新打开所有连接并跳转
|
||||
if main_httpfile then main_httpfile.close() end
|
||||
if left_httpfile then left_httpfile.close() end
|
||||
if right_httpfile then right_httpfile.close() end
|
||||
|
||||
if main_dfpwm_url then
|
||||
main_httpfile = http.get(main_dfpwm_url)
|
||||
if not main_httpfile then error("Could not reopen main stream") end
|
||||
end
|
||||
|
||||
if left_dfpwm_url then
|
||||
left_httpfile = http.get(left_dfpwm_url)
|
||||
if not left_httpfile then error("Could not reopen left stream") end
|
||||
end
|
||||
|
||||
if right_dfpwm_url then
|
||||
right_httpfile = http.get(right_dfpwm_url)
|
||||
if not right_httpfile then error("Could not reopen right stream") end
|
||||
end
|
||||
|
||||
local skip_bytes = math.floor(_G.setPlay * 6000)
|
||||
if skip_bytes < total_size then
|
||||
local skipped = 0
|
||||
while skipped < skip_bytes and _G.Playopen do
|
||||
local to_skip = math.min(8192, skip_bytes - skipped)
|
||||
if main_httpfile then main_httpfile.read(to_skip) end
|
||||
if left_httpfile then left_httpfile.read(to_skip) end
|
||||
if right_httpfile then right_httpfile.read(to_skip) end
|
||||
skipped = skipped + to_skip
|
||||
bytes_read = skip_bytes
|
||||
end
|
||||
_G.getPlay = _G.setPlay
|
||||
_G.setPlay = 0
|
||||
end
|
||||
end
|
||||
|
||||
-- 检查暂停状态
|
||||
while _G.Playstop and _G.Playopen do
|
||||
os.sleep(0.1)
|
||||
end
|
||||
|
||||
-- 检查停止状态
|
||||
if not _G.Playopen then
|
||||
break
|
||||
end
|
||||
|
||||
-- 读取音频数据
|
||||
local main_chunk, left_chunk, right_chunk
|
||||
local main_buffer, left_buffer, right_buffer
|
||||
|
||||
if main_httpfile then
|
||||
main_chunk = main_httpfile.read(chunk_size)
|
||||
end
|
||||
|
||||
if left_httpfile then
|
||||
left_chunk = left_httpfile.read(chunk_size)
|
||||
end
|
||||
|
||||
if right_httpfile then
|
||||
right_chunk = right_httpfile.read(chunk_size)
|
||||
end
|
||||
|
||||
-- 检查是否所有通道都没有数据
|
||||
if (not main_chunk or #main_chunk == 0) and
|
||||
(not left_chunk or #left_chunk == 0) and
|
||||
(not right_chunk or #right_chunk == 0) then
|
||||
break
|
||||
end
|
||||
|
||||
-- 解码音频数据
|
||||
if main_chunk and #main_chunk > 0 then
|
||||
main_buffer = decoder(main_chunk)
|
||||
end
|
||||
|
||||
if left_chunk and #left_chunk > 0 then
|
||||
left_buffer = left_decoder(left_chunk)
|
||||
end
|
||||
|
||||
if right_chunk and #right_chunk > 0 then
|
||||
right_buffer = right_decoder(right_chunk)
|
||||
end
|
||||
|
||||
-- 并行播放所有通道
|
||||
parallel.waitForAll(
|
||||
function()
|
||||
if main_buffer and #main_buffer > 0 then
|
||||
play_audio_chunk(speakerlist.main, main_buffer)
|
||||
end
|
||||
end,
|
||||
function()
|
||||
if right_buffer and #right_buffer > 0 then
|
||||
play_audio_chunk(speakerlist.right, right_buffer)
|
||||
end
|
||||
end,
|
||||
function()
|
||||
if left_buffer and #left_buffer > 0 then
|
||||
play_audio_chunk(speakerlist.left, left_buffer)
|
||||
end
|
||||
end
|
||||
)
|
||||
|
||||
-- 更新进度
|
||||
local max_chunk_size = math.max(
|
||||
main_chunk and #main_chunk or 0,
|
||||
left_chunk and #left_chunk or 0,
|
||||
right_chunk and #right_chunk or 0
|
||||
)
|
||||
bytes_read = bytes_read + max_chunk_size
|
||||
_G.getPlay = bytes_read / 6000
|
||||
|
||||
if _G.Playprint then
|
||||
term.setCursorPos(1, term.getCursorPos())
|
||||
printlog(("Playing: %ds / %ds"):format(math.floor(_G.getPlay), math.ceil(total_length)))
|
||||
end
|
||||
end
|
||||
|
||||
-- 关闭HTTP连接
|
||||
if main_httpfile then main_httpfile.close() end
|
||||
if left_httpfile then left_httpfile.close() end
|
||||
if right_httpfile then right_httpfile.close() end
|
||||
|
||||
if _G.Playprint and _G.Playopen then
|
||||
printlog("Playback finished.")
|
||||
end
|
||||
|
||||
-- 重置播放状态
|
||||
_G.Playopen = true
|
||||
_G.Playstop = false
|
||||
_G.getPlay = 0
|
||||
else
|
||||
local programName = arg[0] or fs.getName(shell.getRunningProgram())
|
||||
printlog("Usage:")
|
||||
printlog(programName .. " play <url>")
|
||||
printlog(programName .. " stop")
|
||||
end
|
||||
Reference in New Issue
Block a user