抱歉,你查看的文章已删除

VB.NET 百度api语音合成

简介

百度语音合成服务,基于HTTP请求的REST API接口,将文本转换为可以播放的音频文件。

合成的文件格式为 mp3,pcm(8k及16k),wav(16k),具体见aue参数。若您需要其它格式,音频文件的转换方法请参考“语音识别工具”=>“音频文件转码”一节

本文档描述了使用语音合成服务REST API的方法。

  • 多音字可以通过标注自行定义发音。格式如:重(chong2)报集团。
  • 目前只有中英文混合这一种语言,优先中文发音。示例:" I bought 3 books” 发音 “three”; “ 3 books are bought” 发音 “三”; “我们买了 3 books” 发音“三”

post参数

参数

可需

描述

tex

必填

合成的文本,使用UTF-8编码。小于2048个中文字或者英文数字。(文本在百度服务器内转换为GBK后,长度必须小于4096字节)

tok

必填

开放平台获取到的开发者access_token(见上面的“鉴权认证机制”段落)

cuid

必填

用户唯一标识,用来计算UV值。建议填写能区分用户的机器 MAC 地址或 IMEI 码,长度为60字符以内

ctp

必填

客户端类型选择,web端填写固定值1

lan

必填

固定值zh。语言选择,目前只有中英文混合模式,填写固定值zh

spd

选填

语速,取值0-15,默认为5中语速

pit

选填

音调,取值0-15,默认为5中语调

vol

选填

音量,取值0-15,默认为5中音量

per(基础音库)

选填

度小宇=1,度小美=0,度逍遥=3,度丫丫=4

per(精品音库)

选填

度博文=106,度小童=110,度小萌=111,度米朵=103,度小娇=5

aue

选填

3为mp3格式(默认);4为pcm-16k;5为pcm-8k;6为wav(内容同pcm-16k); 注意aue=4或者6是语音识别要求的格式,但是音频内容不是语音识别要求的自然人发音,所以识别效果会受影响。

tex字段2次urlencode

由于urlencode有两个标准 RFC 1738和RFC 3986. 百度为了更好地兼容,支持1次及2次urlencode, 其中2次urlencode可以覆盖全部的特殊字符。因而推荐传递tex 参数时做2次urlencode编码。

测试用例:“1+1=2”。一次urlencode时,“+”可能会没有合成。

下面送上VB.NET实例源码

引入web
Imports System.Web

窗体代码

Public Class Form1

Dim tk As String, gss As Integer = 3, fname As String = “\temp.mp3”, PP As Integer = 5
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Get_mp3()
    End Sub
post下载MP3过程
Sub Get_mp3()

        On Error Resume Next
        Dim HTTP_WEB As Net.HttpWebRequest
        Dim HTTP_RES As Net.HttpWebResponse
        '----------------------------------------
        Dim URL As String = "http://tsn.baidu.com/text2audio"
        Dim POST_BYT As Byte() = System.Text.Encoding.UTF8.GetBytes(GET_POSTDATA(TextBox1.Text))
        '----------------------------------------
        HTTP_WEB = CType(Net.WebRequest.Create(URL), Net.HttpWebRequest)
        HTTP_WEB.Method = "POST"
        HTTP_WEB.KeepAlive = True
        HTTP_WEB.AllowAutoRedirect = True
        HTTP_WEB.Timeout = 60000
        HTTP_WEB.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0"
        HTTP_WEB.ContentType = "audio/mp3"
        HTTP_WEB.ContentLength = POST_BYT.Length
        HTTP_WEB.Host = "tsn.baidu.com"
        '-------------------------------------------------------
        Dim RES_STR As IO.Stream = HTTP_WEB.GetRequestStream()
        RES_STR.Write(POST_BYT, 0, POST_BYT.Length)
        RES_STR.Flush()
        RES_STR.Close()
        ''-------------------------------------------------------
        HTTP_RES = CType(HTTP_WEB.GetResponse(), Net.HttpWebResponse)
        Dim RES_STREAM As IO.Stream = HTTP_RES.GetResponseStream()
        Dim List As New List(Of Byte), I As Integer, BYT() As Byte
        I = RES_STREAM.ReadByte()
        Do Until I = -1
            List.Add(I)
            I = RES_STREAM.ReadByte()
        Loop
        BYT = List.ToArray
        ''-------------------------------------------------------
        My.Computer.FileSystem.WriteAllBytes(Application.StartupPath & fname, BYT, False)  ''保存文件
        Process.Start(Application.StartupPath & fname)  ''播放文件
        HTTP_RES.Close()
    End Sub
