-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsubtitleListener.cs
106 lines (97 loc) · 2.81 KB
/
subtitleListener.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
using UnityEngine;
using UnityEngine.UI;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System;
using System.Text;
using System.Collections;
public class subtitleListener : MonoBehaviour
{
private Text subtitle;
// Thread
Thread receiveThread;
TcpClient client;
TcpListener listener;
int port = 5067;
string receivedText = "", prevText = "";
int sameCount = 0;
// Start is called before the first frame update
void Start()
{
subtitle = GetComponent<Text>();
InitTCP();
}
// Update is called once per frame
void Update()
{
if (prevText.Equals(receivedText))
{
sameCount++;
if (sameCount == 60) // if no speech for two seconds, erase the subtitle.
{
receivedText = "";
}
} else
{
sameCount = 0;
}
subtitle.text = receivedText;
prevText = receivedText;
}
private void InitTCP()
{
receiveThread = new Thread(new ThreadStart(ReceiveData));
receiveThread.IsBackground = true;
receiveThread.Start();
}
private void ReceiveData()
{
try
{
listener = new TcpListener(IPAddress.Parse("127.0.0.1"), port);
listener.Start();
Byte[] bytes = new Byte[1024];
while (true)
{
using (client = listener.AcceptTcpClient())
{
using (NetworkStream stream = client.GetStream())
{
int length;
while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
{
var incommingData = new byte[length];
Array.Copy(bytes, 0, incommingData, 0, length);
receivedText = Encoding.UTF8.GetString(incommingData);
if (receivedText.Length > 32) // if the text is longer than 32 words,
// cut the subtitle and print in new
// line.
{
int startIndex = 32 * (receivedText.Length / 32);
receivedText = receivedText.Substring(startIndex);
}
}
}
}
}
}
catch (Exception e)
{
print(e.ToString());
}
}
void OnApplicationQuit()
{
try
{
receiveThread.Abort();
client.Close();
listener.Stop();
}
catch (Exception e)
{
Debug.Log(e.Message);
}
}
}