Partly inspired by Ryan Hipple’s recent presentation at Unity 2014, The Hack Spectrum, I’ve been working on a script that will allow me to play an AudioClip from a custom editor without any nonsense (like instantiating and managing an AudioSource in the current scene).
Using reflection I’ve found the AudioUtil class, which seems to include the PlayClip() method I’ve been looking for. Right now I’ve got something resembling the following:
However, the startTime/startSample functionality of the code does not seem to work. No matter what values I give it, PlayClip always plays the AudioClip from the very beginning.
Any suggestions? Am I misunderstanding something, or does the method just have a bug? (If that’s the case, I suppose I can’t expect any help from Unity since the class and method aren’t public…)
AudioUtilW.PlayClip (audioClip, 0, node.loop);//startSample doesn't work in this function????
AudioUtilW.SetClipSamplePosition (audioClip, sampleStart);
AudioUtilW is reflected Class from AudioUtil. So trick is you first call PlayClip and then SetClipSamplePosition
Problem with AudioUtil is that Stop and StopAll doesn’t work as expected when you Play more clips at once.
You first need to PlayClip() and then execute the SetClipSamplePosition(). Both of these methods need to be called using the Reflection as posted by @winxalex.
Read the whole thread carefully. It also covers some updates to PlayClip() code for Unity 2019 as well as how to get clip samples GetSampleCount() in order to accurately get the position you want to start the clip from.
This is how your code would look like using the AudioUtility.cs script from the thread above:
AudioUtility.PlayClip(selectedAudioClip);
//Get desired position as percentage
var desiredClipPercentagePos = desiredTime / selectedAudioClip.length;
//Get the number of samples:
var samples = AudioUtility.GetSampleCount(selectedAudioClip);
//Then, simply multiply your percentage against that:
int playFrom = Mathf.FloorToInt(samples * desiredClipPercentagePos);
AudioUtility.SetClipSamplePosition(selectedAudioClip, playFrom);