参照下面的unity样式写一个新的接口 httpsgenshinvoicetopapispeaker=胡桃&text=你好&format=wav&length=1&noise=05&noisew=09&sdp_ratio=02using System;using SystemCollections;using UnityEngine;using UnityEngineNetworking;publ
根据提供的Unity样式,编写一个新的接口。该接口使用OpenAI的语音识别API,并将音频转换为文本。
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public class OpenAISpeechToText : STT
{
[SerializeField] private string api_key;
private string m_SpeechRecognizeURL;
private void Awake()
{
m_SpeechRecognizeURL = "https://api.openai.com/v1/audio/transcriptions";
}
public override void SpeechToText(AudioClip _clip, Action<string> _callback)
{
byte[] _audioData = WavUtility.FromAudioClip(_clip);
StartCoroutine(SendAudioData(_audioData, _callback));
}
private IEnumerator SendAudioData(byte[] audioBytes, Action<string> _callback)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
WWWForm form = new WWWForm();
form.AddBinaryData("file", audioBytes, "sample.wav", "audio/wav");
form.AddField("model", "whisper-1");
UnityWebRequest www = UnityWebRequest.Post(m_SpeechRecognizeURL, form);
www.SetRequestHeader("Authorization", "Bearer " + api_key);
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.LogError("Error sending audio file: " + www.error);
}
else
{
Response _response = JsonUtility.FromJson<Response>(www.downloadHandler.text);
_callback(_response.text);
}
stopwatch.Stop();
Debug.Log("OpenAI语音识别耗时:" + stopwatch.Elapsed.TotalSeconds);
}
[Serializable]
public class Response
{
public string text = string.Empty;
}
}
请注意,在使用此代码之前,您需要将api_key设置为您自己的OpenAI API密钥,并确保项目中包含WavUtility类的定义。
原文地址: https://www.cveoy.top/t/topic/i8t2 著作权归作者所有。请勿转载和采集!