当前位置:   article > 正文

{txt-to-video}——文本转视频思路_txt_to_video

txt_to_video

思路:

.txt -> 读取 -> 调用api合成语音 -> 合成语音 -> MP3+PNG/JPG -> 合成视频

目录结构

在这里插入图片描述

  • new_video:存放最后生产的视频文件
  • out_v:存放合成的MP3文件
  • text:存放文本文件
  • voices:存放api导出的MP3

代码结构:

import os
import time
import subprocess
from pydub import AudioSegment
from aip import AipSpeech
import pandas as pd
pd.set_option( 'display.max_columns', None)
pd.set_option( 'display.max_rows', None)
PATH = os.path.abspath(__file__).replace(os.path.abspath(__file__).split('\\')[-1], '')

def text_to_voice(text,file_name,r_num):
    print(len(text))
    text_list = []
    out_max = 500
    if len(text)> out_max:
        text_list.append(text[:out_max])
        text_list.append(text[out_max:])
        while True:
            if len(text_list[-1])>out_max:
                text_re = text_list[-1]
                text_list.remove(text_re)
                text_list.append(text_re[:out_max])
                text_list.append(text_re[out_max:])
            else:
                break
    print(len(text_list))
    file_name_list = []
    for i in range(0,len(text_list)):
        APP_ID = 'xxx'
        API_KEY = 'xxx'
        SECRET_KEY = 'xxx'
        try:
            client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
            result = client.synthesis(text_list[i], 'zh', 1, {
                'vol': 5,
                'per': 3,
                'spd': 6
            })
            print(f"::{file_name}::{i}::{result}")
        except Exception as e:
            print(e)
        if not isinstance(result, dict):
            with open(f'voices/{r_num}_{i}.mp3', 'wb') as f:
                f.write(result)
        time.sleep(2)

        file_name_list.append(f'{r_num}_{i}.mp3')

    f = open(f'voices/{r_num}_ff.txt','a')
    for i in file_name_list:
        f.write(f'file {i}\n')
    f.close()
    return f'{r_num}_ff.txt'


def add_mp3(dir_name,file_name):
    f = open(f"{dir_name}/{file_name}",encoding='utf-8')
    ret = f.readlines()
    f.close()
    outfile_name = ret[0].replace('.mp3','_NEW.mp3').replace('file ','').replace('\n','')
    cmd = f'{PATH}{dir_name}\\ffmpeg.exe -f concat -safe 0'
    cmd+= f' -i {PATH}{dir_name}\\{file_name} -c copy {PATH}out_v\\{outfile_name}'
    print(cmd)
    subprocess.call(cmd,shell=True)


def filter_text(text_src):
    f= open(text_src, encoding='utf-8')
    ret = f.readlines()
    ret_out = []
    for i in ret:
        i = i.strip().replace('\n','')
        if i != '':
            ret_out.append(i)
    f.close()
    return ret_out


def filter_text_1(text_src):
    f = open(text_src, encoding='utf-8')
    ret = f.readlines()
    ret_out = []
    for i in ret:
        i = i.strip().replace('\n', '').replace('|','')
        if i != '':
            ret_out.append(i)
    f.close()
    ret_dict = {}
    str1 = ''
    for i in ret_out:
        if '===' in i:
            title = i.replace('===','').replace(' ','_')
            str1 = ''
            continue
        str1 += i
        ret_dict[title]=str1
    for i in ret_dict:
        print(i)
        print(len(ret_dict[i]))
    return ret_dict


def to_video(src):
    ff = ['ffmpeg.exe','back.png']
    l_r = [i for num, i in enumerate(os.listdir(src)) if num not in ff]
    print(l_r)
    for c in l_r:
        out_name = c.replace('.mp3','.mp4')
        cmd = f'{PATH}voices\\ffmpeg.exe -i {PATH}out_v\\{c} -i {PATH}out_v\\back.png' \
              f'  -acodec aac -strict -2 -vcodec libx264 -ar 22050 -ab 128k -ac 2 -y {PATH}new_video\\{out_name}'
        print(cmd)
        subprocess.call(cmd, shell=True)


def to_video_one(dir_name,vioce_name):
    out_name = vioce_name.replace('.mp3','.mp4')
    cmd = f'{PATH}{dir_name}\\ffmpeg.exe -i {PATH}{dir_name}\\{vioce_name} -i {PATH}{dir_name}\\back.png' \
          f'  -acodec aac -strict -2 -vcodec libx264 -ar 22050 -ab 128k -ac 2 -y {PATH}new_video\\{out_name}'
    print(cmd)
    subprocess.call(cmd, shell=True)

if __name__ == '__main__':
    # ret_dict = filter_text_1('text/1.txt')
    # k = 1
    # txt_file_list=[]
    # for i in ret_dict:
    #     if k>187:
    #         file_name = text_to_voice(ret_dict[i],i,k)
    #         txt_file_list.append(file_name)
    #     k +=1
    # print(txt_file_list)
    #---------------------------
    # f = open('out_v/full.txt','a')
    # for i in range(1,263):
    #     f.write(f'file {i}_0_NEW.mp3\n')
    # f.close()
    # add_mp3('out_v','full.txt')
    #-----------------------------
    # txt_file_list = []
    # for i in range(1,263):
    #     txt_file_list.append(f'{i}_ff.txt')
    # print(txt_file_list)
    # for i in txt_file_list:
    #     add_mp3('voices',i)
    # to_video('out_v/')
    #-------------------
    # to_video_one('out_v','1_0_NEW_NEW.mp3')
    #-------------------
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号