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

如何在Python 3.6中通过Houndify API发起指定领域语音请求?

Got it, let's cut through the confusing official docs and get you up and running with Houndify voice requests in Python 3.6—purely server-side, no browser needed, and limited only to the domains you care about (weather, maps, knowledge, Wikipedia). Here's a step-by-step guide with working code:

Step 1: Install Dependencies

First, install the required packages. The Houndify Python SDK handles the API heavy lifting, and PyAudio lets you record audio directly in Python:

pip install houndify pyaudio

Note for Python 3.6 on Windows: If PyAudio installation fails, grab a pre-built wheel for your architecture (e.g., PyAudio-0.2.11-cp36-cp36m-win_amd64.whl) and install it with pip install <wheel-file-name>.

Step 2: Set Up Houndify Credentials
  1. Go to the Houndify Developer Console and create a new application.
  2. Copy your Client ID and Client Key (you'll need these in the code).
  3. In your app's settings, navigate to the Domains tab. Only enable the domains you want: Weather, Maps, KnowledgeGraph, and Wikipedia. This ensures Houndify only processes requests for these areas.
Step 3: Full Implementation Code

This code will record your voice, send it to Houndify, and return the relevant response—no browser required. Replace YOUR_CLIENT_ID and YOUR_CLIENT_KEY with your actual credentials:

import houndify
import pyaudio
import wave
import json

# Replace with your Houndify credentials
CLIENT_ID = "YOUR_CLIENT_ID"
CLIENT_KEY = "YOUR_CLIENT_KEY"

# List of domains you want to enable
ENABLED_DOMAINS = [
    "Weather",
    "Maps",
    "KnowledgeGraph",
    "Wikipedia"
]

def record_audio(filename="voice_request.wav", duration=5):
    """Record 16kHz, mono, 16-bit PCM audio (Houndify's required format)"""
    chunk = 1024
    sample_format = pyaudio.paInt16
    channels = 1
    sample_rate = 16000

    p = pyaudio.PyAudio()

    print("Recording for 5 seconds... Speak your request now!")
    stream = p.open(
        format=sample_format,
        channels=channels,
        rate=sample_rate,
        frames_per_buffer=chunk,
        input=True
    )

    frames = []
    for _ in range(0, int(sample_rate / chunk * duration)):
        data = stream.read(chunk)
        frames.append(data)

    stream.stop_stream()
    stream.close()
    p.terminate()
    print("Recording finished.")

    # Save audio to WAV file
    wf = wave.open(filename, 'wb')
    wf.setnchannels(channels)
    wf.setsampwidth(p.get_sample_size(sample_format))
    wf.setframerate(sample_rate)
    wf.writeframes(b''.join(frames))
    wf.close()

    return filename

def send_houndify_voice_request(audio_file_path):
    """Send recorded audio to Houndify, restricted to your enabled domains"""
    # Initialize Houndify client
    client = houndify.HoundifyClient(CLIENT_ID, CLIENT_KEY, "unique_user_id", enableVAD=False)

    # Configure request to only use your allowed domains
    request_params = {
        "AllowedDomains": ENABLED_DOMAINS,
        "DisableAllDomainsExceptAllowed": True  # Critical: blocks all other domains
    }

    # Send audio stream to Houndify
    with open(audio_file_path, 'rb') as audio_file:
        response_stream = client.query(audio_file, request_info=request_params)

    # Parse and display the response
    for chunk in response_stream:
        if chunk["Status"] == "OK":
            print("\nRaw Houndify Response (formatted):")
            print(json.dumps(chunk, indent=2))
            
            # Extract the human-readable answer
            if "AllResults" in chunk:
                for result in chunk["AllResults"]:
                    print("\n✅ Final Answer:", result["WrittenResponse"])
        else:
            print(f"\n❌ Error: {chunk['ErrorMessage']}")

if __name__ == "__main__":
    # Record audio and send request
    recorded_audio = record_audio()
    send_houndify_voice_request(recorded_audio)
Step 4: Key Notes & Troubleshooting
  • Audio Format: Houndify strictly requires 16kHz sample rate, mono, 16-bit PCM audio. The record_audio function already adheres to this—don't modify these settings unless you know what you're doing.
  • Domain Restriction: The DisableAllDomainsExceptAllowed flag ensures Houndify ignores any requests outside your enabled domains. Double-check your console settings to make sure only the desired domains are turned on.
  • Offline Testing: If you don't want to record audio every time, replace the record_audio() call with the path to a pre-recorded WAV file that meets the format requirements.
  • Python 3.6 Compatibility: The Houndify SDK supports Python 3.6+, so you shouldn't run into version conflicts here.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:17:00