MaximilianPs

LipSync

May 28th, 2024 (edited)
851
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.23 KB | Source Code | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEditor;
  4. using UnityEngine;
  5. using UnityEngine.UIElements;
  6.  
  7. namespace BrokenWings
  8. {
  9.     [RequireComponent(typeof(AudioSource))]
  10.     public class LipSync : MonoBehaviour
  11.     {
  12.         private AudioSource audioSource;
  13.         private float[] clipSampleData;
  14.         private const int sampleDataLength = 1024;
  15.         private float clipLoudness = 0.0f;
  16.  
  17.         [SerializeField] private Transform lipsObject;
  18.         [SerializeField] private AudioClip[] sentences;
  19.         [SerializeField][Range(0.01f, 5.0f)] private float sensitivity = 1.0f;
  20.         private int sentenceTracker = 0;
  21.  
  22.         [Tooltip("This is used to activate the speech, once activated the speech will start and the system will deactivate it, so you can activate it again for the next sentence.")]
  23.         [SerializeField] GameObject activator;
  24.  
  25.         [SerializeField] GameObject brows;
  26.         Animator browsAnim;
  27.         [Tooltip("Eyes Game Object, to be set by hand, Note that the eyes are scaled on Y axis while the mouth on Z!")]
  28.         [SerializeField] GameObject eyes;
  29.         [SerializeField] float eyeOpene = 1f;
  30.         [SerializeField] float eyeClose = 0.01f;
  31.         [Tooltip("Random interval for the next blink in second")]
  32.         [Range(2f, 20f)]
  33.         [SerializeField] float blinkInterval;
  34.         [SerializeField] private float blinkDuration = 0.1f;
  35.         private float blinkTimer = 0f;
  36.         private bool isBlinking = false;
  37.  
  38.         public enum EmotionState
  39.         {
  40.             Idle = 0,
  41.             RiseBrow = 1,
  42.             Suprise = 2,
  43.             Fear = 3,
  44.             Anger = 4,
  45.             Happy = 5   // This should Rise the bow and squeeze the eyes at 60%
  46.         }
  47.  
  48.         public EmotionState currentEmotion = EmotionState.Idle;
  49.         public EmotionState CurrentEmotion
  50.         {
  51.             get { return currentEmotion; }
  52.             set
  53.             {
  54.                 currentEmotion = value;
  55.                 browsAnim.SetInteger("EmotionalState", (int)currentEmotion);
  56.             }
  57.         }
  58.  
  59.         private bool _play = false;
  60.         public bool Play
  61.         {
  62.             get { return _play; }
  63.             set
  64.             {
  65.                 _play = value;
  66.             }
  67.         }
  68.  
  69.         private enum ScalingAxis
  70.         {
  71.             X,
  72.             Y,
  73.             Z
  74.         }
  75.         [Tooltip("The axis that need to be scaled")]
  76.         [SerializeField] private ScalingAxis selectedAxis = ScalingAxis.Z;
  77.         // Sets the value to maximize and minimize the Y scale for the lips
  78.         [SerializeField] private float minScale = 0.13f;
  79.         [SerializeField] private float maxScale = 1f;
  80.         private float maxLoudness = 0f;
  81.        
  82.  
  83.         private void Start()
  84.         {
  85.             audioSource = GetComponent<AudioSource>();
  86.             clipSampleData = new float[sampleDataLength];
  87.             sentenceTracker = 0;
  88.             audioSource.Stop();
  89.  
  90.             // Brows
  91.             if (brows == null)
  92.                 Debug.LogError("!!! NO BROWS !!! \n " + gameObject.name + "Didn't have any brows assigned!");
  93.  
  94.             browsAnim = brows.GetComponent<Animator>();
  95.  
  96.             // Eyes
  97.             if (eyes == null)
  98.                 Debug.LogError("!!! NO EYES !!! \n " + gameObject.name + "Didn't have any eyes assigned!");
  99.  
  100.         }
  101.  
  102.         private void Update()
  103.         {
  104.             if(activator.activeSelf)
  105.             {
  106.                 activator.SetActive(false);
  107.                 Play = true;
  108.             }
  109.  
  110.             if(_play)
  111.             {
  112.                 if(sentenceTracker >= sentences.Length) sentenceTracker = 0;
  113.                 audioSource.clip = sentences[sentenceTracker];
  114.                 audioSource.Play();
  115.  
  116.                 _play = false;
  117.                 sentenceTracker++;
  118.             }
  119.  
  120.             if(audioSource.isPlaying)
  121.                 MoveLips();
  122.             else
  123.             {
  124.                 IsBlinking();
  125.             }
  126.         }
  127.  
  128.         private void MoveLips()
  129.         {
  130.             if (audioSource.isPlaying)
  131.             {
  132.                 audioSource.clip.GetData(clipSampleData, audioSource.timeSamples);
  133.  
  134.                 if (audioSource.timeSamples > 0)
  135.                 {
  136.                     float sumLoudness = 0f;
  137.                     foreach (var Sample in clipSampleData)
  138.                     {
  139.                         sumLoudness += Mathf.Abs(Sample);
  140.                     }
  141.  
  142.                     // Get the average loudness
  143.                     clipLoudness = sumLoudness / clipSampleData.Length;
  144.  
  145.                     // Aggiorna il valore massimo di loudness se necessario
  146.                     if (clipLoudness > maxLoudness)
  147.                     {
  148.                         maxLoudness = clipLoudness;
  149.                     }
  150.  
  151.                     // Normalize the loudness to the maximum observed value
  152.                     clipLoudness /= maxLoudness;
  153.  
  154.                     // Map normalized loudness within the Y scale
  155.                     float scaleZValue = Mathf.Lerp(minScale, maxScale, clipLoudness);
  156.  
  157.                     // Debug.Log(clipLoudness);
  158.  
  159.                     // Close the mouth when clipLoudness is low.
  160.                     if (clipLoudness <= 0) scaleZValue = minScale;
  161.  
  162.                     // Map normalized loudness within the selected scaling axis
  163.                     float scaleValue = 0f;
  164.  
  165.                     // Calculate the scaled sensitivity based on the maximum observed loudness
  166.                     float scaledSensitivity = sensitivity * maxLoudness;
  167.  
  168.                     switch (selectedAxis)
  169.                     {
  170.                         case ScalingAxis.X:
  171.                             scaleValue = Mathf.Lerp(minScale, maxScale, clipLoudness * scaledSensitivity);
  172.                             lipsObject.localScale = new Vector3(scaleValue, lipsObject.localScale.y, lipsObject.localScale.z);
  173.                             break;
  174.                         case ScalingAxis.Y:
  175.                             scaleValue = Mathf.Lerp(minScale, maxScale, clipLoudness);
  176.                             lipsObject.localScale = new Vector3(lipsObject.localScale.x, scaleValue, lipsObject.localScale.z);
  177.                             break;
  178.                         case ScalingAxis.Z:
  179.                             scaleValue = Mathf.Lerp(minScale, maxScale, clipLoudness);
  180.                             lipsObject.localScale = new Vector3(lipsObject.localScale.x, lipsObject.localScale.y, scaleValue);
  181.                             break;
  182.                     }
  183.  
  184.                     lipsObject.localScale = new Vector3(lipsObject.localScale.x, lipsObject.localScale.y, scaleZValue);
  185.                 }
  186.             }
  187.         }
  188.  
  189.         public void BlinkEyes(float ec, float eo)
  190.         {
  191.             float randomScale = Random.Range(ec, eo);
  192.             Vector3 newScale = eyes.transform.localScale;
  193.             newScale.y = randomScale;
  194.             eyes.transform.localScale = newScale;
  195.         }
  196.  
  197.         private void ResetEyeScale()
  198.         {
  199.             Vector3 newScale = eyes.transform.localScale;
  200.             newScale.y = 1f;
  201.             eyes.transform.localScale = newScale;
  202.         }
  203.  
  204.         private void IsBlinking()
  205.         {
  206.             if (!isBlinking)
  207.             {
  208.                 // Generate a random time interval for the next blink
  209.                 float randomInterval = Random.Range(1f, blinkInterval);
  210.                 blinkTimer += Time.deltaTime;
  211.  
  212.                 if (blinkTimer >= randomInterval)
  213.                 {
  214.                     // Start blinking
  215.                     isBlinking = true;
  216.                     blinkTimer = 0f;
  217.                     BlinkEyes(eyeClose, eyeOpene);
  218.                 }
  219.             }
  220.             else
  221.             {
  222.                 // Continue blinking for the blink duration
  223.                 blinkTimer += Time.deltaTime;
  224.  
  225.                 if (blinkTimer >= blinkDuration)
  226.                 {
  227.                     // Stop blinking
  228.                     isBlinking = false;
  229.                     blinkTimer = 0f;
  230.                     ResetEyeScale();
  231.                 }
  232.             }
  233.         }
  234.  
  235.         public void SetSentence(int sentence)
  236.         {
  237.             sentenceTracker = sentence;
  238.         }    
  239.     }
  240.  
  241. }
  242.  
Advertisement
Add Comment
Please, Sign In to add comment