matcha-en-playback.pas
6.4 KB
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
{ Copyright (c) 2025 Xiaomi Corporation }
program matcha_en_playback;
{
This file shows how to use the text to speech API of sherpa-onnx
with MatchaTTS models.
It generates speech from text and saves it to a wave file.
Note that it plays the audio back as it is still generating.
}
{$mode objfpc}
uses
{$ifdef unix}
cthreads,
{$endif}
SysUtils,
dos,
ctypes,
portaudio,
sherpa_onnx;
var
CriticalSection: TRTLCriticalSection;
Tts: TSherpaOnnxOfflineTts;
Audio: TSherpaOnnxGeneratedAudio;
Resampler: TSherpaOnnxLinearResampler;
Text: AnsiString;
Speed: Single = 1.0; {Use a larger value to speak faster}
SpeakerId: Integer = 0;
Buffer: TSherpaOnnxCircularBuffer;
FinishedGeneration: Boolean = False;
FinishedPlaying: Boolean = False;
Version: String;
EnvStr: String;
Status: Integer;
NumDevices: Integer;
DeviceIndex: Integer;
DeviceInfo: PPaDeviceInfo;
{ If you get EDivByZero: Division by zero error, please change the sample rate
to the one supported by your microphone.
}
DeviceSampleRate: Integer = 48000;
I: Integer;
Param: TPaStreamParameters;
Stream: PPaStream;
Wave: TSherpaOnnxWave;
function GenerateCallback(
Samples: pcfloat; N: cint32;
Arg: Pointer): cint; cdecl;
begin
EnterCriticalSection(CriticalSection);
try
if Resampler <> nil then
Buffer.Push(Resampler.Resample(Samples, N, False))
else
Buffer.Push(Samples, N);
finally
LeaveCriticalSection(CriticalSection);
end;
{ 1 means to continue generating; 0 means to stop generating. }
Result := 1;
end;
function PlayCallback(
input: Pointer; output: Pointer;
frameCount: culong;
timeInfo: PPaStreamCallbackTimeInfo;
statusFlags: TPaStreamCallbackFlags;
userData: Pointer ): cint; cdecl;
var
Samples: TSherpaOnnxSamplesArray;
I: Integer;
begin
EnterCriticalSection(CriticalSection);
try
if Buffer.Size >= frameCount then
begin
Samples := Buffer.Get(Buffer.Head, FrameCount);
Buffer.Pop(FrameCount);
end
else if Buffer.Size > 0 then
begin
Samples := Buffer.Get(Buffer.Head, Buffer.Size);
Buffer.Pop(Buffer.Size);
SetLength(Samples, frameCount);
end
else
SetLength(Samples, frameCount);
for I := 0 to frameCount - 1 do
pcfloat(output)[I] := Samples[I];
if (Buffer.Size > 0) or (not FinishedGeneration) then
Result := paContinue
else
begin
Result := paComplete;
FinishedPlaying := True;
end;
finally
LeaveCriticalSection(CriticalSection);
end;
end;
function GetOfflineTts: TSherpaOnnxOfflineTts;
var
Config: TSherpaOnnxOfflineTtsConfig;
begin
Config.Model.Matcha.AcousticModel := './matcha-icefall-en_US-ljspeech/model-steps-3.onnx';
Config.Model.Matcha.Vocoder := './vocos-22khz-univ.onnx';
Config.Model.Matcha.Tokens := './matcha-icefall-en_US-ljspeech/tokens.txt';
Config.Model.Matcha.DataDir := './matcha-icefall-en_US-ljspeech/espeak-ng-data';
Config.Model.NumThreads := 1;
Config.Model.Debug := False;
Config.MaxNumSentences := 1;
Result := TSherpaOnnxOfflineTts.Create(Config);
end;
begin
Tts := GetOfflineTts;
if Tts.GetSampleRate <> DeviceSampleRate then
Resampler := TSherpaOnnxLinearResampler.Create(Tts.GetSampleRate, DeviceSampleRate);
Version := String(Pa_GetVersionText);
WriteLn('Version is ', Version);
Status := Pa_Initialize;
if Status <> paNoError then
begin
WriteLn('Failed to initialize portaudio, ', Pa_GetErrorText(Status));
Exit;
end;
NumDevices := Pa_GetDeviceCount;
WriteLn('Num devices: ', NumDevices);
DeviceIndex := Pa_GetDefaultOutputDevice;
if DeviceIndex = paNoDevice then
begin
WriteLn('No default output device found');
Pa_Terminate;
Exit;
end;
EnvStr := GetEnv('SHERPA_ONNX_MIC_DEVICE');
if EnvStr <> '' then
begin
DeviceIndex := StrToIntDef(EnvStr, DeviceIndex);
WriteLn('Use device index from environment variable SHERPA_ONNX_MIC_DEVICE: ', EnvStr);
end;
for I := 0 to (NumDevices - 1) do
begin
DeviceInfo := Pa_GetDeviceInfo(I);
if I = DeviceIndex then
{ WriteLn(Format(' * %d %s', [I, DeviceInfo^.Name])) }
WriteLn(Format(' * %d %s', [I, AnsiString(DeviceInfo^.Name)]))
else
WriteLn(Format(' %d %s', [I, AnsiString(DeviceInfo^.Name)]));
end;
WriteLn('Use device ', DeviceIndex);
WriteLn(' Name ', Pa_GetDeviceInfo(DeviceIndex)^.Name);
WriteLn(' Max output channels ', Pa_GetDeviceInfo(DeviceIndex)^.MaxOutputChannels);
Initialize(Param);
Param.Device := DeviceIndex;
Param.ChannelCount := 1;
Param.SampleFormat := paFloat32;
param.SuggestedLatency := Pa_GetDeviceInfo(DeviceIndex)^.DefaultHighOutputLatency;
param.HostApiSpecificStreamInfo := nil;
Buffer := TSherpaOnnxCircularBuffer.Create(30 * DeviceSampleRate);
{ Note(fangjun): PortAudio invokes PlayCallback in a separate thread. }
Status := Pa_OpenStream(stream, nil, @Param, DeviceSampleRate, paFramesPerBufferUnspecified, paNoFlag,
PPaStreamCallback(@PlayCallback), nil);
if Status <> paNoError then
begin
WriteLn('Failed to open stream, ', Pa_GetErrorText(Status));
Pa_Terminate;
Exit;
end;
InitCriticalSection(CriticalSection);
Status := Pa_StartStream(stream);
if Status <> paNoError then
begin
WriteLn('Failed to start stream, ', Pa_GetErrorText(Status));
Pa_Terminate;
Exit;
end;
WriteLn('There are ', Tts.GetNumSpeakers, ' speakers');
Text := 'Friends fell out often because life was changing so fast. The easiest thing in the world was to lose touch with someone.';
Audio := Tts.Generate(Text, SpeakerId, Speed,
PSherpaOnnxGeneratedAudioCallbackWithArg(@GenerateCallback), nil);
FinishedGeneration := True;
SherpaOnnxWriteWave('./matcha-en-playback.wav', Audio.Samples, Audio.SampleRate);
WriteLn('Saved to ./matcha-en-playback.wav');
while not FinishedPlaying do
Pa_Sleep(100); {sleep for 0.1 second }
{TODO(fangjun): Use an event to indicate the play is finished}
DoneCriticalSection(CriticalSection);
FreeAndNil(Tts);
FreeAndNil(Resampler);
Status := Pa_CloseStream(stream);
if Status <> paNoError then
begin
WriteLn('Failed to close stream, ', Pa_GetErrorText(Status));
Exit;
end;
Status := Pa_Terminate;
if Status <> paNoError then
begin
WriteLn('Failed to deinitialize portaudio, ', Pa_GetErrorText(Status));
Exit;
end;
end.