音频ncm格式转mp3格式

2023-12-16 12:36
文章标签 音频 格式 mp3 ncm

本文主要是介绍音频ncm格式转mp3格式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

做个笔记,ncm格式转mp3格式
参考:传送门

import os
import json
import base64
import struct
import logging
import binascii
from glob import glob
from tqdm.auto import tqdm
from textwrap import dedent
from Crypto.Cipher import AES
from multiprocessing import Poolclass TqdmLoggingHandler(logging.StreamHandler):"""Avoid tqdm progress bar interruption by logger's output to console"""# see logging.StreamHandler.eval method:# https://github.com/python/cpython/blob/d2e2534751fd675c4d5d3adc208bf4fc984da7bf/Lib/logging/__init__.py#L1082-L1091# and tqdm.write method:# https://github.com/tqdm/tqdm/blob/f86104a1f30c38e6f80bfd8fb16d5fcde1e7749f/tqdm/std.py#L614-L620def emit(self, record):try:msg = self.format(record)tqdm.write(msg, end=self.terminator)except RecursionError:raiseexcept Exception:self.handleError(record)log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
handler = TqdmLoggingHandler()
fmt = '%(levelname)7s [%(asctime)s] %(message)s'
datefmt = '%Y-%m-%d %H:%M:%S'
handler.setFormatter(logging.Formatter(fmt, datefmt))
log.addHandler(handler)def dump_single_file(filepath):try:filename = filepath.split('/')[-1]if not filename.endswith('.ncm'): returnfilename = filename[:-4]for ftype in ['mp3', 'flac']:fname = f'{filename}.{ftype}'if os.path.isfile(fname):log.warning(f'Skipping "{filepath}" due to existing file "{fname}"')returnlog.info(f'Converting "{filepath}"')# hex to strcore_key = binascii.a2b_hex('687A4852416D736F356B496E62617857')meta_key = binascii.a2b_hex('2331346C6A6B5F215C5D2630553C2728')unpad = lambda s: s[0:-(s[-1] if isinstance(s[-1], int) else ord(s[-1]))]with open(filepath, 'rb') as f:header = f.read(8)# str to hexassert binascii.b2a_hex(header) == b'4354454e4644414d'f.seek(2, 1)key_length = f.read(4)key_length = struct.unpack('<I', bytes(key_length))[0]key_data = f.read(key_length)key_data_array = bytearray(key_data)for i in range(0, len(key_data_array)):key_data_array[i] ^= 0x64key_data = bytes(key_data_array)cryptor = AES.new(core_key, AES.MODE_ECB)key_data = unpad(cryptor.decrypt(key_data))[17:]key_length = len(key_data)key_data = bytearray(key_data)key_box = bytearray(range(256))c = 0last_byte = 0key_offset = 0for i in range(256):swap = key_box[i]c = (swap + last_byte + key_data[key_offset]) & 0xffkey_offset += 1if key_offset >= key_length:key_offset = 0key_box[i] = key_box[c]key_box[c] = swaplast_byte = cmeta_length = f.read(4)meta_length = struct.unpack('<I', bytes(meta_length))[0]meta_data = f.read(meta_length)meta_data_array = bytearray(meta_data)for i in range(0, len(meta_data_array)):meta_data_array[i] ^= 0x63meta_data = bytes(meta_data_array)meta_data = base64.b64decode(meta_data[22:])cryptor = AES.new(meta_key, AES.MODE_ECB)meta_data = unpad(cryptor.decrypt(meta_data)).decode('utf-8')[6:]meta_data = json.loads(meta_data)crc32 = f.read(4)crc32 = struct.unpack('<I', bytes(crc32))[0]f.seek(5, 1)image_size = f.read(4)image_size = struct.unpack('<I', bytes(image_size))[0]image_data = f.read(image_size)target_filename = filename + '.' + meta_data['format']with open(target_filename, 'wb') as m:chunk = bytearray()while True:chunk = bytearray(f.read(0x8000))chunk_length = len(chunk)if not chunk:breakfor i in range(1, chunk_length + 1):j = i & 0xffchunk[i - 1] ^= key_box[(key_box[j] + key_box[(key_box[j] + j) & 0xff]) & 0xff]m.write(chunk)log.info(f'Converted file saved at "{target_filename}"')return target_filenameexcept KeyboardInterrupt:log.warning('Aborted')quit()def list_filepaths(path):if os.path.isfile(path):return [path]elif os.path.isdir(path):return [fp for p in glob(f'{path}/*') for fp in list_filepaths(p)]else:raise ValueError(f'path not recognized: {path}')def dump(*paths, n_workers=None):header = dedent(r'''_  _  ___ __  __ ___  _   _ __  __ ____ __ _  _| \| |/ __|  \/  |   \| | | |  \/  | _ \| '_ \ || | .` | (__| |\/| | |) | |_| | |\/| |  _/| .__/\_, |_|\_|\___|_|  |_|___/ \___/|_|  |_|_|  |_|   |__/                                        pyNCMDUMP                     https://github.com/allenfrostline/pyNCMDUMP  ''')for line in header.split('\n'):log.info(line)all_filepaths = [fp for p in paths for fp in list_filepaths(p)]if n_workers > 1:log.info(f'Running pyNCMDUMP with up to {n_workers} parallel workers')with Pool(processes=n_workers) as p:list(p.map(dump_single_file, all_filepaths))else:log.info('Running pyNCMDUMP on single-worker mode')for fp in tqdm(all_filepaths, leave=False): dump_single_file(fp)log.info('All finished')if __name__ == '__main__':from argparse import ArgumentParserparser = ArgumentParser(description='pyNCMDUMP command-line interface')parser.add_argument('paths',metavar='paths',type=str,nargs='+',help='one or more paths to source files')parser.add_argument('-w', '--workers',metavar='',type=int,help=f'parallel convertion when set to more than 1 workers (default: 1)',default=1)args = parser.parse_args()dump(*args.paths, n_workers=args.workers)

在这里插入图片描述

这篇关于音频ncm格式转mp3格式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/500498

相关文章

C#中DateTime的格式符的实现示例

《C#中DateTime的格式符的实现示例》本文介绍了C#中DateTime格式符的使用方法,分为预定义格式和自定义格式两类,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值... 目录DateTime的格式符1.核心概念2.预定义格式(快捷方案,直接复用)3.自定义格式(灵活可控

使用C#导出Excel数据并保存多种格式的完整示例

《使用C#导出Excel数据并保存多种格式的完整示例》在现代企业信息化管理中,Excel已经成为最常用的数据存储和分析工具,从员工信息表、销售数据报表到财务分析表,几乎所有部门都离不开Excel,本文... 目录引言1. 安装 Spire.XLS2. 创建工作簿和填充数据3. 保存为不同格式4. 效果展示5

使用python生成固定格式序号的方法详解

《使用python生成固定格式序号的方法详解》这篇文章主要为大家详细介绍了如何使用python生成固定格式序号,文中的示例代码讲解详细,具有一定的借鉴价值,有需要的小伙伴可以参考一下... 目录生成结果验证完整生成代码扩展说明1. 保存到文本文件2. 转换为jsON格式3. 处理特殊序号格式(如带圈数字)4

使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解

《使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解》本文详细介绍了如何使用Python通过ncmdump工具批量将.ncm音频转换为.mp3的步骤,包括安装、配置ffmpeg环... 目录1. 前言2. 安装 ncmdump3. 实现 .ncm 转 .mp34. 执行过程5. 执行结

SpringBoot 异常处理/自定义格式校验的问题实例详解

《SpringBoot异常处理/自定义格式校验的问题实例详解》文章探讨SpringBoot中自定义注解校验问题,区分参数级与类级约束触发的异常类型,建议通过@RestControllerAdvice... 目录1. 问题简要描述2. 异常触发1) 参数级别约束2) 类级别约束3. 异常处理1) 字段级别约束

SQLite3 在嵌入式C环境中存储音频/视频文件的最优方案

《SQLite3在嵌入式C环境中存储音频/视频文件的最优方案》本文探讨了SQLite3在嵌入式C环境中存储音视频文件的优化方案,推荐采用文件路径存储结合元数据管理,兼顾效率与资源限制,小文件可使用B... 目录SQLite3 在嵌入式C环境中存储音频/视频文件的专业方案一、存储策略选择1. 直接存储 vs

Mysql常见的SQL语句格式及实用技巧

《Mysql常见的SQL语句格式及实用技巧》本文系统梳理MySQL常见SQL语句格式,涵盖数据库与表的创建、删除、修改、查询操作,以及记录增删改查和多表关联等高级查询,同时提供索引优化、事务处理、临时... 目录一、常用语法汇总二、示例1.数据库操作2.表操作3.记录操作 4.高级查询三、实用技巧一、常用语

利用Python脚本实现批量将图片转换为WebP格式

《利用Python脚本实现批量将图片转换为WebP格式》Python语言的简洁语法和库支持使其成为图像处理的理想选择,本文将介绍如何利用Python实现批量将图片转换为WebP格式的脚本,WebP作为... 目录简介1. python在图像处理中的应用2. WebP格式的原理和优势2.1 WebP格式与传统

C++ 函数 strftime 和时间格式示例详解

《C++函数strftime和时间格式示例详解》strftime是C/C++标准库中用于格式化日期和时间的函数,定义在ctime头文件中,它将tm结构体中的时间信息转换为指定格式的字符串,是处理... 目录C++ 函数 strftipythonme 详解一、函数原型二、功能描述三、格式字符串说明四、返回值五

C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式

《C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式》Markdown凭借简洁的语法、优良的可读性,以及对版本控制系统的高度兼容性,逐渐成为最受欢迎的文档格式... 目录为什么要将文档转换为 Markdown 格式使用工具将 Word 文档转换为 Markdown(.