少年修仙传客户端代码仓库
lcy
2024-12-16 a39c35fc6449430cd02bccb681c4a0a880e46cd9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
using LitJson;
using System;
using UnityEngine;
using System.Collections.Generic;
 
 
public class SpeechTranslate : Singleton<SpeechTranslate>
 
{
    public const int AUDIO_TIMELIMIT = 8;//秒
 
    static readonly string serverURL = "http://vop.baidu.com/server_api";
    static string token = "";
 
    static readonly string apiKey = "qb8RdIh80K9LsGtNS0S1f2b9";
    static readonly string secretKey = "1f6050e7c508e8bb8c598bac1cea067a";
    static readonly string cuid = "123456789";
 
    bool m_IsGetToken = false;
    public bool gotToken { get { return m_IsGetToken; } }
 
    bool m_Busy = false;
    public bool busy { get { return m_Busy; } }
 
    public event Action<int, bool, string> translateResultEvent = null;
    Queue<int> translateQueue = new Queue<int>();
 
    public void RequestGetToken()
    {
        //var url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials" + "&client_id=" + apiKey + "&client_secret=" + secretKey;
        //HttpRequest.Instance.RequestHttpGet(url, HttpRequest.defaultHttpContentType, 2, OnGetToken);
    }
 
    private void OnGetToken(bool _ok, string _result)
    {
        if (_ok)
        {
            if (!string.IsNullOrEmpty(_result))
            {
                JsonData data = JsonMapper.ToObject(_result);
                token = data["access_token"].ToString();
                m_IsGetToken = true;
            }
        }
    }
 
    public void ReqeustVoiceTranslate(int _voiceInstanceId, byte[] _data)
    {
        if (m_IsGetToken && _data != null)
        {
            JsonData json = new JsonData();
            json["format"] = "wav";
            json["rate"] = VoiceSettings.frequency;
            json["channel"] = 1;
            json["token"] = token;
            json["cuid"] = cuid;
            json["len"] = _data.Length;
            json["speech"] = Convert.ToBase64String(_data);
 
            translateQueue.Enqueue(_voiceInstanceId);
            HttpRequest.Instance.RequestHttpPost(serverURL, json.ToJson(), HttpRequest.jsonHttpContentType, 1, OnGetTranslateResult);
            Debug.Log("serverURL" + serverURL);
            m_Busy = true;
        }
    }
 
    private void OnGetTranslateResult(bool _ok, string _result)
    {
        m_Busy = false;
        var instanceId = translateQueue.Dequeue();
 
        if (!_ok)
        {
            if (translateResultEvent != null)
            {
                translateResultEvent(instanceId, false, string.Empty);
            }
            return;
        }
 
        JsonData data = JsonMapper.ToObject(_result);
        if (data["err_msg"].ToString() == "success.")
        {
            var content = data["result"][0].ToString();
            if (content.EndsWith(","))
            {
                content = content.Substring(0, content.Length - 1);
            }
 
            if (translateResultEvent != null)
            {
                translateResultEvent(instanceId, true, content);
            }
        }
        else
        {
            if (translateResultEvent != null)
            {
                translateResultEvent(instanceId, false, string.Empty);
            }
            Debug.Log("当前声音质量不合格:"+ data["err_msg"].ToString());
        }
    }
 
    static float[] samples = new float[VoiceSettings.frequency * AUDIO_TIMELIMIT];
 
    public static byte[] AudioCompress(AudioClip _clip, int _seconds)
    {
        if (_clip == null)
        {
            Debug.LogError("录音数据为空");
            return null;
        }
 
        _clip.GetData(samples, 0);
 
        byte[] outData = new byte[VoiceSettings.frequency * _seconds * 2];
 
        int rescaleFactor = 32767; //to convert float to Int16   
 
        for (int i = 0; i < VoiceSettings.frequency * _seconds; i++)
        {
            short temshort = (short)(samples[i] * rescaleFactor);
 
            if (temshort == 0)
            {
                outData[i * 2] = 0;
                outData[i * 2 + 1] = 0;
            }
            else
            {
                byte[] temdata = BitConverter.GetBytes(temshort);
 
                outData[i * 2] = temdata[0];
                outData[i * 2 + 1] = temdata[1];
            }
        }
 
        if (outData == null || outData.Length <= 0)
        {
            Debug.LogError("录音数据为空");
            return null;
        }
 
        return outData;
    }
 
    public void AudioCompress(int _instanceId, AudioClip _clip)
    {
        if (_clip == null || VoiceCodec.IsBusy)
        {
            Debug.LogError("录音数据为空");
            return;
        }
        _clip.GetData(samples, 0);
        var _instance = _instanceId;
        VoiceCodec.Encode(samples, (byte[] encode) =>
         {
             VoiceWarehouse.SaveVoice(_instance, encode);
         });
    }
}