Sample code for 30+ languages & platforms
Zig

IBM Cloud - Text to Speech - Synthesize Audio (POST)

See more IBM Text to Speech Examples

Synthesizes text to audio that is spoken in the specified voice. Uses a POST which allows for more text to be synthesized.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // This example assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    const http = try chilkat.Http.init();
    defer http.deinit();

    http.setLogin("apikey");
    http.setPassword("my_apikey");
    http.setBasicAuth(true);

    // Send the following request:

    // curl -X POST -u "apikey:{apikey}"
    //    --header "Content-Type: application/json"
    //    --header "Accept: audio/wav"
    //    --data "{\"text\":\"When life gives you lemons, order the lobster tail.\"}"
    //    --output lobster.wav "{url}/v1/synthesize?voice=en-US_AllisonV3Voice"

    // Use your base URL shown in the credentials web page (below your apikey)
    const my_base_url = "https://api.us-south.text-to-speech.watson.cloud.ibm.com/instances/31941e96-7b89-4d56-8993-9cd8f18ec2d8";

    const sb_url = try chilkat.StringBuilder.init();
    defer sb_url.deinit();
    sb_url.append(my_base_url) catch {};
    sb_url.append("/v1/synthesize?voice=en-US_AllisonV3Voice") catch {};

    http.setAccept("audio/wav");

    const json = try chilkat.JsonObject.init();
    defer json.deinit();
    json.updateString("text", "When life gives you lemons, order the lobster tail.") catch {};

    const url = try sb_url.getAsString(alloc);
    const resp = try chilkat.HttpResponse.init();
    defer resp.deinit();
    http.httpJson("POST", url, json, "application/json", resp) catch {
        std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
        return;
    };

    const resp_status_code = resp.getStatusCode();
    std.debug.print("response status code = {d}\n", .{resp_status_code});

    if (resp_status_code == 200) {
        try resp.saveBodyBinary("qa_output/lobster.wav");
        std.debug.print("Success!\n", .{});
    } else {
        std.debug.print("{s}\n", .{try resp.getBodyStr(alloc)});
    }
}