使用python实现音频与文本互转!

使用python实现音频与文本互转!!

音频文件

常见的音频文件格式如WAV、MP3、AAC等,都是以二进制形式存储的。二进制文件都可以编码成base64编码。我们可以通过转为base64编码的形式,来实现把音频文件转为文本。
PS:本文举例wav格式来进行转换,不同的格式会有一些不同

base64编码

  • Base64是一种二进制到文本的编码方式。如果要更具体一点的话,可以认为它是一种将
    byte数组编码为字符串的方法,而且编码出的字符串只包含ASCII基础字符。
  • Base64使用到的64个字符:
  • A-Z 26个
  • a-z 26个
  • 0-9 10个
  • +1个
  • / 1个

效果

在这里插入图片描述
比较意外的是,转成文本后文件大小变大了!
文本内容如下图所示:
在这里插入图片描述

代码

import base64
import wave
import os


def audio_to_base64(audio_file_path, output_txt_path):
    # 打开音频文件
    with wave.open(audio_file_path, 'rb') as audio_file:
        # 读取二进制数据
        audio_content = audio_file.readframes(audio_file.getnframes())

        # 将二进制数据编码为Base64
    base64_content = base64.b64encode(audio_content).decode('utf-8')

    # 将Base64编码保存到文本文件
    with open(output_txt_path, 'w') as txt_file:
        txt_file.write(base64_content)

    print(f"音频文件已成功转换为Base64并保存到 {output_txt_path}")


def base64_to_audio(base64_txt_path, output_audio_path, original_audio_path):
    # 从文本文件读取Base64编码
    with open(base64_txt_path, 'r') as txt_file:
        base64_content = txt_file.read()

        # 将Base64编码解码为二进制数据
    audio_content = base64.b64decode(base64_content)

    # 读取原始音频文件的参数
    with wave.open(original_audio_path, 'rb') as original_audio_file:
        params = original_audio_file.getparams()

        # 创建一个新的wave文件对象并写入二进制数据,使用原始音频文件的参数
    with wave.open(output_audio_path, 'wb') as audio_file:
        audio_file.setparams(params)
        audio_file.writeframes(audio_content)

    print(f"Base64编码已成功还原为音频文件并保存到 {output_audio_path}")


# 使用函数示例
audio_file = 'example.wav'  # 假设当前目录有一个名为example.wav的音频文件
base64_txt = 'base64.txt'  # 输出的Base64编码文本文件名

# 将音频文件转换为Base64并保存为文本文件
audio_to_base64(audio_file, base64_txt)

# 从Base64编码文本文件还原为音频文件
output_audio = 'restored_example.wav'  # 还原后的音频文件名
base64_to_audio(base64_txt, output_audio,audio_file)
  • 21
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

立秋6789

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值