# -*- coding: utf-8 -*-
#マイク0番からの入力を受ける。一定時間(RECROD_SECONDS)だけ録音し、ファイル名:mono.wavで保存する。

import pyaudio
import sys
import time
import wave
import requests
import os
import json
import subprocess

def recognize():
    url = "https://api.apigw.smt.docomo.ne.jp/amiVoice/v1/recognize?APIKEY={}".format(APIKEY)
    files = {"a": open(PATH, 'rb'), "v":"on"}
    r = requests.post(url, files=files)
    message = r.json()['text']
    print message
    return message

def dialogue(message="こんにちは"):
    url = "https://api.apigw.smt.docomo.ne.jp/dialogue/v1/dialogue?APIKEY={}".format(APIKEY)
    payload = {
      "utt": message,
      "context": "",
      "nickname": "光",
      "nickname_y": "ヒカリ",
      "sex": "女",
      "bloodtype": "B",
      "birthdateY": "1997",
      "birthdateM": "5",
      "birthdateD": "30",
      "age": "16",
      "constellations": "双子座",
      "place": "東京",
      "mode": "dialog",
      "t":20
    }
    r = requests.post(url, data=json.dumps(payload))
    print r.json()['utt']
    return r.json()['utt']
    def talk(message="こんにちは",card=1,device=0):      
        res = subprocess.check_output('/home/pi/aquestalkpi/AquesTalkPi " ' + message.encode('utf-8') + ' " | aplay -Dhw:{},{}', stderr=subprocess.STDOUT, shell=True)


if __name__ == '__main__':
    chunk = 1024
    FORMAT = pyaudio.paInt16
    CHANNELS = 1
    PATH = '/var/tmp/tmp.wav'
    APIKEY='48316b555a686253622f6f47746b386a77624b437a65754d69466173495041415747647a482f524a756543' #DocomoAPI Key
    CARD = 1 #OUTPUTの指定
    DEVICE = 0 #OUTPUTの指定
    #サンプリングレート、マイク性能に依存
    RATE = 48000
    #録音時間
    RECORD_SECONDS = input('Please input recoding time>>>')

    #pyaudio
    p = pyaudio.PyAudio()

    #マイク0番を設定
    input_device_index = 0
    #マイクからデータ取得
    stream = p.open(format = FORMAT,
                    channels = CHANNELS,
                    rate = RATE,
                    input = True,
                    frames_per_buffer = chunk)
    all = []
    for i in range(0, RATE / chunk * RECORD_SECONDS):
        data = stream.read(chunk)
        all.append(data)

    stream.close()    
    data = ''.join(all)                    
    out = wave.open(PATH,'w')
    out.setnchannels(1) #mono
    out.setsampwidth(2) #16bits
    out.setframerate(RATE)
    out.writeframes(data)
    out.close()

    p.terminate()

    message = recognize()
    talk_message = dialogue(message)
    talk(talk_message, CARD, DEVICE)

上のpythonスクリプトを実行すると

Please input recoding time>>>3
ALSA lib pcm_dmix.c:1022:(snd_pcm_dmix_open) unable to open slave
ALSA lib pcm.c:2239:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2239:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
ALSA lib pcm.c:2239:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
ALSA lib pcm.c:2239:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.hdmi
ALSA lib pcm.c:2239:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.hdmi
ALSA lib pcm.c:2239:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.modem
ALSA lib pcm.c:2239:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.modem
ALSA lib pcm.c:2239:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.phoneline
ALSA lib pcm.c:2239:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.phoneline
ALSA lib pulse.c:243:(pulse_connect) PulseAudio: Unable to connect: Connection refused

ALSA lib pulse.c:243:(pulse_connect) PulseAudio: Unable to connect: Connection refused

ALSA lib pcm_dmix.c:1022:(snd_pcm_dmix_open) unable to open slave
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
jack server is not running or cannot be started

こんにちは!今日もたくさん話そう
Traceback (most recent call last):
  File "dialogue_test.py", line 88, in <module>
    talk(talk_message, CARD, DEVICE)
NameError: name 'talk' is not defined

というふうにエラーになってしまします
どうやって解決できるでしょうか

詳細情報

このスクリプトに関係するAPIまたはアプリ

  • requests (PythonのHTTPライブラリ)
  • pyaudio (pythonでマイク入力)
  • AquesTalkPi (合成音声)
  • docomo雑談API (会話するためのAPI)
  • docomo音声認識API (音声を認識してTEXTに変換するAPI)*NTTじゃない方のやつ

環境

  • raspberry pi 2 model B
  • Python 2.7.9

参考サイト

スクリプトの出処(上のスクリプトは若干変えてます)

P.S.

APIKeyとレート(RATE)は正しく入力しているはずです

下の方からインデントを改善したほうがいいと言われますした
しかしインデントを正しく(サンプルコードに)合わせると

こんにちはー。海へ行きたいね
Traceback (most recent call last):
  File "dialogue_test.py", line 89, in <module>
    talk(talk_message, CARD, DEVICE)
  File "dialogue_test.py", line 44, in talk
    res = subprocess.check_output('/home/pi/aquestalkpi/AquesTalkPi " ' + message.encode('utf-8') + ' " | aplay -Dhw:{},{}', stderr=subprocess.STDOUT, shell=True)
  File "/usr/lib/python2.7/subprocess.py", line 573, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '/home/pi/aquestalkpi/AquesTalkPi " こんにちはー。海へ行きたいね " | aplay -Dhw:{},{}' returned non-zero exit status 1

というようなエラーが出てきました
どうすればいいでしょうか?