Search code examples
delphiindyfreepascallazarus

How to connect to VoiceRSS API with my Lazarus/Delphi program?


On the form of my program, there are TIdHTTP and TButton components:

procedure TForm1.Button1Click(Sender: TObject);
var
  HTTP: TIdHTTP;
  AudioFilePath: string;
  AudioFileContent: TMemoryStream;

begin
  AudioFilePath := 'speech.wav'; // Path to the file to which the audio file will be saved

  HTTP := TIdHTTP.Create(nil);
  AudioFileContent := TMemoryStream.Create;
  try
    // Send a request to the VoiceRSS API and receive an audio file
    HTTP.Get('http://api.voicerss.org/?key=1234567890QWERTY&hl=en-us&src=Hello, world!',AudioFileContent);

    // Save the audio file to disk
    AudioFileContent.SaveToFile(AudioFilePath);
  finally
    AudioFileContent.Free;
    HTTP.Free;
  end;
end;

When I just enter this address (but with my API key):

http://api.voicerss.org/?key=1234567890QWERTY&hl=en-us&src=Hello, world!

It automatically starts downloading the audio file where the robot says hello world. But, when I run my program, it shows an error:

image

Nothing ................


Solution

  • The text you are sending to the server contains an unencoded space character in the URL:

    HTTP.Get('http://api.voicerss.org/?key=1234567890QWERTY&hl=en-us&src=Hello, world!',AudioFileContent);
                                                                               ^
    

    The space character needs to be percent-encoded as %20 in a URL:

    HTTP.Get('http://api.voicerss.org/?key=1234567890QWERTY&hl=en-us&src=Hello,%20world!', AudioFileContent);
                                                                               ^^^
    

    A web browser would handle this for you, but you have to do it manually in your code. You can use Indy's TIdURI class to help you with this task (it will also encode other characters that need to be encoded), eg:

    uses
      ..., IdURI;
    
    var
      sText: string;
    
    sText := 'Hello, world!';
    HTTP.Get('http://api.voicerss.org/?key=1234567890QWERTY&hl=en-us&src=' + TIdURI.ParamsEncode(sText), AudioFileContent);