e novamente dll e mercado - página 27

 
Alexsandr San:

aqui está a primeira execução - carregou um arquivo de texto com texto russo, alguns rabiscos - mas guardou, salve o arquivo como .wav


copiado e colado - obteve um arquivo.wav no arquivo salvo em.wav.

Instantâneo2

Arquivos anexados:
 
Nikolai Karetnikov:

bem, aqui está o problema do Google

Eles dão o fluxo na Base64. Consegui convertê-lo para mp3, mas não com LINEAR16.

LINEAR16 deve ser convertido para wav

O conteúdo de áudio retornado como LINEAR16 também contém um cabeçalho WAV.
Method: text.synthesize  |  Cloud Text-to-Speech  |  Google Cloud
Method: text.synthesize  |  Cloud Text-to-Speech  |  Google Cloud
  • cloud.google.com
Synthesizes speech synchronously: receive results after all text input has been processed. Request body The request body contains data with the following structure: Fields Response body If successful, the response body contains data with the following structure: The message returned to the client by the method. Fields The audio data bytes...
 

pergunta aos especialistas

Referindo-se a um serviço Google em código

No Google

1. apenas um cabeçalho

2. A chave é passada via url

3. controlamos o motor através do arquivo json.

No encaracolado, é assim

curl -X POST -H "Content-Type: application/json" -d @request.json https://texttospeech.googleapis.com/v1/text:synthesize?key=AIzaSyCaLxPh84wXpLkT-zOE04MlvHj3JhLXU0w

request.json

{"input":{"text":"M"},"voice":{"languageCode":"en-gb"},"audioConfig":{"audioEncoding":"LINEAR16"}}

o encaracolado obtém a resposta correta



Agora, implemente isto com WebRequest


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnStart()
  {

   char    post[],result[];
   string  url="https://texttospeech.googleapis.com/v1/text:synthesize?key=AIzaSyCaLxPh84wXpLkT-zOE04MlvHj3JhLXU0w";
   string  headers;
   string  result_headers;
   int     status;
   
   
   string jsonbody;
   headers = "Content-Type: application/json";
//---

// original json file
//{"input":{"text":"M"},"voice":{"languageCode":"en-gb"},"audioConfig":{"audioEncoding":"LINEAR16"}}
////

  jsonbody = "{\"input\":{\"text\":\"M\"},\"voice\":{\"languageCode\":\"en-gb\"},\"audioConfig\":{\"audioEncoding\":\"LINEAR16\"}}";
  StringToCharArray(jsonbody,post);
  status=WebRequest("POST",url,headers,100000,post,result,result_headers);
   
   if(status==-1)
     {
      Print("Ошибка в WebRequest. Код ошибки  =",GetLastError());
      //---
      StringSetLength(url,StringFind(url,"/",8));
      MessageBox("Необходимо добавить адрес '"+url+"' в список разрешенных URL во вкладке 'Советники'","Ошибка",MB_ICONINFORMATION);
     }
   else
     {
      if(status==200)
        {
         //--- успешная загрузка
         PrintFormat("Файл успешно загружен, размер %d байт.",ArraySize(result));
         PrintFormat("Заголовки сервера: %s",result_headers);
         //--- сохраняем данные в файл
         int filehandle=FileOpen("result.wav",FILE_WRITE|FILE_BIN);
         if(filehandle!=INVALID_HANDLE)
           {
            //--- сохраняем содержимое массива result[] в файл
            FileWriteArray(filehandle,result,0,ArraySize(result));
            //--- закрываем файл
            FileClose(filehandle);
            PlaySound("\\Files\\test.mp3");
           }
         else
            Print("Ошибка в FileOpen. Код ошибки =",GetLastError());
        }
      else
         PrintFormat("Ошибка загрузки '%s', код %d",url,status);
     }
  }

Mas a resposta volta

2020.06.02 11:52:15.887 GoogleVoice (EURUSD,H1) Ошибка загрузки 'https://texttospeech.googleapis.com/v1/text:synthesize?key=AIzaSyCaLxPh84wXpLkT-zOE04MlvHj3JhLXU0w', код 400

como se o servidor não entendesse a matriz enviada para ele na variável json short

Ou estou formando a matriz de forma incorreta ou algo mais?

 
TheXpert:

LINEAR16 deve ser ondulável

deve! ) E é.

A razão é.

se você remover caracteres extras e "alimentar" a corda limpa na Base64, você recebe um arquivo wav PlaySound legível

 
Nikolai Karetnikov:

deve! ) E citado.

A razão é.

se você remover caracteres extras e "alimentar" a corda limpa para Base64, você recebe um arquivo wav PlaySound

