今天写完AI儿童故事的项目,调通了三个模型分别是文本生成,语音合成,和ai作画。
其中因为ai作画免费额度低,试错次数少,在刚开始无脑用AI导致试错很多,后面看文档才修改过了错误参数
以下是文本生成,和语音合成示例代码,只需要替换其中api密钥即可生成
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class QianfanApiTest {
private static final String BASE_URL = "https://qianfan.baidubce.com/v2";
private static final String API_KEY = "";// 配置超时时间的 OkHttpClient
private static final OkHttpClient client = new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS) // 连接超时.readTimeout(60, TimeUnit.SECONDS) // 读取超时.writeTimeout(30, TimeUnit.SECONDS) // 写入超时.build();private static final ObjectMapper mapper = new ObjectMapper();public static void main(String[] args) {try {// 测试对话 APIString response = testChatCompletion();System.out.println("API 响应: " + response);} catch (Exception e) {System.err.println("错误信息: " + e.getMessage());e.printStackTrace();}
}/*** 测试对话补全 API*/
public static String testChatCompletion() throws IOException {String url = BASE_URL + "/chat/completions";// 构建请求体Map<String, Object> requestBody = new HashMap<>();requestBody.put("model", "ernie-speed-128k");List<Map<String, String>> messages = new ArrayList<>();// 系统消息Map<String, String> systemMessage = new HashMap<>();systemMessage.put("role", "system");systemMessage.put("content", "你是一个有用的助手");messages.add(systemMessage);// 用户消息Map<String, String> userMessage = new HashMap<>();userMessage.put("role", "user");userMessage.put("content", "你好,写一个5000字的儿童故事");messages.add(userMessage);requestBody.put("messages", messages);// 转换为 JSONString jsonBody = mapper.writeValueAsString(requestBody);System.out.println("请求体: " + jsonBody);// 构建请求Request request = new Request.Builder().url(url).post(RequestBody.create(jsonBody, MediaType.parse("application/json"))).addHeader("Content-Type", "application/json").addHeader("Authorization", "Bearer " + API_KEY).build();System.out.println("开始发送请求...");// 发送请求try (Response response = client.newCall(request).execute()) {if (!response.isSuccessful()) {throw new IOException("HTTP错误: " + response.code() + " - " + response.message());}String responseBody = response.body().string();System.out.println("请求成功!");return responseBody;}
}
}
import okhttp3.;
import org.json.JSONObject;
import java.io.;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;
class SimpleTextToSpeech {
public static final String API_KEY = "";
public static final String SECRET_KEY = "";
public static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder()
.readTimeout(300, TimeUnit.SECONDS)
.build();
public static void main(String[] args) throws IOException {String text = "哈哈啊啊啊啊啊啊啊啊啊啊啊啊啊啊";String outputFile = "speech_output.mp3";boolean success = textToSpeechSimple(text, outputFile);if (success) {System.out.println("语音合成成功!文件: " + outputFile);} else {System.out.println("语音合成失败!");}
}/*** 简化版文本转语音 - 使用GET请求*/
public static boolean textToSpeechSimple(String text, String outputFilePath) throws IOException {String accessToken = getAccessToken();if (accessToken == null) {return false;}try {// 构建GET请求URLString url = "http://tsn.baidu.com/text2audio?"+ "tex=" + URLEncoder.encode(text, "UTF-8")+ "&lan=zh"+ "&cuid=test_user_123"+ "&ctp=1"+ "&tok=" + accessToken+ "&spd=5" // 语速+ "&pit=5" // 音调+ "&vol=5" // 音量+ "&per=0"; // 发音人Request request = new Request.Builder().url(url).get().build();try (Response response = HTTP_CLIENT.newCall(request).execute()) {System.out.println("响应码: " + response.code());if (!response.isSuccessful()) {System.out.println("请求失败: " + response.code());String errorBody = response.body().string();System.out.println("错误信息: " + errorBody);return false;}// 检查响应类型String contentType = response.header("Content-Type");System.out.println("响应类型: " + contentType);if (contentType != null && contentType.contains("audio")) {// 保存音频文件try (InputStream inputStream = response.body().byteStream();FileOutputStream outputStream = new FileOutputStream(outputFilePath)) {byte[] buffer = new byte[4096];int bytesRead;long totalBytes = 0;while ((bytesRead = inputStream.read(buffer)) != -1) {outputStream.write(buffer, 0, bytesRead);totalBytes += bytesRead;}System.out.println("音频文件大小: " + totalBytes + " 字节");}return true;} else {// 读取错误信息String errorResponse = response.body().string();System.out.println("API返回错误: " + errorResponse);// 尝试解析错误信息try {JSONObject errorJson = new JSONObject(errorResponse);System.out.println("错误码: " + errorJson.optInt("err_no"));System.out.println("错误信息: " + errorJson.optString("err_msg"));} catch (Exception e) {System.out.println("无法解析错误信息");}return false;}}} catch (Exception e) {System.out.println("请求异常: " + e.getMessage());e.printStackTrace();return false;}
}/*** 获取访问令牌*/
static String getAccessToken() throws IOException {try {MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");RequestBody body = RequestBody.create(mediaType,"grant_type=client_credentials&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY);Request request = new Request.Builder().url("https://aip.baidubce.com/oauth/2.0/token").method("POST", body).addHeader("Content-Type", "application/x-www-form-urlencoded").build();try (Response response = HTTP_CLIENT.newCall(request).execute()) {String responseBody = response.body().string();System.out.println("Token获取响应: " + responseBody);JSONObject jsonResponse = new JSONObject(responseBody);return jsonResponse.getString("access_token");}} catch (Exception e) {System.out.println("获取token异常: " + e.getMessage());return null;}
}
}