Merge branch 'pkgver' of https://gitee.com/EillesWan/Musicreater into pkgver

This commit is contained in:
EillesWan 2022-12-31 13:20:32 +08:00
commit fba83ef968

View File

@ -61,7 +61,7 @@ def makeZip(sourceDir, outFilename, compression=8, exceptFile=None):
class SingleNote: class SingleNote:
def __init__(self, instrument: int, pitch: int, velocity, startTime, lastTime): def __init__(self, instrument: int, pitch: int, velocity, startTime, lastTime):
"""用于存储单个音符的类 """用于存储单个音符的类
:param inst 乐器编号 :param instrument 乐器编号
:param pitch 音符编号 :param pitch 音符编号
:param velocity 力度/响度 :param velocity 力度/响度
:param startTime 开始之时(ms) :param startTime 开始之时(ms)
@ -155,7 +155,7 @@ class midiConvert:
"""MidiFile对象""" """MidiFile对象"""
except Exception as E: except Exception as E:
raise MidiDestroyedError(f"文件{self.midiFile}损坏:{E}") raise MidiDestroyedError(f"文件{self.midiFile}损坏:{E}")
self.outputPath = os.path.abspath(outputPath) self.outputPath = os.path.abspath(outputPath)
"""输出路径""" """输出路径"""
# 将self.midiFile的文件名不含路径且不含后缀存入self.midiFileName # 将self.midiFile的文件名不含路径且不含后缀存入self.midiFileName
@ -320,13 +320,13 @@ class midiConvert:
return str(int(int(score / 20) / 60)) + ":" + str(int(int(score / 20) % 60)) return str(int(int(score / 20) / 60)) + ":" + str(int(int(score / 20) % 60))
def __formProgressBar( def __formProgressBar(
self, self,
maxscore: int, maxscore: int,
scoreboardname: str, scoreboardname: str,
progressbar: tuple = ( progressbar: tuple = (
r"%%N [ %%s/%^s %%% __________ %%t|%^t ]", r"%%N [ %%s/%^s %%% __________ %%t|%^t ]",
("§e=§r", "§7=§r"), ("§e=§r", "§7=§r"),
), ),
) -> list: ) -> list:
pgsstyle = progressbar[0] pgsstyle = progressbar[0]
@ -345,7 +345,7 @@ class midiConvert:
""" """
def __replace( def __replace(
s: str, tobeReplaced: str, replaceWith: str, times: int, other: str s: str, tobeReplaced: str, replaceWith: str, times: int, other: str
): ):
if times == 0: if times == 0:
return s.replace(tobeReplaced, other) return s.replace(tobeReplaced, other)
@ -420,16 +420,16 @@ class midiConvert:
return finalprgsbar return finalprgsbar
def __formCMDblk( def __formCMDblk(
self, self,
command: str, command: str,
particularValue: int, particularValue: int,
impluse: int = 0, impluse: int = 0,
condition: bool = False, condition: bool = False,
needRedstone: bool = True, needRedstone: bool = True,
tickDelay: int = 0, tickDelay: int = 0,
customName: str = "", customName: str = "",
executeOnFirstTick: bool = False, executeOnFirstTick: bool = False,
trackOutput: bool = True, trackOutput: bool = True,
): ):
""" """
使用指定项目返回指定的指令方块放置指令项 使用指定项目返回指定的指令方块放置指令项
@ -492,7 +492,7 @@ class midiConvert:
return block return block
def _toCmdList_m1( def _toCmdList_m1(
self, scoreboardname: str = "mscplay", volume: float = 1.0, speed: float = 1.0 self, scoreboardname: str = "mscplay", volume: float = 1.0, speed: float = 1.0
) -> list: ) -> list:
""" """
使用Dislink Sforza的转换思路将midi转换为我的世界命令列表 使用Dislink Sforza的转换思路将midi转换为我的世界命令列表
@ -518,14 +518,13 @@ class midiConvert:
for msg in track: for msg in track:
ticks += msg.time ticks += msg.time
# print(msg)
if msg.is_meta: if msg.is_meta:
if msg.type == "set_tempo": if msg.type == "set_tempo":
tempo = msg.tempo tempo = msg.tempo
else: else:
if msg.type == "program_change": if msg.type == "program_change":
# print("TT")
instrumentID = msg.program instrumentID = msg.program
if msg.type == "note_on" and msg.velocity != 0: if msg.type == "note_on" and msg.velocity != 0:
try: try:
nowscore = round( nowscore = round(
@ -536,13 +535,26 @@ class midiConvert:
raise NotDefineTempoError("计算当前分数时出错 未定义参量 Tempo") raise NotDefineTempoError("计算当前分数时出错 未定义参量 Tempo")
maxscore = max(maxscore, nowscore) maxscore = max(maxscore, nowscore)
soundID, _X = self.__Inst2soundIDwithX(instrumentID) soundID, _X = self.__Inst2soundIDwithX(instrumentID)
# /playsound <sound: string> [player: target] [position: x y z]
# [volume: float] [pitch: float] [minimumVolume: float]
# volume_d = 1 / volume - 1
# if volume_d == 0.0:
# volume_d = ""
# command_now = "playsound {0} @a[scores={{{1}}}] ~ ~{2} ~ {3} {4}" \
# .format(soundID, "{}={}".format(scoreboardname,
# nowscore), volume_d,
# msg.velocity, 2 ** ((msg.note - 60 - _X) / 12))
# singleTrack.append(command_now)
singleTrack.append( singleTrack.append(
"execute @a[scores={" "execute @a[scores={"
+ str(scoreboardname) + str(scoreboardname)
+ "=" + "="
+ str(nowscore) + str(nowscore)
+ "}" + "}"
+ f"] ~ ~ ~ playsound {soundID} @s ~ ~{1 / volume - 1} ~ {msg.velocity * (0.7 if msg.channel == 0 else 0.9)} {2 ** ((msg.note - 60 - _X) / 12)}" + f"] ~ ~ ~ playsound {soundID} @s ~ ~{1 / volume - 1} ~ "
f"{msg.velocity * (0.7 if msg.channel == 0 else 0.9)} {2 ** ((msg.note - 60 - _X) / 12)}"
) )
commands += 1 commands += 1
if len(singleTrack) != 0: if len(singleTrack) != 0:
@ -553,10 +565,10 @@ class midiConvert:
# 原本这个算法的转换效果应该和上面的算法相似的 # 原本这个算法的转换效果应该和上面的算法相似的
# 但不好意思 我增加了泛音功能 # 但不好意思 我增加了泛音功能
def _toCmdList_m2( def _toCmdList_m2(
self, self,
scoreboardname: str = "mscplay", scoreboardname: str = "mscplay",
MaxVolume: float = 1.0, MaxVolume: float = 1.0,
speed: float = 1.0, speed: float = 1.0,
) -> list: ) -> list:
""" """
使用金羿的转换思路将midi转换为我的世界命令列表 使用金羿的转换思路将midi转换为我的世界命令列表
@ -612,7 +624,7 @@ class midiConvert:
) )
elif (msg.type == "note_on" and msg.velocity == 0) or ( elif (msg.type == "note_on" and msg.velocity == 0) or (
msg.type == "note_off" msg.type == "note_off"
): ):
channels[msg.channel].append(("NoteE", msg.note, microseconds)) channels[msg.channel].append(("NoteE", msg.note, microseconds))
@ -687,10 +699,10 @@ class midiConvert:
# 已经经过验证 需要再次修改 # 已经经过验证 需要再次修改
# 等一段时间后我来通知 # 等一段时间后我来通知
def _toCmdList_m3( def _toCmdList_m3(
self, self,
scoreboardname: str = "mscplay", scoreboardname: str = "mscplay",
MaxVolume: float = 1.0, MaxVolume: float = 1.0,
speed: float = 1.0, speed: float = 1.0,
) -> list: ) -> list:
""" """
使用金羿的转换思路将midi转换为我的世界命令列表并使用线性插值算法优化音量 使用金羿的转换思路将midi转换为我的世界命令列表并使用线性插值算法优化音量
@ -746,7 +758,7 @@ class midiConvert:
) )
elif (msg.type == "note_on" and msg.velocity == 0) or ( elif (msg.type == "note_on" and msg.velocity == 0) or (
msg.type == "note_off" msg.type == "note_off"
): ):
channels[msg.channel].append(("NoteE", msg.note, microseconds)) channels[msg.channel].append(("NoteE", msg.note, microseconds))
@ -797,7 +809,6 @@ class midiConvert:
noteMsgs.pop(MsgIndex.index(msg[1])) noteMsgs.pop(MsgIndex.index(msg[1]))
MsgIndex.pop(MsgIndex.index(msg[1])) MsgIndex.pop(MsgIndex.index(msg[1]))
tracks = [] tracks = []
cmdAmount = 0 cmdAmount = 0
maxScore = 0 maxScore = 0
@ -808,14 +819,15 @@ class midiConvert:
'''传入音符数据,返回以半秒为分割的插值列表 '''传入音符数据,返回以半秒为分割的插值列表
:param note: SingleNote 音符 :param note: SingleNote 音符
:return list[tuple(int开始时间毫秒, int乐器, int音符, int力度内置, float音量播放),]''' :return list[tuple(int开始时间毫秒, int乐器, int音符, int力度内置, float音量播放),]'''
result = [] result = []
totalCount = int(note.lastTime / 500000) totalCount = int(note.lastTime / 500000)
for i in range(totalCount): for i in range(totalCount):
result.append((note.startTime+i*500000,note.instrument,note.pitch,note.velocity,MaxVolume*((totalCount-i)/totalCount))) result.append((note.startTime + i * 500000, note.instrument, note.pitch, note.velocity,
MaxVolume * ((totalCount - i) / totalCount)))
return result return result
# 此处 我们把通道视为音轨 # 此处 我们把通道视为音轨
@ -834,7 +846,6 @@ class midiConvert:
for note in track: for note in track:
for everynote in _linearFun(note): for everynote in _linearFun(note):
# 应该是计算的时候出了点小问题 # 应该是计算的时候出了点小问题
# 我们应该用一个MC帧作为时间单位而不是半秒 # 我们应该用一个MC帧作为时间单位而不是半秒
@ -861,11 +872,11 @@ class midiConvert:
return [tracks, cmdAmount, maxScore] return [tracks, cmdAmount, maxScore]
def _toCmdList_withDelay_m1( def _toCmdList_withDelay_m1(
self, self,
volume: float = 1.0, volume: float = 1.0,
speed: float = 1.0, speed: float = 1.0,
player: str = "@a", player: str = "@a",
isMixedWithPrograssBar=False, isMixedWithPrograssBar=False,
) -> list: ) -> list:
""" """
使用Dislink Sforza的转换思路将midi转换为我的世界命令列表并输出每个音符之后的延迟 使用Dislink Sforza的转换思路将midi转换为我的世界命令列表并输出每个音符之后的延迟
@ -937,7 +948,7 @@ class midiConvert:
""" """
def __replace( def __replace(
s: str, tobeReplaced: str, replaceWith: str, times: int, other: str s: str, tobeReplaced: str, replaceWith: str, times: int, other: str
): ):
if times == 0: if times == 0:
return s.replace(tobeReplaced, other) return s.replace(tobeReplaced, other)
@ -1038,13 +1049,13 @@ class midiConvert:
return math.ceil(math.sqrt(math.ceil(total / maxHeight))) return math.ceil(math.sqrt(math.ceil(total / maxHeight)))
def tomcpack( def tomcpack(
self, self,
method: int = 1, method: int = 1,
isAutoReset: bool = False, isAutoReset: bool = False,
progressbar=None, progressbar=None,
scoreboardname: str = "mscplay", scoreboardname: str = "mscplay",
volume: float = 1.0, volume: float = 1.0,
speed: float = 1.0, speed: float = 1.0,
) -> bool or tuple: ) -> bool or tuple:
""" """
使用method指定的转换算法将midi转换为我的世界mcpack格式的包 使用method指定的转换算法将midi转换为我的世界mcpack格式的包
@ -1057,7 +1068,6 @@ class midiConvert:
:return 成功与否成功返回(True,True)失败返回(False,str失败原因) :return 成功与否成功返回(True,True)失败返回(False,str失败原因)
""" """
# try: # try:
cmdlist, maxlen, maxscore = self.methods[method - 1]( cmdlist, maxlen, maxscore = self.methods[method - 1](
scoreboardname, volume, speed scoreboardname, volume, speed
@ -1073,7 +1083,7 @@ class midiConvert:
# 写入manifest.json # 写入manifest.json
if not os.path.exists(f"{self.outputPath}/temp/manifest.json"): if not os.path.exists(f"{self.outputPath}/temp/manifest.json"):
with open( with open(
f"{self.outputPath}/temp/manifest.json", "w", encoding="utf-8" f"{self.outputPath}/temp/manifest.json", "w", encoding="utf-8"
) as f: ) as f:
f.write( f.write(
'{\n "format_version": 1,\n "header": {\n "description": "' '{\n "format_version": 1,\n "header": {\n "description": "'
@ -1090,7 +1100,7 @@ class midiConvert:
) )
else: else:
with open( with open(
f"{self.outputPath}/temp/manifest.json", "r", encoding="utf-8" f"{self.outputPath}/temp/manifest.json", "r", encoding="utf-8"
) as manifest: ) as manifest:
data = json.loads(manifest.read()) data = json.loads(manifest.read())
data["header"][ data["header"][
@ -1114,9 +1124,9 @@ class midiConvert:
"function mscplay/track" + str(cmdlist.index(track) + 1) + "\n" "function mscplay/track" + str(cmdlist.index(track) + 1) + "\n"
) )
with open( with open(
f"{self.outputPath}/temp/functions/mscplay/track{cmdlist.index(track) + 1}.mcfunction", f"{self.outputPath}/temp/functions/mscplay/track{cmdlist.index(track) + 1}.mcfunction",
"w", "w",
encoding="utf-8", encoding="utf-8",
) as f: ) as f:
f.write("\n".join(track)) f.write("\n".join(track))
indexfile.writelines( indexfile.writelines(
@ -1127,12 +1137,12 @@ class midiConvert:
+ scoreboardname + scoreboardname
+ " 1\n", + " 1\n",
( (
"scoreboard players reset @a[scores={" "scoreboard players reset @a[scores={"
+ scoreboardname + scoreboardname
+ "=" + "="
+ str(maxscore + 20) + str(maxscore + 20)
+ "..}]" + "..}]"
+ f" {scoreboardname}\n" + f" {scoreboardname}\n"
) )
if isAutoReset if isAutoReset
else "", else "",
@ -1143,18 +1153,18 @@ class midiConvert:
if progressbar: if progressbar:
if progressbar: if progressbar:
with open( with open(
f"{self.outputPath}/temp/functions/mscplay/progressShow.mcfunction", f"{self.outputPath}/temp/functions/mscplay/progressShow.mcfunction",
"w", "w",
encoding="utf-8", encoding="utf-8",
) as f: ) as f:
f.writelines( f.writelines(
"\n".join(self.__formProgressBar(maxscore, scoreboardname)) "\n".join(self.__formProgressBar(maxscore, scoreboardname))
) )
else: else:
with open( with open(
f"{self.outputPath}/temp/functions/mscplay/progressShow.mcfunction", f"{self.outputPath}/temp/functions/mscplay/progressShow.mcfunction",
"w", "w",
encoding="utf-8", encoding="utf-8",
) as f: ) as f:
f.writelines( f.writelines(
"\n".join( "\n".join(
@ -1174,17 +1184,16 @@ class midiConvert:
return (True, f"转换完成,总长度{maxlen}") return (True, f"转换完成,总长度{maxlen}")
def toBDXfile( def toBDXfile(
self, self,
method: int = 1, method: int = 1,
author: str = "Eilles", author: str = "Eilles",
progressbar=False, progressbar=False,
maxheight: int = 64, maxheight: int = 64,
scoreboardname: str = "mscplay", scoreboardname: str = "mscplay",
volume: float = 1.0, volume: float = 1.0,
speed: float = 1.0, speed: float = 1.0,
isAutoReset: bool = False, isAutoReset: bool = False,
): ):
""" """
使用method指定的转换算法将midi转换为BDX结构文件 使用method指定的转换算法将midi转换为BDX结构文件
@ -1208,13 +1217,13 @@ class midiConvert:
if not os.path.exists(self.outputPath): if not os.path.exists(self.outputPath):
os.makedirs(self.outputPath) os.makedirs(self.outputPath)
with open(os.path.abspath(os.path.join(self.outputPath,f"{self.midFileName}.bdx")), "w+") as f: with open(os.path.abspath(os.path.join(self.outputPath, f"{self.midFileName}.bdx")), "w+") as f:
f.write("BD@") f.write("BD@")
_bytes = ( _bytes = (
b"BDX\x00" b"BDX\x00"
+ author.encode("utf-8") + author.encode("utf-8")
+ b" & Musicreater\x00\x01command_block\x00" + b" & Musicreater\x00\x01command_block\x00"
) )
key = { key = {
@ -1243,12 +1252,12 @@ class midiConvert:
if isAutoReset: if isAutoReset:
commands += ( commands += (
"scoreboard players reset @a[scores={" "scoreboard players reset @a[scores={"
+ scoreboardname + scoreboardname
+ "=" + "="
+ str(maxScore + 20) + str(maxScore + 20)
+ "}] " + "}] "
+ scoreboardname + scoreboardname
) )
# 此处是对于仅有 True 的参数和自定义参数的判断 # 此处是对于仅有 True 的参数和自定义参数的判断
@ -1265,13 +1274,13 @@ class midiConvert:
cmd, cmd,
(1 if yforward else 0) (1 if yforward else 0)
if ( if (
((nowy != 0) and (not yforward)) ((nowy != 0) and (not yforward))
or ((yforward) and (nowy != maxheight)) or ((yforward) and (nowy != maxheight))
) )
else (3 if zforward else 2) else (3 if zforward else 2)
if ( if (
((nowz != 0) and (not zforward)) ((nowz != 0) and (not zforward))
or ((zforward) and (nowz != _sideLength)) or ((zforward) and (nowz != _sideLength))
) )
else 5, else 5,
impluse=2, impluse=2,
@ -1293,7 +1302,7 @@ class midiConvert:
nowz += 1 if zforward else -1 nowz += 1 if zforward else -1
if ((nowz > _sideLength) and (zforward)) or ( if ((nowz > _sideLength) and (zforward)) or (
(nowz < 0) and (not zforward) (nowz < 0) and (not zforward)
): ):
nowz -= 1 if zforward else -1 nowz -= 1 if zforward else -1
zforward = not zforward zforward = not zforward
@ -1307,20 +1316,20 @@ class midiConvert:
_bytes += key[y][int(yforward)] _bytes += key[y][int(yforward)]
with open(os.path.abspath(os.path.join(self.outputPath,f"{self.midFileName}.bdx")), "ab+") as f: with open(os.path.abspath(os.path.join(self.outputPath, f"{self.midFileName}.bdx")), "ab+") as f:
f.write(brotli.compress(_bytes + b"XE")) f.write(brotli.compress(_bytes + b"XE"))
return (True, _bytes, (nowx, maxheight, _sideLength)) return (True, _bytes, (nowx, maxheight, _sideLength))
def toBDXfile_withDelay( def toBDXfile_withDelay(
self, self,
method: int = 1, method: int = 1,
author: str = "Eilles", author: str = "Eilles",
progressbar=False, progressbar=False,
maxheight: int = 64, maxheight: int = 64,
volume: float = 1.0, volume: float = 1.0,
speed: float = 1.0, speed: float = 1.0,
player: str = "@a", player: str = "@a",
): ):
""" """
使用method指定的转换算法将midi转换为BDX结构文件 使用method指定的转换算法将midi转换为BDX结构文件
@ -1344,13 +1353,13 @@ class midiConvert:
if not os.path.exists(self.outputPath): if not os.path.exists(self.outputPath):
os.makedirs(self.outputPath) os.makedirs(self.outputPath)
with open(os.path.abspath(os.path.join(self.outputPath,f"{self.midFileName}.bdx")), "w+") as f: with open(os.path.abspath(os.path.join(self.outputPath, f"{self.midFileName}.bdx")), "w+") as f:
f.write("BD@") f.write("BD@")
_bytes = ( _bytes = (
b"BDX\x00" b"BDX\x00"
+ author.encode("utf-8") + author.encode("utf-8")
+ b" & Musicreater\x00\x01command_block\x00" + b" & Musicreater\x00\x01command_block\x00"
) )
key = { key = {
@ -1377,13 +1386,13 @@ class midiConvert:
cmd, cmd,
(1 if yforward else 0) (1 if yforward else 0)
if ( if (
((nowy != 0) and (not yforward)) ((nowy != 0) and (not yforward))
or ((yforward) and (nowy != maxheight)) or ((yforward) and (nowy != maxheight))
) )
else (3 if zforward else 2) else (3 if zforward else 2)
if ( if (
((nowz != 0) and (not zforward)) ((nowz != 0) and (not zforward))
or ((zforward) and (nowz != _sideLength)) or ((zforward) and (nowz != _sideLength))
) )
else 5, else 5,
impluse=2, impluse=2,
@ -1405,7 +1414,7 @@ class midiConvert:
nowz += 1 if zforward else -1 nowz += 1 if zforward else -1
if ((nowz > _sideLength) and (zforward)) or ( if ((nowz > _sideLength) and (zforward)) or (
(nowz < 0) and (not zforward) (nowz < 0) and (not zforward)
): ):
nowz -= 1 if zforward else -1 nowz -= 1 if zforward else -1
zforward = not zforward zforward = not zforward
@ -1419,16 +1428,15 @@ class midiConvert:
_bytes += key[y][int(yforward)] _bytes += key[y][int(yforward)]
with open(os.path.abspath(os.path.join(self.outputPath,f"{self.midFileName}.bdx")), "ab+") as f: with open(os.path.abspath(os.path.join(self.outputPath, f"{self.midFileName}.bdx")), "ab+") as f:
f.write(brotli.compress(_bytes + b"XE")) f.write(brotli.compress(_bytes + b"XE"))
return (True, _bytes, (nowx, maxheight, _sideLength)) return (True, _bytes, (nowx, maxheight, _sideLength))
# def isProgressBar(pgbarLike:str): # def isProgressBar(pgbarLike:str):
# '''判断所输入数据是否为进度条式样数据 # '''判断所输入数据是否为进度条式样数据
# 注意,使用本函数时不得直接放在 if 后,正确用法如下: # 注意,使用本函数时不得直接放在 if 后,正确用法如下:
# 判断是否是合规进度条样式数据: # 判断是否是合规进度条样式数据:
# ``` # ```
# if isProgressBar(pgb) == False: # if isProgressBar(pgb) == False:
@ -1451,6 +1459,3 @@ class midiConvert:
# return (r"▶ %%N [ %%s/%^s %%% __________ %%t|%^t ]",("§e=§r", "§7=§r"),) # return (r"▶ %%N [ %%s/%^s %%% __________ %%t|%^t ]",("§e=§r", "§7=§r"),)
# elif pgbarLike.lower() in ('false','0'): # elif pgbarLike.lower() in ('false','0'):
# return () # return ()