引用
示例
通过RecordVoice组件录制音频,
将录制音频作为参数传入VoiceQuestion组件中,播放音频
csharp
using UnityEngine;
public class UseVoiceQuestion : MonoBehaviour
{
[SerializeField] RecordVoice recordVoice;
[SerializeField] VoiceQuestion voiceQuestion;
KeyCode voiceInputKey = KeyCode.Space;
bool enableVoiceInput = true;
bool isRecordIng = false;
void Awake()
{
recordVoice.OnRecordAudioCompleted += OnRecordVoiceCompleted;
voiceQuestion.OnTextAnswerCompleted += OnTextAnswerCompleted;
voiceQuestion.OnError += OnVoiceQuestionError;
}
void OnRecordVoiceCompleted(AudioClip audioClip)
{
voiceQuestion.InputQuestionAudio(audioClip);
}
void OnTextAnswerCompleted()
{
enableVoiceInput = true;
}
void OnVoiceQuestionError()
{
enableVoiceInput = true;
}
void Update()
{
if (enableVoiceInput == false) return;
if (Input.GetKeyDown(voiceInputKey))
{
if (isRecordIng == false)
{
if (recordVoice.ExistMicrophoneDevice())
{
Debug.Log("录音开始");
isRecordIng = true;
recordVoice.BeginRecord();
}
else
{
Debug.LogError("没有录音设备,无法录音");
}
}
}
if (Input.GetKeyUp(voiceInputKey))
{
if (isRecordIng)
{
Debug.Log("录音结束");
isRecordIng = false;
enableVoiceInput = false;
recordVoice.EndRecord();
}
}
}
void OnGUI()
{
GUI.skin.label.fontSize = 40;
if (enableVoiceInput)
{
if (isRecordIng == false)
GUILayout.Label("按下空格键,进行语音输入");
else
GUILayout.Label("语音录制中");
}
else
{
GUILayout.Label("等待提问结束");
}
}
void OnDestroy()
{
voiceQuestion.OnError -= OnVoiceQuestionError;
voiceQuestion.OnTextAnswerCompleted -= OnTextAnswerCompleted;
recordVoice.OnRecordAudioCompleted -= OnRecordVoiceCompleted;
}
}