当前位置:首页>文章>使用指南>whisper-1-Python示例代码

whisper-1-Python示例代码

文本是《工具配置(共30篇)》专题的第 30 篇。阅读本文前,建议先阅读前面的文章:

1. 资源准备

2. 安装依赖

pip install openai

3. 实现代码

import openai

# 这里填写您在https://yibuapi.com上创建的apikey
api_key = "sk-xxxxx"
# 这里填写https://yibuapi.com/v1
base_url = "https://yibuapi.com/v1"

# 音频文件路径
audio_file_path = "/Users/mufeng.yang/Desktop/test.m4a"  # 请替换为您的音频文件路径

def transcribe_audio_with_whisper(audio_file_path, api_key, base_url):
    """
    使用 Whisper-1 模型将音频转换为文本
    """
    try:
        client = openai.OpenAI(api_key=api_key, base_url=base_url)

        # 打开音频文件
        with open(audio_file_path, "rb") as audio_file:
            # 调用 Whisper API 进行语音转文本
            response = client.audio.transcriptions.create(
                model="whisper-1",
                file=audio_file,
                language="zh",  # 指定为中文,可选参数
                response_format="text"  # 返回格式:text, json, srt, verbose_json, vtt
            )

        return response
    except FileNotFoundError:
        return f"错误:找不到音频文件 {audio_file_path}"
    except Exception as e:
        return f"转录失败: {str(e)}"

def transcribe_audio_with_translation(audio_file_path, api_key, base_url):
    """
    使用 Whisper-1 模型将音频转换为英文文本(翻译功能)
    """
    try:
        client = openai.OpenAI(api_key=api_key, base_url=base_url)

        with open(audio_file_path, "rb") as audio_file:
            # 使用翻译 API,将任何语言转换为英文
            response = client.audio.translations.create(
                model="whisper-1",
                file=audio_file,
                response_format="text"
            )

        return response
    except FileNotFoundError:
        return f"错误:找不到音频文件 {audio_file_path}"
    except Exception as e:
        return f"翻译失败: {str(e)}"

if __name__ == "__main__":
    # 语音转文本(保持原语言)
    print("正在进行语音转文本...")
    transcription = transcribe_audio_with_whisper(audio_file_path, api_key, base_url)
    print(f"转录结果: {transcription}\n")

    # 语音转文本并翻译为英文(可选)
    print("正在进行语音翻译为英文...")
    translation = transcribe_audio_with_translation(audio_file_path, api_key, base_url)
    print(f"翻译结果: {translation}\n")

4. 运行效果

whisper-1-Python示例代码

使用指南

Claude-Java示例代码

2025-9-29 11:26:38

工具配置

探索前沿AI对话:LibreChat部署的深度洞察与最佳实践

2025-7-30 11:45:15

搜索