串接post数据包
    Function GET_POSTDATA(ByVal TXT As String) As String
        On Error Resume Next
        Dim PST As New Text.StringBuilder, temp As String
        temp = HttpUtility.UrlEncode(TXT, System.Text.Encoding.GetEncoding("utf-8"))  ''第一次url比编码
        temp = HttpUtility.UrlEncode(temp, System.Text.Encoding.GetEncoding("utf-8")) ''第二次url比编码
        PST.Append("tex=").Append(temp).Append("&")  ''文本
        PST.Append("lan=").Append("zh").Append("&")  ''语言
        PST.Append("cuid=").Append("ac:a5:77:e7:22:0d").Append("&")
        PST.Append("ctp=").Append("1").Append("&")
        PST.Append("aue=").Append(gss).Append("&")  ''文件格式
        PST.Append("spd=").Append(spd.Value).Append("&")  ''语速
        PST.Append("pit=").Append(pit.Value).Append("&") ''语调
        PST.Append("vol=").Append(vol.Value).Append("&") ''音量
        PST.Append("per=").Append(PP).Append("&") ''语音库
        PST.Append("tok=").Append(tk)  ''token
        Return PST.ToString
    End Function
控件事件
    Private Sub per_SelectedIndexChanged(sender As Object, e As EventArgs) Handles per.SelectedIndexChanged
        On Error Resume Next
        Select Case per.Text
            Case "度小宇"
                PP = 1
            Case "度小美"
                PP = 0
            Case "度逍遥"
                PP = 3
            Case "度丫丫"
                PP = 4
            Case "度博文"
                PP = 106
            Case "度小童"
                PP = 110
            Case "度小萌"
                PP = 111
            Case "度米朵"
                PP = 103
            Case "度小娇"
                PP = 5
        End Select
    End Sub

    Private Sub spd_Scroll(sender As Object, e As EventArgs) Handles spd.Scroll
        Label6.Text = spd.Value & "/15"
    End Sub

    Private Sub pit_Scroll(sender As Object, e As EventArgs) Handles pit.Scroll
        Label7.Text = pit.Value & "/15"
    End Sub

    Private Sub vol_Scroll(sender As Object, e As EventArgs) Handles vol.Scroll
        Label8.Text = vol.Value & "/15"
    End Sub
获取token
    Private Function GetAccessToken() As String
        Try
            Dim authHost As String = "https://openapi.baidu.com/oauth/2.0/token"
            Using client As New Net.Http.HttpClient()
                Dim paraList As List(Of KeyValuePair(Of String, String)) = New List(Of KeyValuePair(Of String, String)) From {
                New KeyValuePair(Of String, String)("grant_type", "client_credentials"),
                New KeyValuePair(Of String, String)("client_id", "gjSloBnS3VLZBLzODcxOjf48"),
                New KeyValuePair(Of String, String)("client_secret", "cqnTyRdGyQ2i9fREWhoGly7T6du8I4pS")
            }
                Dim response As Net.Http.HttpResponseMessage = client.PostAsync(authHost, New Net.Http.FormUrlEncodedContent(paraList)).Result
                Dim result As String = response.Content.ReadAsStringAsync().Result
                ''******************************************************************
                Dim js As Object
                js = CreateObject("ScriptControl")
                js.Language = "JScript"
                js.addcode("var json=" & result)
                ''*******************************************************************
                Return js.eval("json.access_token")
            End Using
        Catch ex As Exception
            Return ""
        End Try

    End Function     
 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load            On Error Resume Next          tk = GetAccessToken()        If tk <> "" Then
            Text = "百度语音合成实例--->初始化成功"
        Else
            Text = "百度语音合成实例--->初始化失败!"
            Button1.Enabled = False
        End If
        ''----------------------------------------------------
        fomt.Items.AddRange({"mp3", "pcm-16k", "pcm-8k", "wav"})
        per.Items.AddRange({"度小宇", "度小美", "度逍遥", "度丫丫", "度博文", "度小童", "度小萌", "度米朵", "度小娇"})
        Label6.Text = spd.Value & "/15"
        Label7.Text = pit.Value & "/15"
        Label8.Text = vol.Value & "/15"
    End Sub

    Private Sub Fomt_SelectedIndexChanged(sender As Object, e As EventArgs) Handles fomt.SelectedIndexChanged
        Select Case fomt.Text
            Case "mp3"
                gss = 3
                fname = "\temp.mp3"
            Case "pcm-16k"
                gss = 4
                fname = "\temp.pcm"
            Case "pcm-8k"
                gss = 5
                fname = "\temp.pcm"
            Case "wav"
                gss = 6
                fname = "\temp.wav"
        End Select
    End Sub
End Class

实例下载

https://www.lanzous.com/i7a15mf

今天教程到此就结束啦!

本文分享自微信公众号 - VB小源码(vb_xym)

原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。

原始发表时间:2019-11-10

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

编辑于

VB小源码

128 篇文章36 人订阅

扫码关注云+社区

领取腾讯云代金券