é um json :-) de uma maneira agradável, você deve obter o valor da chave AudioContent

 
Nikolai Karetnikov:


Você pode não ser capaz de lê-lo, então

         int filehandle=FileOpen("result.wav",FILE_WRITE|FILE_BIN);
         if(filehandle!=INVALID_HANDLE)
           {
            //--- сохраняем содержимое массива result[] в файл
            FileWriteArray(filehandle,result,0,ArraySize(result));
            //--- закрываем файл
            FileClose(filehandle);
            PlaySound("\\Files\\test.mp3");
você recebe arquivos diferentes
 
Alexsandr San:

Você pode não ser capaz de lê-lo, e é por isso

Os arquivos ficam diferentes

Aexecução do programa é interrompida na etapa WebRequest, não chega aos arquivos ))))

 
Maxim Kuznetsov:

é um json :-) de uma maneira agradável, você precisa obter o valor do conteúdo de áudio

Ah, certo! Obrigado!!! )))

 
Nikolai Karetnikov:

Mas a resposta volta

como se o servidor não entendesse o conjunto json curto

Ou estou formando a própria matriz de forma incorreta ou algo mais?

O problema é o caráter nulo do trailing.

void OnStart()
  {

   char    post[],result[];
   string  url="https://texttospeech.googleapis.com/v1/text:synthesize?key=AIzaSyCaLxPh84wXpLkT-zOE04MlvHj3JhLXU0w";
   string  headers;
   string  result_headers;
   int     status;
   
   
   string jsonbody;
   headers = "Content-Type: application/json";
//---

// original json file
//{"input":{"text":"M"},"voice":{"languageCode":"en-gb"},"audioConfig":{"audioEncoding":"LINEAR16"}}
////

  jsonbody = "{\"input\":{\"text\":\"M\"},\"voice\":{\"languageCode\":\"en-gb\"},\"audioConfig\":{\"audioEncoding\":\"LINEAR16\"}}";
  ArrayResize(post, StringToCharArray(jsonbody,post) - 1);
  status=WebRequest("POST",url,headers,100000,post,result,result_headers);
   
   if(status==-1)
     {
      Print("Ошибка в WebRequest. Код ошибки  =",GetLastError());
      //---
      StringSetLength(url,StringFind(url,"/",8));
      MessageBox("Необходимо добавить адрес '"+url+"' в список разрешенных URL во вкладке 'Советники'","Ошибка",MB_ICONINFORMATION);
     }
   else
     {
      if(status==200)
        {
         //--- успешная загрузка
         PrintFormat("Файл успешно загружен, размер %d байт.",ArraySize(result));
         PrintFormat("Заголовки сервера: %s",result_headers);
         //--- сохраняем данные в файл
         int filehandle=FileOpen("result.wav",FILE_WRITE|FILE_BIN);
         if(filehandle!=INVALID_HANDLE)
           {
            //--- сохраняем содержимое массива result[] в файл
            FileWriteArray(filehandle,result,0,ArraySize(result));
            //--- закрываем файл
            FileClose(filehandle);
            PlaySound("\\Files\\test.mp3");
           }
         else
            Print("Ошибка в FileOpen. Код ошибки =",GetLastError());
        }
      else
      {
         PrintFormat("Ошибка загрузки '%s', код %d",url,status);
         Print("result: ", CharArrayToString(result));
      }
     }
  }

e se você receber um erro de solicitação na web, há informações adicionais muito possíveis no parâmetro de resultado.

Por exemplo:

2020.06.02 12:29:27.935 google_speech (USDRUB,M30)      Ошибка загрузки 'https://texttospeech.googleapis.com/v1/text:synthesize?key=AIzaSyCaLxPh84wXpLkT-zOE04MlvHj3JhLXU0w', код 400
2020.06.02 12:29:27.935 google_speech (USDRUB,M30)      result: {
2020.06.02 12:29:27.935 google_speech (USDRUB,M30)        "error": {
2020.06.02 12:29:27.935 google_speech (USDRUB,M30)          "code": 400,
2020.06.02 12:29:27.935 google_speech (USDRUB,M30)          "message": "Invalid JSON payload received. Parsing terminated before end of input.\ncoding\":\"LINEAR16\"}}\u0000\n                    ^",
2020.06.02 12:29:27.935 google_speech (USDRUB,M30)          "status": "INVALID_ARGUMENT"
2020.06.02 12:29:27.935 google_speech (USDRUB,M30)        }
2020.06.02 12:29:27.935 google_speech (USDRUB,M30)      }
 
TheXpert:

o problema é o caráter nulo terminante.

e se você receber um erro de solicitação na web, pode muito bem haver informações extras no parâmetro de resultado.

por exemplo:

Obrigado! )