在线文字转语音适用与多有平台,在线api接口形式

67 阅读1分钟

推荐一个很方便实用的api,在线将文字转化为语音输出,废话不多说,先上代码

<template>
	<view>
		<input v-model="text" placeholder="请输入要生成语音的文字" class="input_style" />
		<view @click="requestAPI" class="btn">生成语音</view>
		
		<view v-if="url && status==='no'" class="btn" @click="playVoice">播放语音</view>
		<view v-else-if="status==='loading'" style="margin-top: 50rpx;">
			<image src="/static/icon_spinner.png" style="width: 68rpx;height: 68rpx;" class="rotating-element"></image>
		</view>
	</view>
</template>

<script>
	// 语音播放器实例
	let mp3 = uni.createInnerAudioContext();
	
	export default {
		data() {
			return {
				text:'',
				status: 'none',
				url: ''
			}
		},
		methods: {
			playVoice(){
				mp3.src = this.url;
				mp3.play();
			},
			requestAPI(){
				if(!this.text || this.text.length < 1){
					uni.showToast({
						title:'请输入内容',
						icon:'none'
					})
					return;
				}
				
				let that = this;
				that.status = 'loading';
				
				uni.request({
					method:'POST',
					url:'https://5555api.com/data/api',
					data:{
						apikey: 'test_app_key_5555api.com',
						action:'queryVoiceByText',
						text: that.text,
					},
					success(res) {
						that.status = 'no';
						console.error('请求成功:', res);
						that.url = res.data.data.data;
					},
					fail() {
						that.status = 'no';
					}
				});
			}
		}
	}
</script>

<style>
	.input_style{
		width: 600rpx;
		margin-left: 74rpx;
		margin-right: 75rpx;
		border: 2rpx solid #12c212;
		padding: 10rpx 20rpx;
		border-radius: 10rpx;
		font-size: 28rpx;
		margin-top: 50rpx;
	}
	
	.btn{
		background-color: #12c212;
		color: #ffffff;
		display: flex;
		width: 450rpx;
		margin-left: 150rpx;
		margin-right: 149rpx;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
		padding: 20rpx 0rpx;
		margin-top: 50rpx;
	}
</style>

只需要给api接口传一个文本内容即可,接口会返回语音文件地址