|
| 1 | +{ Copyright (c) 2025 Xiaomi Corporation } |
| 2 | +program kokoro_en_playback; |
| 3 | +{ |
| 4 | +This file shows how to use the text to speech API of sherpa-onnx |
| 5 | +with Kokoro models. |
| 6 | +
|
| 7 | +It generates speech from text and saves it to a wave file. |
| 8 | +
|
| 9 | +Note that it plays the audio back as it is still generating. |
| 10 | +} |
| 11 | + |
| 12 | +{$mode objfpc} |
| 13 | + |
| 14 | +uses |
| 15 | + {$ifdef unix} |
| 16 | + cthreads, |
| 17 | + {$endif} |
| 18 | + SysUtils, |
| 19 | + dos, |
| 20 | + ctypes, |
| 21 | + portaudio, |
| 22 | + sherpa_onnx; |
| 23 | + |
| 24 | +var |
| 25 | + CriticalSection: TRTLCriticalSection; |
| 26 | + |
| 27 | + Tts: TSherpaOnnxOfflineTts; |
| 28 | + Audio: TSherpaOnnxGeneratedAudio; |
| 29 | + Resampler: TSherpaOnnxLinearResampler; |
| 30 | + |
| 31 | + Text: AnsiString; |
| 32 | + Speed: Single = 1.0; {Use a larger value to speak faster} |
| 33 | + SpeakerId: Integer = 7; |
| 34 | + Buffer: TSherpaOnnxCircularBuffer; |
| 35 | + FinishedGeneration: Boolean = False; |
| 36 | + FinishedPlaying: Boolean = False; |
| 37 | + |
| 38 | + Version: String; |
| 39 | + EnvStr: String; |
| 40 | + Status: Integer; |
| 41 | + NumDevices: Integer; |
| 42 | + DeviceIndex: Integer; |
| 43 | + DeviceInfo: PPaDeviceInfo; |
| 44 | + |
| 45 | + { If you get EDivByZero: Division by zero error, please change the sample rate |
| 46 | + to the one supported by your microphone. |
| 47 | + } |
| 48 | + DeviceSampleRate: Integer = 48000; |
| 49 | + I: Integer; |
| 50 | + Param: TPaStreamParameters; |
| 51 | + Stream: PPaStream; |
| 52 | + Wave: TSherpaOnnxWave; |
| 53 | + |
| 54 | +function GenerateCallback( |
| 55 | + Samples: pcfloat; N: cint32; |
| 56 | + Arg: Pointer): cint; cdecl; |
| 57 | +begin |
| 58 | + EnterCriticalSection(CriticalSection); |
| 59 | + try |
| 60 | + if Resampler <> nil then |
| 61 | + Buffer.Push(Resampler.Resample(Samples, N, False)) |
| 62 | + else |
| 63 | + Buffer.Push(Samples, N); |
| 64 | + finally |
| 65 | + LeaveCriticalSection(CriticalSection); |
| 66 | + end; |
| 67 | + |
| 68 | + { 1 means to continue generating; 0 means to stop generating. } |
| 69 | + Result := 1; |
| 70 | +end; |
| 71 | + |
| 72 | +function PlayCallback( |
| 73 | + input: Pointer; output: Pointer; |
| 74 | + frameCount: culong; |
| 75 | + timeInfo: PPaStreamCallbackTimeInfo; |
| 76 | + statusFlags: TPaStreamCallbackFlags; |
| 77 | + userData: Pointer ): cint; cdecl; |
| 78 | +var |
| 79 | + Samples: TSherpaOnnxSamplesArray; |
| 80 | + I: Integer; |
| 81 | +begin |
| 82 | + EnterCriticalSection(CriticalSection); |
| 83 | + try |
| 84 | + if Buffer.Size >= frameCount then |
| 85 | + begin |
| 86 | + Samples := Buffer.Get(Buffer.Head, FrameCount); |
| 87 | + Buffer.Pop(FrameCount); |
| 88 | + end |
| 89 | + else if Buffer.Size > 0 then |
| 90 | + begin |
| 91 | + Samples := Buffer.Get(Buffer.Head, Buffer.Size); |
| 92 | + Buffer.Pop(Buffer.Size); |
| 93 | + SetLength(Samples, frameCount); |
| 94 | + end |
| 95 | + else |
| 96 | + SetLength(Samples, frameCount); |
| 97 | + |
| 98 | + for I := 0 to frameCount - 1 do |
| 99 | + pcfloat(output)[I] := Samples[I]; |
| 100 | + |
| 101 | + if (Buffer.Size > 0) or (not FinishedGeneration) then |
| 102 | + Result := paContinue |
| 103 | + else |
| 104 | + begin |
| 105 | + Result := paComplete; |
| 106 | + FinishedPlaying := True; |
| 107 | + end; |
| 108 | + finally |
| 109 | + LeaveCriticalSection(CriticalSection); |
| 110 | + end; |
| 111 | +end; |
| 112 | + |
| 113 | +function GetOfflineTts: TSherpaOnnxOfflineTts; |
| 114 | +var |
| 115 | + Config: TSherpaOnnxOfflineTtsConfig; |
| 116 | +begin |
| 117 | + Config.Model.Kokoro.Model := './kokoro-en-v0_19/model.onnx'; |
| 118 | + Config.Model.Kokoro.Voices := './kokoro-en-v0_19/voices.bin'; |
| 119 | + Config.Model.Kokoro.Tokens := './kokoro-en-v0_19/tokens.txt'; |
| 120 | + Config.Model.Kokoro.DataDir := './kokoro-en-v0_19/espeak-ng-data'; |
| 121 | + Config.Model.NumThreads := 2; |
| 122 | + Config.Model.Debug := False; |
| 123 | + Config.MaxNumSentences := 1; |
| 124 | + |
| 125 | + Result := TSherpaOnnxOfflineTts.Create(Config); |
| 126 | +end; |
| 127 | + |
| 128 | +begin |
| 129 | + Tts := GetOfflineTts; |
| 130 | + if Tts.GetSampleRate <> DeviceSampleRate then |
| 131 | + Resampler := TSherpaOnnxLinearResampler.Create(Tts.GetSampleRate, DeviceSampleRate); |
| 132 | + |
| 133 | + Version := String(Pa_GetVersionText); |
| 134 | + WriteLn('Version is ', Version); |
| 135 | + Status := Pa_Initialize; |
| 136 | + if Status <> paNoError then |
| 137 | + begin |
| 138 | + WriteLn('Failed to initialize portaudio, ', Pa_GetErrorText(Status)); |
| 139 | + Exit; |
| 140 | + end; |
| 141 | + |
| 142 | + NumDevices := Pa_GetDeviceCount; |
| 143 | + WriteLn('Num devices: ', NumDevices); |
| 144 | + |
| 145 | + DeviceIndex := Pa_GetDefaultOutputDevice; |
| 146 | + |
| 147 | + if DeviceIndex = paNoDevice then |
| 148 | + begin |
| 149 | + WriteLn('No default output device found'); |
| 150 | + Pa_Terminate; |
| 151 | + Exit; |
| 152 | + end; |
| 153 | + |
| 154 | + EnvStr := GetEnv('SHERPA_ONNX_MIC_DEVICE'); |
| 155 | + if EnvStr <> '' then |
| 156 | + begin |
| 157 | + DeviceIndex := StrToIntDef(EnvStr, DeviceIndex); |
| 158 | + WriteLn('Use device index from environment variable SHERPA_ONNX_MIC_DEVICE: ', EnvStr); |
| 159 | + end; |
| 160 | + |
| 161 | + for I := 0 to (NumDevices - 1) do |
| 162 | + begin |
| 163 | + DeviceInfo := Pa_GetDeviceInfo(I); |
| 164 | + if I = DeviceIndex then |
| 165 | + { WriteLn(Format(' * %d %s', [I, DeviceInfo^.Name])) } |
| 166 | + WriteLn(Format(' * %d %s', [I, AnsiString(DeviceInfo^.Name)])) |
| 167 | + else |
| 168 | + WriteLn(Format(' %d %s', [I, AnsiString(DeviceInfo^.Name)])); |
| 169 | + end; |
| 170 | + |
| 171 | + WriteLn('Use device ', DeviceIndex); |
| 172 | + WriteLn(' Name ', Pa_GetDeviceInfo(DeviceIndex)^.Name); |
| 173 | + WriteLn(' Max output channels ', Pa_GetDeviceInfo(DeviceIndex)^.MaxOutputChannels); |
| 174 | + |
| 175 | + Initialize(Param); |
| 176 | + Param.Device := DeviceIndex; |
| 177 | + Param.ChannelCount := 1; |
| 178 | + Param.SampleFormat := paFloat32; |
| 179 | + param.SuggestedLatency := Pa_GetDeviceInfo(DeviceIndex)^.DefaultHighOutputLatency; |
| 180 | + param.HostApiSpecificStreamInfo := nil; |
| 181 | + |
| 182 | + Buffer := TSherpaOnnxCircularBuffer.Create(30 * DeviceSampleRate); |
| 183 | + |
| 184 | + |
| 185 | + { Note(fangjun): PortAudio invokes PlayCallback in a separate thread. } |
| 186 | + Status := Pa_OpenStream(stream, nil, @Param, DeviceSampleRate, paFramesPerBufferUnspecified, paNoFlag, |
| 187 | + PPaStreamCallback(@PlayCallback), nil); |
| 188 | + |
| 189 | + if Status <> paNoError then |
| 190 | + begin |
| 191 | + WriteLn('Failed to open stream, ', Pa_GetErrorText(Status)); |
| 192 | + Pa_Terminate; |
| 193 | + Exit; |
| 194 | + end; |
| 195 | + |
| 196 | + InitCriticalSection(CriticalSection); |
| 197 | + |
| 198 | + Status := Pa_StartStream(stream); |
| 199 | + if Status <> paNoError then |
| 200 | + begin |
| 201 | + WriteLn('Failed to start stream, ', Pa_GetErrorText(Status)); |
| 202 | + Pa_Terminate; |
| 203 | + Exit; |
| 204 | + end; |
| 205 | + |
| 206 | + WriteLn('There are ', Tts.GetNumSpeakers, ' speakers'); |
| 207 | + |
| 208 | + Text := 'Friends fell out often because life was changing so fast. The easiest thing in the world was to lose touch with someone.'; |
| 209 | + |
| 210 | + Audio := Tts.Generate(Text, SpeakerId, Speed, |
| 211 | + PSherpaOnnxGeneratedAudioCallbackWithArg(@GenerateCallback), nil); |
| 212 | + FinishedGeneration := True; |
| 213 | + SherpaOnnxWriteWave('./kokoro-en-playback-7.wav', Audio.Samples, Audio.SampleRate); |
| 214 | + WriteLn('Saved to ./kokoro-en-playback-7.wav'); |
| 215 | + |
| 216 | + while not FinishedPlaying do |
| 217 | + Pa_Sleep(100); {sleep for 0.1 second } |
| 218 | + {TODO(fangjun): Use an event to indicate the play is finished} |
| 219 | + |
| 220 | + DoneCriticalSection(CriticalSection); |
| 221 | + |
| 222 | + FreeAndNil(Tts); |
| 223 | + FreeAndNil(Resampler); |
| 224 | + |
| 225 | + Status := Pa_CloseStream(stream); |
| 226 | + if Status <> paNoError then |
| 227 | + begin |
| 228 | + WriteLn('Failed to close stream, ', Pa_GetErrorText(Status)); |
| 229 | + Exit; |
| 230 | + end; |
| 231 | + |
| 232 | + Status := Pa_Terminate; |
| 233 | + if Status <> paNoError then |
| 234 | + begin |
| 235 | + WriteLn('Failed to deinitialize portaudio, ', Pa_GetErrorText(Status)); |
| 236 | + Exit; |
| 237 | + end; |
| 238 | +end. |
| 239 | + |
0 commit comments