在Java中引用SpeechSynthesisResult
类,需先导入相关包,通常是com.alibaba.dashscope.audio.tts.SpeechSynthesisResult
该类代表一次流式语音合成的数据响应,包含音频片段(getAudioFrame()
)和对应的文本时间戳(getTimestamp()
)。
音频数据和时间戳可能会在不同的数据帧中交替返回,因此在处理时需检查这两个方法的返回值是否为空。
使用时,通常配合SpeechSynthesizer
类的streamCall()
方法获取Flowable
,并通过订阅或blockingForEach
等操作处理每个返回的SpeechSynthesisResult
实例。
代码示例:
package com.alibaba.dashscope.sample;
import com.alibaba.dashscope.audio.tts.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.tts.SpeechSynthesisResult;
import com.alibaba.dashscope.audio.tts.SpeechSynthesizer;
import com.alibaba.dashscope.common.ResultCallback;
import com.alibaba.dashscope.common.Status;
import java.util.concurrent.CountDownLatch;
public class Main {
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(1);
SpeechSynthesizer synthesizer = new SpeechSynthesizer();
SpeechSynthesisParam param = SpeechSynthesisParam.builder()
.model("sambert-zhichu-v1")
.text("今天天气怎么样")
.sampleRate(48000)
.enableWordTimestamp(true)
.enablePhonemeTimestamp(true)
.apiKey("your-dashscope-api-key")
.build();
class ReactCallback extends ResultCallback<SpeechSynthesisResult> {
@Override
public void onEvent(SpeechSynthesisResult result) {
if (result.getAudioFrame() != null) {
// do something with the audio frame
System.out.println("audio result length: " + result.getAudioFrame().array().length);
}
if (result.getTimestamp() != null) {
// do something with the timestamp
System.out.println("tiemstamp: " + result.getTimestamp());
}
}
@Override
public void onComplete() {
// do something when the synthesis is done
System.out.println("onComplete!");
latch.countDown();
}
@Override
public void onError(Exception e) {
// do something when an error occurs
System.out.println("onError:" + e);
latch.countDown();
}
}
synthesizer.call(param, new ReactCallback());
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.exit(0);
}
}
参考链接:https://help.aliyun.com/zh/model-studio/developer-reference/sambert-api-reference#8c6c80e003xuy
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。