-
Notifications
You must be signed in to change notification settings - Fork 0
/
WavRecorder.cs
109 lines (90 loc) · 3.14 KB
/
WavRecorder.cs
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
using System.Collections;
using System.Collections.Generic;
using System.IO;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class WavRecorder : MonoBehaviour
{
public Button startButton;
public Button stopButton;
public TextMeshProUGUI text;
private AudioClip clip;
private byte[] bytes;
private bool recording;
private RunWhisper runWhisper;
private void Start()
{
runWhisper = this.GetComponent<RunWhisper>();
//给startbutton添加事件
startButton.onClick.AddListener(StartRecording);
stopButton.onClick.AddListener(StopRecording);
stopButton.gameObject.SetActive(false);
}
private void Update()
{
if (recording && Microphone.GetPosition(null) >= clip.samples)
{
StopRecording();
}
}
public void StartRecording()
{
stopButton.gameObject.SetActive(true);
startButton.gameObject.SetActive(false);
text.color = Color.white;
text.text = "录音中......";
//录制16k的wav
clip = Microphone.Start(null, false, 30, 16000);
recording = true;
}
public void StopRecording()
{
stopButton.gameObject.SetActive(false);
startButton.gameObject.SetActive(true);
var position = Microphone.GetPosition(null);
Microphone.End(null);
var samples = new float[position * clip.channels];
clip.GetData(samples, 0);
bytes = EncodeAsWAV(samples, clip.frequency, clip.channels);
recording = false;
//保存wav
Debug.Log(Application.persistentDataPath);
//文件路径
string filename = Application.persistentDataPath + "/output.wav";
using (FileStream fs = new FileStream(filename,FileMode.Create,FileAccess.Write))
using (BinaryWriter writer = new BinaryWriter(fs))
{
writer.Write(bytes);
}
runWhisper.audioClip = clip;
runWhisper.StartASR();
}
private byte[] EncodeAsWAV(float[] samples, int frequency, int channels)
{
using (var memoryStream = new MemoryStream(44 + samples.Length * 2))
{
using (var writer = new BinaryWriter(memoryStream))
{
writer.Write("RIFF".ToCharArray());
writer.Write(36 + samples.Length * 2);
writer.Write("WAVE".ToCharArray());
writer.Write("fmt ".ToCharArray());
writer.Write(16);
writer.Write((ushort)1);
writer.Write((ushort)channels);
writer.Write(frequency);
writer.Write(frequency * channels * 2);
writer.Write((ushort)(channels * 2));
writer.Write((ushort)16);
writer.Write("data".ToCharArray());
writer.Write(samples.Length * 2);
foreach (var sample in samples)
{
writer.Write((short)(sample * short.MaxValue));
}
}
return memoryStream.ToArray();
}
}
}