-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathPiperVoice.cs
78 lines (68 loc) · 2.35 KB
/
PiperVoice.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
using System;
using System.IO;
using System.Threading.Tasks;
namespace Abuksigun.Piper
{
public sealed unsafe class PiperVoice : IDisposable
{
Piper piper;
PiperLib.Voice* voice;
public Piper Piper => piper;
internal PiperLib.Voice* Voice => voice;
PiperVoice(Piper piper, PiperLib.Voice* voice)
{
this.piper = piper;
this.voice = voice;
}
~PiperVoice()
{
Dispose();
}
public void Dispose()
{
if (voice != null)
{
PiperLib.destroy_Voice(voice);
voice = null;
}
}
public static Task<PiperVoice> LoadPiperVoice(Piper piper, string fullModelPath)
{
if (!File.Exists(fullModelPath))
throw new FileNotFoundException("Model file not found", fullModelPath);
if (!File.Exists(fullModelPath + ".json"))
throw new FileNotFoundException("Model descriptor not found (Make sure it has the same name as model + .json)", fullModelPath);
return Task.Run(() =>
{
var newVoice = PiperLib.create_Voice();
try
{
PiperLib.loadVoice(piper.Config, fullModelPath, fullModelPath + ".json", newVoice, null);
return Task.FromResult(new PiperVoice(piper, newVoice));
}
catch
{
PiperLib.destroy_Voice(newVoice);
throw;
}
});
}
public float[] TextToPCMAudio(string text)
{
float[] audioData = new float[0];
TextToAudioStream(text, (short* data, int length) =>
{
int writeIndex = audioData.Length;
Array.Resize(ref audioData, audioData.Length + length);
for (int i = writeIndex; i < audioData.Length; i++)
audioData[i] = data[i] / 32768f;
});
return audioData;
}
public void TextToAudioStream(string text, PiperLib.AudioCallbackDelegate audioCallback)
{
PiperLib.SynthesisResult result = new PiperLib.SynthesisResult();
PiperLib.textToAudio(piper.Config, voice, text, &result, audioCallback);
}
}
}