工作中碰到的,在这里记录一下。根据原来的shell脚本修改,有不足之处各位指正,调用的程序我放在百度网盘,需要自取,各位如果有更好的可以分享分享
链接:https://pan.baidu.com/s/14Hil8jUVZ9fHm3SX_OfPAA?pwd=ty78
提取码:ty78
# -*- coding: utf-8 -*-
# @Time : 2024/01/22 18:31
# @Author : hjcui
# @Site :
# @File : convert_silk.py
# @Software: vim
import os,time
from multiprocessing import Process
from termcolor import colored
class Decode_Audio(object):
def __init__(self,src,dest,decoder_path,silk_audio_path):
self.src = src
self.dest = dest
self.decoder_path = decoder_path
self.silk_audio_path = silk_audio_path
def compile_env(self):
try:
if os.path.exists(self.decoder_path):
os.chdir(self.decoder_path)
cmd = "make && make decoder"
os.system(cmd)
print(colored("========= Silk v3 Decoder Compile Finish =========","green"))
else:
print(colored("[Error]","red"),"Silk v3 Decoder Compile False, Please Check Your System For GCC.")
except Exception as e:
print(e)
def Decode_file(self):
CURRENT = 0
silk_num = 0
print(colored("========= Batch Conversion Start ==========","green"))
if os.path.exists(self.src):
files = os.listdir(self.src)
decoder = self.decoder_path + "/" + "decoder"
TOTAL = len(files)
for file in files:
CURRENT += 1
src_file = os.path.join(self.src,file)
dest_file = os.path.join(self.dest,file + '.wav')
silk_file = os.path.join(self.silk_audio_path,file + '_silk')
format_head = self.Check_Audio_Format(src_file)
#print(format_head)
if format_head == b"SILK_V3":
silk_num += 1
# silk convert to pcm
silk_cmd = "%s %s %s" % (decoder,src_file,silk_file)
print(colored("SILK-[%s/%s] [OK]" % (CURRENT,silk_num),"green"),"Convert %s To %s Finish." % (src_file,silk_file))
os.system(silk_cmd)
# pcm convert to wav
conv_cmd = 'ffmpeg -i %s -vn -ar 8000 -ac 1 -ab 128k -y -f wav -loglevel 0 %s' % (silk_file,dest_file)
os.system(conv_cmd)
print(colored("[%s/%s] [OK]" % (CURRENT,TOTAL),"green"),"Convert %s To %s Finish." % (silk_file,dest_file))
else:
cmd = 'ffmpeg -i %s -vn -ar 8000 -ac 1 -ab 128k -y -f wav -loglevel 0 %s' % (src_file,dest_file)
os.system(cmd)
print(colored("[%s/%s] [OK]" % (CURRENT,TOTAL),"green"),"Convert %s To %s Finish." % (src_file,dest_file))
print(colored("========= Batch Conversion Finish =========","green"))
print(f"SILK file {silk_num}")
def Check_Audio_Format(self,audio):
with open(audio,'rb') as f:
file_header = f.read(10)[2:9].strip()
return file_header
if __name__ == "__main__":
src = r'/home/ulang/lang_engine/convert_format/src'
dest = r'/home/ulang/lang_engine/convert_format/dest'
decode = r'/home/ulang/lang_engine/convert_format/silk-v3-decoder/silk'
silk_to_pcm = r'/home/ulang/lang_engine/convert_format/silk_to_pcm'
instance = Decode_Audio(src,dest,decode,silk_to_pcm)
instance.compile_env()
instance.Decode_file()