Как отправить поток аудио WAV в diaglogflow - PullRequest
0 голосов
/ 05 июля 2019

У меня есть JSON с полем, которое содержит Aduio (WAV). Теперь я хочу отправить его в диалоговое окно.

Как показано в коде, после декодирования данных я хочу отправить их непосредственно в диалоговый поток, а не сохранять их в файл, а затем передавать их в диалоговый поток.


# instead of audio_file_path int the below method, i want to pass a variable that contains audio data

def detect_intent_stream(project_id, session_id, audio_file_path,
                         language_code):   
    session_client = dialogflow.SessionsClient()

    audio_encoding = dialogflow.enums.AudioEncoding.AUDIO_ENCODING_LINEAR_16
    sample_rate_hertz = 16000

    session_path = session_client.session_path(project_id, session_id)
    print('Session path: {}\n'.format(session_path))

    def request_generator(audio_config, audio_file_path):
        query_input = dialogflow.types.QueryInput(audio_config=audio_config)

        # The first request contains the configuration.
        yield dialogflow.types.StreamingDetectIntentRequest(
            session=session_path, query_input=query_input)

        # Here we are reading small chunks of audio data from a local
        # audio file.  In practice these chunks should come from
        # an audio input device.
        with open(audio_file_path, 'rb') as audio_file:
            while True:
                chunk = audio_file.read(4096)
                if not chunk:
                    break
                # The later requests contains audio data.
                yield dialogflow.types.StreamingDetectIntentRequest(
                    input_audio=chunk)

    audio_config = dialogflow.types.InputAudioConfig(
        audio_encoding=audio_encoding, language_code=language_code,
        sample_rate_hertz=sample_rate_hertz)

    requests = request_generator(audio_config, audio_file_path)
    responses = session_client.streaming_detect_intent(requests)

    print('=' * 20)
    for response in responses:
        print('Intermediate transcript: "{}".'.format(
                response.recognition_result.transcript))

    # Note: The result from the last response is the final transcript along
    # with the detected content.
    query_result = response.query_result

    print('Fulfillment text: {}\n'.format(query_result.fulfillment_text))

# ----------------------------------------------------

data = request.json["data"]  # this contain Audio(WAV) in base64 format

decoded = base64.b64decode(audio)  # decoding base64

# I want this like I am passing "decoded" variable that contains audio data in WAV format instead of audio file path
detect_intent_stream('my_project_id','my_session_id', decoded,'language_code') 

f = open('new.wav', 'wb').write(decoded) # writing the decoded data into file

1 Ответ

0 голосов
/ 21 июля 2019

Во-первых, убедитесь, что данные WAV, которые вы получаете, имеют правильный формат и соответствуют частоте дискретизации (обычно 44100) и правильному количеству аудиоканалов (Dialogflow использует только моно или одноканальный звук).В коде, который они предоставляют, они устанавливают переменную audio_encoding и конфигурацию входного аудио, изучите их.

Далее у вас есть строка данных WAV, но StreamingDetectIntentRequest принимает байты, поэтому вместо преобразования вашего base64 вСтрока, я бы преобразовал его в bytearray

Далее, вместо того, чтобы выдавать звуковые чанки из аудиофайла, получим чанки из байтового массива.

    def request_generator(audio_config, byte_array):
        query_input = dialogflow.types.QueryInput(audio_config=audio_config)

        # The first request contains the configuration.
        yield dialogflow.types.StreamingDetectIntentRequest(
            session=session_path, query_input=query_input) 

        for chunk in range(44, len(byte_array), 4096): # Start at position 44 to discard the wav header
            yield  dialogflow.types.StreamingDetectIntentRequest(
                input_audio=bytes(chunk))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...