当前位置: 首页>数据库>正文

Java调用百度云语音合成【tts 长文本在线合成】

Java调用百度云语音合成【tts 长文本在线合成】,Java调用百度云语音合成【tts 长文本在线合成】_java,第1张

百度云文档  https://ai.baidu.com/ai-doc/SPEECH/ulbxh8rbu
<!--JSONObject-->
<dependency>
	<groupId>org.json</groupId>
	<artifactId>json</artifactId>
	<version>20210307</version>
</dependency>
 
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
 
 
/**
 * 语音合成
 *
 */
@Slf4j
@Component
public class LongSpeechUtils {
 
    public static final String API_KEY = "U92RRV****ag9xZv";
    public static final String SECRET_KEY = "SU05xD****0ziDkM";
 
 
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient.Builder()
            .connectTimeout(60, TimeUnit.SECONDS) // Set the connection timeout
            .readTimeout(300, TimeUnit.SECONDS)    // Set the read timeout
            .build();
 
 
    public static void main(String[] args) throws IOException {
        String text = "文本";
        checkTaskStatus(createTTS(text));
    }
 
 
    /**
     * 长文本在线合成
     *
     * @param text  总字数不超过10万个字符,1个中文字、英文字母、数字或符号均算作1个字符
     * @return
     * @throws IOException
     */
    private static String createTTS(String text) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\n" +
                "    \"text\": \"" + text + "\",\n" +
                "    \"format\": \"mp3-16k\",\n" +
                "    \"voice\": 0,\n" +
                "    \"lang\": \"zh\"\n" +
                "}");
 
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/tts/v1/create?access_token=" + getAccessToken())
                .post(body)
                .addHeader("Content-Type", "application/json")
                .build();
 
        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String responseBody = response.body().string();
                log.info("创建TTS任务响应: {}", responseBody);
 
                String task_id = JSON.parseObject(responseBody).getString("task_id");
                return task_id;
            } else {
                log.info("创建TTS任务失败: {}", response.code());
                return null;
            }
        }
    }
 
    private static String checkTaskStatus(String taskId) throws IOException {
 
        if (StringUtils.isEmpty(taskId)) {
            return "";
        }
 
        String taskStatus = "";
 
        while (!("Success".equals(taskStatus) || "Failed".equals(taskStatus))) {
            // Add a delay before the next query
            try {
                Thread.sleep(1000); // Sleep for 1 seconds (adjust as needed)
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
 
            HashMap<String, Object> map = new HashMap<>();
            ArrayList<Object> list = new ArrayList<>();
            list.add(taskId);
            map.put("task_ids", list);
 
            JSONObject jsonObject = new JSONObject(map);
            String toJSON = jsonObject.toString();
 
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, toJSON);
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rpc/2.0/tts/v1/query?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .build();
 
            try (Response response = HTTP_CLIENT.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
 
                    com.alibaba.fastjson.JSONArray tasksInfo = JSON.parseObject(responseBody).getJSONArray("tasks_info");
 
                    if (tasksInfo.size() > 0) {
                        com.alibaba.fastjson.JSONObject taskInfo = tasksInfo.getJSONObject(0);
                        taskStatus = taskInfo.getString("task_status");
 
                        if ("Success".equals(taskStatus)) {
                            String audioUrl = taskInfo.getJSONObject("task_result").getString("speech_url");
                            log.info("文字转音频: {}", audioUrl);
                            return audioUrl;
                        } else if ("Failed".equals(taskStatus)) {
                            log.info("任务失败: {}", taskStatus);
                        }
                    } else {
                        log.info("未找到任务信息");
                    }
                } else {
                    log.info("检查任务状态失败: {}", response.code());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }
 
 
    /**
     * 从用户的AK,SK生成鉴权签名(Access Token)
     *
     * @return 鉴权签名(Access Token)
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        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();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String access_token = new JSONObject(response.body().string()).getString("access_token");
        return access_token;
    }
}

转发:https://blog.csdn.net/weixin_43652507/article/details/135398417


https://www.xamrdz.com/database/6gw1957498.html

相关文章: