Created
May 22, 2015 22:31
-
-
Save wilg/12456d4bf54bcbc52b99 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections.Generic; | |
using System.Collections; | |
[RequireComponent (typeof (AudioSource))] | |
public class AutoLipSyncBlendshape : MonoBehaviour | |
{ | |
public SkinnedMeshRenderer skinnedMeshRenderer; | |
public float maxWeight = 1; | |
public string blendShapeName; | |
private int blendShapeIndex = -1; | |
private float volume; | |
private float bin = 0.04f; | |
private int width = 64; | |
private float output; | |
private float[] array; | |
private AudioSource _audio; | |
private void Awake () | |
{ | |
_audio = GetComponent <AudioSource>(); | |
array = new float[width]; | |
for (int i = 0; i < skinnedMeshRenderer.sharedMesh.blendShapeCount; i++) | |
{ | |
if (skinnedMeshRenderer.sharedMesh.GetBlendShapeName(i) == blendShapeName) { | |
blendShapeIndex = i; | |
} | |
} | |
if (blendShapeIndex == -1) { | |
Debug.LogError("No blend shape named " + blendShapeName + " was found."); | |
} | |
} | |
private void FixedUpdate () | |
{ | |
if (_audio.isPlaying) | |
{ | |
_audio.GetOutputData(array, 0); | |
float num3 = 0f; | |
for (int i = 0; i < width; i++) | |
{ | |
float num4 = Mathf.Abs(array[i]); | |
num3 += num4; | |
} | |
num3 /= (float) width; | |
// Only record changes big enough | |
if (Mathf.Abs (num3 - volume) > bin) | |
volume = num3; | |
volume = Mathf.Clamp01 (volume * 2); | |
volume *= 0.3f; | |
output = Mathf.Lerp (output, volume, Time.deltaTime * Mathf.Abs (maxWeight)); | |
} | |
else | |
{ | |
output = 0f; | |
} | |
} | |
private void LateUpdate () | |
{ | |
skinnedMeshRenderer.SetBlendShapeWeight(blendShapeIndex, output * maxWeight); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment