当前位置: 首页 > news >正文

2025.11.12总结

今天写完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;}
}

}

http://www.jsqmd.com/news/38870/

相关文章:

  • 以太坊的测试网络 - all-in
  • Scala基础学习day01
  • 洛谷 P11965:[GESP202503 七级] 等价消除 ← 位运算(异或) + STL map
  • C 指针数组函数之间的关联
  • 2025.11.12 测试
  • 13. 罗马数字转化为字符串
  • 这封邮件写得真好,是你自己写的吗? 不,是AI写的
  • FFmpeg 官方汇编课程:写出快 5 倍的视频处理代码
  • 四、中断(基于北京迅为电子)
  • List执行Dispose时可释放子元素逻辑占用的List写法
  • Sora 后思考:从 AI 工具到 AI 平台,产业 AGI 又近了一步 - 指南
  • Scapy构建telnet包
  • Spring AI Alibaba 项目源码学习(三)-Graph 执行流程分析
  • 值得复习的题目
  • 逻辑回归原理与案例分析
  • 找唯一特征去重转移DP——CF1210F2 Marek and Matching
  • UEFI Boot Manager
  • 25年11月计数题做题记录
  • 固体废物资源化处理简答题与论述题
  • noip6 多校1
  • CCPC2025哈尔滨站-H. 匹配
  • 通过开发环境部署工具安装qt相关c++开发环境
  • 第23天(简单题中等题 二分查找)
  • Cinema4D 2025保姆级下载安装教程|含安装包获取+新手入门指南
  • 2014 吉林省赛题解 | CCUT应用OJ题解——F[X] + X = N
  • 洛谷 P4859 已经没有什么好害怕的了 题解(DP,二项式反演)
  • 01321:棋盘问题
  • C 变量的作用域与生存周期
  • 模式识别与机器学习课程笔记(11):深度学习 - 详解
  • 05.创建型 - 简单工厂模式(Simple Factory Pattern)