Sample code for 30+ languages & platforms
Zig

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

See more IBM Text to Speech Examples

Synthesizes text to audio that is spoken in the specified voice.

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);

    // 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?accept=ACCEPT_TYPE&voice=CHOSEN_VOICE&text=TEXT_TO_SYNTHESIZE") catch {};

    // Choose "audio/wav" for the output file type.
    var num_replaced: i32 = sb_url.replace("ACCEPT_TYPE", try http.urlEncode(alloc, "audio/wav"));
    // See the choices for voices at https://cloud.ibm.com/apidocs/text-to-speech#synthesize-audio-get
    num_replaced = sb_url.replace("CHOSEN_VOICE", "en-US_MichaelVoice");
    const text_to_synthesize = "When life gives you lemons, order the lobster tail.";
    num_replaced = sb_url.replace("TEXT_TO_SYNTHESIZE", try http.urlEncode(alloc, text_to_synthesize));

    // Send the GET to synthesize the voice.
    // The response file will be contained in bdResponseBody
    const bd_response_body = try chilkat.BinData.init();
    defer bd_response_body.deinit();
    http.quickGetBd(try sb_url.getAsString(alloc), bd_response_body) catch {
        std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
        return;
    };

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

    if (resp_status_code == 200) {
        try bd_response_body.writeFile("qa_output/lobster.wav");
        std.debug.print("Success!\n", .{});
    } else {
        std.debug.print("{s}\n", .{try bd_response_body.getString(alloc, "utf-8")});
    }
}