You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Python实现用户名关联语音存储与回放功能的技术求助

解决方案:Python 用户名关联语音录制与回放工具

Hey there! I’ve built similar voice recording tools before, so let’s walk through a practical, working implementation that covers your needs: saving usernames, recording their audio, and playing it back.

核心依赖选择

First, we’ll use a few reliable libraries— no fancy external services needed:

  • sounddevice: Handles cross-platform audio recording and playback (way easier to set up than PyAudio for most cases)
  • soundfile: Saves/loads audio files in WAV format (lossless, perfect for this use case)
  • json: To store the mapping between usernames and their audio file paths (lightweight, no database required unless you need to scale later)

Install them first with pip:

pip install sounddevice soundfile

完整实现代码

Here’s a working script that ties everything together. I’ve added comments to explain each part clearly:

import sounddevice as sd
import soundfile as sf
import json
import os

# 保存用户名与音频路径的映射文件
USER_VOICE_MAP = "user_voices.json"
# 音频存储目录,自动创建如果不存在
AUDIO_DIR = "user_recordings"
os.makedirs(AUDIO_DIR, exist_ok=True)

def load_user_map():
    """加载已有的用户名-音频映射"""
    if os.path.exists(USER_VOICE_MAP):
        with open(USER_VOICE_MAP, "r") as f:
            return json.load(f)
    return {}

def save_user_map(user_map):
    """保存用户名-音频映射到文件"""
    with open(USER_VOICE_MAP, "w") as f:
        json.dump(user_map, f, indent=2)

def record_voice(username, duration=5, sample_rate=44100):
    """录制指定时长的语音并保存,关联用户名"""
    print(f"Recording {username}'s voice for {duration} seconds... Speak now!")
    # 录制单声道音频
    audio_data = sd.rec(int(duration * sample_rate), samplerate=sample_rate, channels=1)
    sd.wait()  # 等待录制完成
    
    # 生成安全的文件名(替换空格避免路径问题)
    audio_filename = f"{username.replace(' ', '_')}.wav"
    audio_path = os.path.join(AUDIO_DIR, audio_filename)
    # 保存音频文件
    sf.write(audio_path, audio_data, sample_rate)
    
    # 更新用户映射表
    user_map = load_user_map()
    user_map[username] = audio_path
    save_user_map(user_map)
    print(f"Recording saved for {username} at {audio_path}")

def play_voice(username):
    """根据用户名回放对应的语音"""
    user_map = load_user_map()
    if username not in user_map:
        print(f"No recording found for user: {username}")
        return
    
    audio_path = user_map[username]
    if not os.path.exists(audio_path):
        print(f"Audio file missing for {username}: {audio_path}")
        return
    
    print(f"Playing back {username}'s voice...")
    audio_data, sample_rate = sf.read(audio_path)
    sd.play(audio_data, sample_rate)
    sd.wait()  # 等待播放完成
    print("Playback finished!")

def main():
    """主交互界面"""
    while True:
        print("\n--- Voice Recording Tool ---")
        print("1. Record a new user's voice")
        print("2. Play back a user's voice")
        print("3. Exit")
        choice = input("Enter your choice (1/2/3): ")
        
        if choice == "1":
            username = input("Enter the username: ").strip()
            if not username:
                print("Username cannot be empty!")
                continue
            # 支持自定义录制时长
            try:
                duration = int(input("Enter recording duration in seconds (default 5): ") or 5)
            except ValueError:
                duration = 5
            record_voice(username, duration)
        elif choice == "2":
            username = input("Enter the username to play back: ").strip()
            play_voice(username)
        elif choice == "3":
            print("Exiting tool. Goodbye!")
            break
        else:
            print("Invalid choice, please enter 1, 2, or 3.")

if __name__ == "__main__":
    main()

关键细节说明

  • 跨平台兼容: sounddevice 在Windows、macOS和Linux上都能正常工作,不像PyAudio在部分系统上安装会出问题
  • 避免文件名冲突: 我们把用户名里的空格替换成下划线,比如"John Doe"会变成John_Doe.wav,防止路径错误
  • 数据持久化: user_voices.json 文件会保存所有用户和对应音频的映射,重启程序后数据不会丢失
  • 基础错误处理: 脚本会检查用户是否存在、音频文件是否缺失,也能处理无效输入

If you were stuck on a specific part (like linking usernames to audio files, or getting recording/playback to work), this should fill those gaps. Feel free to tweak the duration, sample rate, or swap JSON for SQLite if you need to handle hundreds of users later!

内容的提问来源于stack exchange,提问作者Tlhogi Dube

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:09:28