luc117.c (2544B)
1 /* Write a program to convert a given text into an audio file using OpenAI Audio API (TTS). 2 */ 3 /* Let Us C, Chap- 24 (Interaction with ChatGPT through C), Qn No.: B(a) */ 4 5 /* This file is auto-generated by a bot. */ 6 /* This code is not compiled; it is for reference only. */ 7 8 /* NOTE: These programs require the 'libcurl' library to compile. 9 Command: gcc luc117.c -o output -lcurl */ 10 11 12 #include <stdio.h> 13 #include <stdlib.h> 14 #include <string.h> 15 #include <curl/curl.h> 16 17 /* Pre-requisites: 18 1. Install libcurl development package. 19 2. Get OpenAI API Key. 20 */ 21 22 #define API_KEY "YOUR_OPENAI_API_KEY_HERE" 23 24 size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) { 25 size_t written = fwrite(ptr, size, nmemb, stream); 26 return written; 27 } 28 29 int main(void) { 30 CURL *curl; 31 CURLcode res; 32 FILE *fp; 33 34 // JSON Payload construction 35 const char *url = "https://api.openai.com/v1/audio/speech"; 36 const char *data = "{" 37 "\"model\": \"tts-1\"," 38 "\"input\": \"Hello! This is a C program talking to you.\"," 39 "\"voice\": \"alloy\"" 40 "}"; 41 42 struct curl_slist *headers = NULL; 43 char auth_header[100]; 44 sprintf(auth_header, "Authorization: Bearer %s", API_KEY); 45 46 curl_global_init(CURL_GLOBAL_ALL); 47 curl = curl_easy_init(); 48 49 if(curl) { 50 // Set Headers 51 headers = curl_slist_append(headers, "Content-Type: application/json"); 52 headers = curl_slist_append(headers, auth_header); 53 54 // Open file to save audio 55 fp = fopen("output_audio.mp3", "wb"); 56 if(!fp) { 57 printf("Error opening file for writing.\n"); 58 return 1; 59 } 60 61 // Configure CURL 62 curl_easy_setopt(curl, CURLOPT_URL, url); 63 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data); 64 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); 65 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); 66 curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); 67 68 // Perform Request 69 printf("Sending request to OpenAI TTS API...\n"); 70 res = curl_easy_perform(curl); 71 72 if(res != CURLE_OK) 73 fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); 74 else 75 printf("Audio saved to 'output_audio.mp3' successfully.\n"); 76 77 // Cleanup 78 fclose(fp); 79 curl_slist_free_all(headers); 80 curl_easy_cleanup(curl); 81 } 82 83 curl_global_cleanup(); 84 return 0; 85 }