-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetworkAudioSource.cs
More file actions
668 lines (565 loc) · 20.5 KB
/
NetworkAudioSource.cs
File metadata and controls
668 lines (565 loc) · 20.5 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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Networking;
/// <summary>
/// The Network AudioSource allows for easy and fast synchronisation of AudioSources across the network using Unity‘s NetworkMessages. It synchronises from and to both clients and servers.
/// Created by https://twitter.com/Chykary
/// </summary>
public class NetworkAudioSource : NetworkBehaviour
{
public AudioSource NetworkedAudioSource;
/// <summary>
/// Set this to a value you are not using anywhere else. It should be higher than 47.
/// </summary>
private static readonly short NetworkAudioSourceMessageIdentifier = 50;
private static Dictionary<uint, NetworkAudioSource> NetworkedAudioSources;
private static Dictionary<int, AudioClip> IdToAudioClip;
private static Dictionary<AudioClip, int> AudioClipToId;
private uint myIdentifier;
private Coroutine loopCoroutine;
private List<Tuple<NetworkAudioSource, float>> LinkedAudioSources;
private float originalVolume;
/// <summary>
/// The volume of the audio source (0.0 to 1.0).
/// </summary>
public float Volume
{
get
{
return NetworkedAudioSource.volume;
}
set
{
NetworkAudioSourceMessage message = GetNewMessage();
message.CallIdentifier = (byte)CallIdentifier.Volume;
message.Payload = BitConverter.GetBytes(value);
Send(message);
}
}
/// <summary>
/// The default AudioClip to play.
/// </summary>
public AudioClip Clip
{
get
{
return NetworkedAudioSource.clip;
}
set
{
NetworkAudioSourceMessage message = GetNewMessage();
message.CallIdentifier = (byte)CallIdentifier.Clip;
message.Payload = BitConverter.GetBytes(AudioClipToId[value]);
Send(message);
}
}
/// <summary>
/// Sets the Doppler scale for this AudioSource.
/// </summary>
public float DopplerLevel
{
get
{
return NetworkedAudioSource.dopplerLevel;
}
set
{
NetworkAudioSourceMessage message = GetNewMessage();
message.CallIdentifier = (byte)CallIdentifier.DopplerLevel;
message.Payload = BitConverter.GetBytes(value);
Send(message);
}
}
/// <summary>
/// Allows AudioSource to play even though AudioListener.pause is set to true.
/// This is useful for the menu element sounds or background music in pause menus.
/// </summary>
public bool IgnoreListenerPause
{
get
{
return NetworkedAudioSource.ignoreListenerPause;
}
set
{
NetworkAudioSourceMessage message = GetNewMessage();
message.CallIdentifier = (byte)CallIdentifier.IgnoreListenerPause;
message.Payload = BitConverter.GetBytes(value);
Send(message);
}
}
/// <summary>
/// This makes the audio source not take into account the volume of the audio listener.
/// </summary>
public bool IgnoreListenerVolume
{
get
{
return NetworkedAudioSource.ignoreListenerVolume;
}
set
{
NetworkAudioSourceMessage message = GetNewMessage();
message.CallIdentifier = (byte)CallIdentifier.IgnoreListenerVolume;
message.Payload = BitConverter.GetBytes(value);
Send(message);
}
}
/// <summary>
/// Is the clip playing right now (Read Only)?
/// </summary>
public bool IsPlaying
{
get
{
return NetworkedAudioSource.isPlaying;
}
}
/// <summary>
/// Is the audio clip looping?
/// </summary>
public bool Loop
{
get
{
return NetworkedAudioSource.loop;
}
set
{
NetworkAudioSourceMessage message = GetNewMessage();
message.CallIdentifier = (byte)CallIdentifier.Loop;
message.Payload = BitConverter.GetBytes(value);
Send(message);
}
}
/// <summary>
/// The pitch of the audio source.
/// </summary>
public float Pitch
{
get
{
return NetworkedAudioSource.pitch;
}
set
{
NetworkAudioSourceMessage message = GetNewMessage();
message.CallIdentifier = (byte)CallIdentifier.Pitch;
message.Payload = BitConverter.GetBytes(value);
Send(message);
}
}
/// <summary>
/// Playback position in seconds.
/// </summary>
public float Time
{
get
{
return NetworkedAudioSource.time;
}
set
{
NetworkAudioSourceMessage message = GetNewMessage();
message.CallIdentifier = (byte)CallIdentifier.Time;
message.Payload = BitConverter.GetBytes(value);
Send(message);
}
}
/// <summary>
/// Playback position in PCM samples.
/// </summary>
public int TimeSamples
{
get
{
return NetworkedAudioSource.timeSamples;
}
set
{
NetworkAudioSourceMessage message = GetNewMessage();
message.CallIdentifier = (byte)CallIdentifier.TimeSamples;
message.Payload = BitConverter.GetBytes(value);
Send(message);
}
}
public static void Initialise(List<AudioClip> clips)
{
NetworkedAudioSources = new Dictionary<uint, NetworkAudioSource>();
clips.Sort(delegate (AudioClip x, AudioClip y)
{
if (x.GetHashCode() > y.GetHashCode())
{
return 1;
}
else
{
return -1;
}
});
IdToAudioClip = new Dictionary<int, AudioClip>();
AudioClipToId = new Dictionary<AudioClip, int>();
foreach (AudioClip audioClip in clips)
{
Debug.Assert(!AudioClipToId.ContainsKey(audioClip), "Hash Collision! You can fix this by renaming the audioclip with name " + audioClip.name);
IdToAudioClip.Add(audioClip.name.GetHashCode(), audioClip);
AudioClipToId.Add(audioClip, audioClip.name.GetHashCode());
}
NetworkServer.RegisterHandler(NetworkAudioSourceMessageIdentifier, (msg) => OnReceiveNetworkAudioSourceMessage(msg, true));
NetworkManager.singleton.client.RegisterHandler(NetworkAudioSourceMessageIdentifier, (msg) => OnReceiveNetworkAudioSourceMessage(msg, false));
}
protected void Start()
{
if (NetworkedAudioSource == null)
{
Debug.Log("NetworkedAudioSource not assigned for GameObject " + gameObject.name);
return;
}
Debug.Assert(NetworkAudioSourceMessageIdentifier > MsgType.Highest, "NetworkAudioSourceMessageIdentifier must be higher than internal range!");
myIdentifier = GetComponent<NetworkIdentity>().netId.Value;
NetworkedAudioSources.Add(myIdentifier, this);
LinkedAudioSources = new List<Tuple<NetworkAudioSource, float>>();
LinkedAudioSources.Add(new Tuple<NetworkAudioSource, float>(this, 1f));
originalVolume = Volume;
}
/// <summary>
/// Pauses playing the clip.
/// </summary>
public void Pause()
{
NetworkAudioSourceMessage message = GetNewMessage();
message.CallIdentifier = (byte)CallIdentifier.Pause;
Send(message);
}
/// <summary>
/// Plays the clip with an optional certain delay.
/// </summary>
/// <param name="delay">Delay in number of samples, assuming a 44100Hz sample rate (meaning that Play(44100) will delay the playing by exactly 1 sec).</param>
public void Play(ulong delay = 0)
{
NetworkAudioSourceMessage message = GetNewMessage();
message.CallIdentifier = (byte)CallIdentifier.Play;
message.Payload = BitConverter.GetBytes(delay);
Send(message);
}
/// <summary>
/// Plays an AudioClip, and scales the AudioSource volume by volumeScale.
/// </summary>
/// <param name="clip">The clip being played.</param>
/// <param name="volumeScale">The scale of the volume (0-1).</param>
public void PlayOneShot(AudioClip clip, float volumeScale = 1.0F)
{
if (clip == null || !AudioClipToId.ContainsKey(clip))
{
Debug.Log("Clip not contained in NetworkAudioSource");
}
else
{
NetworkAudioSourceMessage message = GetNewMessage();
message.CallIdentifier = (byte)CallIdentifier.PlayOneShot;
int audioClipId = AudioClipToId[clip];
byte[] clipByteArray = BitConverter.GetBytes(audioClipId);
byte[] volumeScaleArray = BitConverter.GetBytes(volumeScale);
message.Payload = new byte[8];
Buffer.BlockCopy(clipByteArray, 0, message.Payload, 0, 4);
Buffer.BlockCopy(volumeScaleArray, 0, message.Payload, 4, 4);
Send(message);
}
}
/// <summary>
/// Plays the clip with a delay specified in seconds. Users are advised to use this function instead of the old Play(delay) function
/// that took a delay specified in samples relative to a reference rate of 44.1 kHz as an argument.
/// </summary>
/// <param name="delay">Delay time specified in seconds.</param>
public void PlayDelayed(float delay)
{
NetworkAudioSourceMessage message = GetNewMessage();
message.CallIdentifier = (byte)CallIdentifier.PlayDelayed;
message.Payload = BitConverter.GetBytes(delay);
Send(message);
}
/// <summary>
/// Plays the clip at a specific time on the absolute time-line that AudioSettings.dspTime reads from.
/// </summary>
/// <param name="time">Time in seconds on the absolute time-line that AudioSettings.dspTime refers to for when the sound should start playing.</param>
public void PlayScheduled(double time)
{
NetworkAudioSourceMessage message = GetNewMessage();
message.CallIdentifier = (byte)CallIdentifier.PlayScheduled;
message.Payload = BitConverter.GetBytes(time);
Send(message);
}
/// <summary>
/// Stops playing the clip.
/// </summary>
public void Stop()
{
NetworkAudioSourceMessage message = GetNewMessage();
message.CallIdentifier = (byte)CallIdentifier.Stop;
Send(message);
}
/// <summary>
/// Unpause the paused playback of this AudioSource.
/// </summary>
public void UnPause()
{
NetworkAudioSourceMessage message = GetNewMessage();
message.CallIdentifier = (byte)CallIdentifier.UnPause;
Send(message);
}
/// <summary>
/// Fades out the AudioSource given a specified time.
/// </summary>
/// <param name="fadeTime">Time to fade out clip.</param>
public void FadeOut(float fadeTime)
{
NetworkAudioSourceMessage message = GetNewMessage();
message.CallIdentifier = (byte)CallIdentifier.FadeOut;
message.Payload = BitConverter.GetBytes(fadeTime);
Send(message);
}
/// <summary>
/// Fades the AudioSource from the current volume to a specified target volume given a specified time.
/// </summary>
/// <param name="fadeTime">Target volume to fade in to.</param>
/// <param name="targetVolume">Time to fade in clip.</param>
public void FadeIn(float targetVolume, float fadeTime)
{
NetworkAudioSourceMessage message = GetNewMessage();
message.CallIdentifier = (byte)CallIdentifier.FadeIn;
byte[] arrTargetVol = BitConverter.GetBytes(targetVolume);
byte[] arrFadeTime = BitConverter.GetBytes(fadeTime);
message.Payload = new byte[8];
Buffer.BlockCopy(arrTargetVol, 0, message.Payload, 0, 4);
Buffer.BlockCopy(arrFadeTime, 0, message.Payload, 4, 4);
Send(message);
}
private IEnumerator FadeOutRoutine(float fadeTime, float startVolume)
{
while (NetworkedAudioSource.volume > 0)
{
NetworkedAudioSource.volume -= startVolume * UnityEngine.Time.deltaTime / fadeTime;
yield return null;
}
NetworkedAudioSource.Stop();
NetworkedAudioSource.volume = startVolume;
}
private IEnumerator FadeInRoutine(float targetVolume, float fadeTime, float startVolume)
{
while (NetworkedAudioSource.volume < targetVolume)
{
NetworkedAudioSource.volume += (targetVolume - startVolume) * UnityEngine.Time.deltaTime / fadeTime;
yield return null;
}
NetworkedAudioSource.volume = targetVolume;
}
public void PlayAndLoop(AudioClip clip, float volume)
{
Clip = clip;
Loop = true;
Volume = volume;
Play();
}
/// <summary>
/// Randomly and endlessly plays one of the provided clips with a random time distance specified.
/// </summary>
/// <param name="minTime">minimum time until next clip</param>
/// <param name="maxTime">maximum time until next clip</param>
/// <param name="clips">clips to choose from</param>
/// <returns></returns>
public void LoopRandomClips(float minTime, float maxTime, params AudioClip[] clips)
{
Debug.Assert(loopCoroutine == null, "Starting Coroutine, but another one is still running which can not be stopped anymore");
loopCoroutine = StartCoroutine(LoopRandomClips(clips, minTime, maxTime));
}
/// <summary>
/// Stops the playing of random and endless clips.
/// </summary>
public void StopLoopRandomClips()
{
if (loopCoroutine != null)
{
StopCoroutine(loopCoroutine);
loopCoroutine = null;
}
}
private IEnumerator LoopRandomClips(AudioClip[] clips, float minTime, float maxTime)
{
while(true)
{
PlayOneShot(clips[GlobalVars.Random.Next(0, clips.Length)]);
yield return new WaitForSeconds(GlobalVars.GetNextFloat(minTime, maxTime));
}
}
/// <summary>
/// Adds a linked audioSource that plays sounds like this one, but with a damping factor. Can only be called on the server.
/// </summary>
/// <param name="audioSource">audioSource that should be linked</param>
/// <param name="dampingFactor">damping when passing sounds. 1f = no damping, 0f = silence</param>
/// <param name="bidirectionalLink"></param>
[Server]
public void AddLinkedSource(NetworkAudioSource audioSource, float dampingFactor, bool bidirectionalLink = false)
{
if (bidirectionalLink)
{
audioSource.AddLinkedSource(this, dampingFactor, false);
}
RpcAddLinkedSource(audioSource.myIdentifier, dampingFactor);
}
[ClientRpc]
private void RpcAddLinkedSource(uint identifier, float dampingFactor)
{
Debug.Assert(identifier != 0, "NetworkAudioSource not initialised!");
Debug.Assert(LinkedAudioSources.Select(x => x.Item1).Count() == LinkedAudioSources.Select(x => x.Item1).Distinct().Count(), "AudioSource was already added!");
LinkedAudioSources.Add(new Tuple<NetworkAudioSource, float>(NetworkedAudioSources[identifier], dampingFactor));
}
private void SetVolume(float volume, bool dampened)
{
originalVolume = volume;
NetworkedAudioSource.volume = volume;
}
private NetworkAudioSourceMessage GetNewMessage()
{
NetworkAudioSourceMessage message = new NetworkAudioSourceMessage();
message.NetworkAudioSourceIdentifier = myIdentifier;
return message;
}
private void Send(NetworkAudioSourceMessage message)
{
if (isServer)
{
NetworkServer.SendToAll(NetworkAudioSourceMessageIdentifier, message);
}
else
{
NetworkManager.singleton.client.Send(NetworkAudioSourceMessageIdentifier, message);
}
}
private static void OnReceiveNetworkAudioSourceMessage(NetworkMessage message, bool isServer)
{
NetworkAudioSourceMessage networkAudioSourceMessage = message.ReadMessage<NetworkAudioSourceMessage>();
if (isServer && message.conn != NetworkManager.singleton.client.connection)
{
NetworkServer.SendToAll(NetworkAudioSourceMessageIdentifier, networkAudioSourceMessage);
}
else
{
if(!NetworkedAudioSources.ContainsKey(networkAudioSourceMessage.NetworkAudioSourceIdentifier))
{
Debug.Log($"{networkAudioSourceMessage.NetworkAudioSourceIdentifier} not found, maybe game has not finished initialising.");
return;
}
NetworkAudioSource targetAudioSource = NetworkedAudioSources[networkAudioSourceMessage.NetworkAudioSourceIdentifier];
foreach (Tuple<NetworkAudioSource, float> audioSourceVolumePair in targetAudioSource.LinkedAudioSources)
{
NetworkAudioSource audioSource = audioSourceVolumePair.Item1;
float dampingFactor = audioSourceVolumePair.Item2;
switch (networkAudioSourceMessage.CallIdentifier)
{
case (byte)CallIdentifier.Pause:
audioSource.NetworkedAudioSource.Pause();
break;
case (byte)CallIdentifier.Stop:
audioSource.NetworkedAudioSource.Stop();
break;
case (byte)CallIdentifier.UnPause:
audioSource.NetworkedAudioSource.UnPause();
break;
case (byte)CallIdentifier.Play:
ulong playDelay = BitConverter.ToUInt64(networkAudioSourceMessage.Payload, 0);
audioSource.SetVolume(audioSource.originalVolume * dampingFactor, true);
audioSource.NetworkedAudioSource.Play(playDelay);
break;
case (byte)CallIdentifier.PlayDelayed:
float playDelayedDelay = BitConverter.ToSingle(networkAudioSourceMessage.Payload, 0);
audioSource.NetworkedAudioSource.PlayDelayed(playDelayedDelay);
break;
case (byte)CallIdentifier.PlayScheduled:
double playScheduledTime = BitConverter.ToDouble(networkAudioSourceMessage.Payload, 0);
audioSource.NetworkedAudioSource.PlayScheduled(playScheduledTime);
break;
case (byte)CallIdentifier.PlayOneShot:
int clipUid = BitConverter.ToInt32(networkAudioSourceMessage.Payload, 0);
float volumeScale = BitConverter.ToSingle(networkAudioSourceMessage.Payload, 4) * dampingFactor;
if (!IdToAudioClip.ContainsKey(clipUid))
{
Debug.Log("Clip not contained in NetworkAudioSource");
}
else
{
AudioClip clip = IdToAudioClip[clipUid];
audioSource.NetworkedAudioSource.PlayOneShot(clip, volumeScale);
}
break;
case (byte)CallIdentifier.Volume:
uint volume = BitConverter.ToUInt32(networkAudioSourceMessage.Payload, 0);
audioSource.SetVolume(volume, false);
break;
case (byte)CallIdentifier.FadeOut:
float fadeTime = BitConverter.ToSingle(networkAudioSourceMessage.Payload, 0);
audioSource.StartCoroutine(audioSource.FadeOutRoutine(fadeTime, audioSource.originalVolume * dampingFactor));
break;
case (byte)CallIdentifier.FadeIn:
float targetVol = BitConverter.ToSingle(networkAudioSourceMessage.Payload, 0);
float fadeInTime = BitConverter.ToSingle(networkAudioSourceMessage.Payload, 4);
audioSource.StartCoroutine(audioSource.FadeInRoutine(targetVol, fadeInTime, audioSource.originalVolume * dampingFactor));
break;
case (byte)CallIdentifier.Clip:
int clipId = BitConverter.ToInt32(networkAudioSourceMessage.Payload, 0);
if (!IdToAudioClip.ContainsKey(clipId))
{
Debug.Log("Clip not contained in NetworkAudioSource");
}
else
{
AudioClip clip = IdToAudioClip[clipId];
audioSource.NetworkedAudioSource.clip = clip;
}
break;
case (byte)CallIdentifier.DopplerLevel:
float dopplerLevel = BitConverter.ToSingle(networkAudioSourceMessage.Payload, 0);
audioSource.NetworkedAudioSource.dopplerLevel = dopplerLevel;
break;
case (byte)CallIdentifier.IgnoreListenerPause:
bool ignoreListenerPause = BitConverter.ToBoolean(networkAudioSourceMessage.Payload, 0);
audioSource.NetworkedAudioSource.ignoreListenerPause = ignoreListenerPause;
break;
case (byte)CallIdentifier.IgnoreListenerVolume:
bool ignoreListenerVolume = BitConverter.ToBoolean(networkAudioSourceMessage.Payload, 0);
audioSource.NetworkedAudioSource.ignoreListenerVolume = ignoreListenerVolume;
break;
case (byte)CallIdentifier.Loop:
bool loop = BitConverter.ToBoolean(networkAudioSourceMessage.Payload, 0);
audioSource.NetworkedAudioSource.loop = loop;
break;
case (byte)CallIdentifier.Pitch:
float pitch = BitConverter.ToSingle(networkAudioSourceMessage.Payload, 0);
audioSource.NetworkedAudioSource.pitch = pitch;
break;
case (byte)CallIdentifier.Time:
float time = BitConverter.ToSingle(networkAudioSourceMessage.Payload, 0);
audioSource.NetworkedAudioSource.time = time;
break;
case (byte)CallIdentifier.TimeSamples:
int timeSamples = BitConverter.ToInt32(networkAudioSourceMessage.Payload, 0);
audioSource.NetworkedAudioSource.timeSamples = timeSamples;
break;
}
}
}
}
private class NetworkAudioSourceMessage : MessageBase
{
public uint NetworkAudioSourceIdentifier;
public byte CallIdentifier;
public byte[] Payload;
}
private enum CallIdentifier : byte
{
Pause, Stop, UnPause, Play, PlayDelayed, PlayScheduled, PlayOneShot, Volume, FadeOut, FadeIn, Clip, DopplerLevel, IgnoreListenerPause, IgnoreListenerVolume,
Loop, Pitch, Time, TimeSamples
}
}