- Home /
Triggering a certain part of an AudioClip, once.
Hello there, I'm trying to figure out how to make a script which allows me to trigger only a certain part of an audio clip. After searching around on the web I came around some piece of code which seemed useful, so I altered it a bit. What I am trying to accomplish is sampling an AudioClip and then creating a new one, which is only a part of the older Clip. Then it should be assigned to the AudioSource and played as the Player enters the trigger. And from then the bool "alreadyPlayed" turns true, making it so the audio cannot be triggered again.
The problem is that I get these errors saying, "A field initializer cannot reference the non-static field, method, or property". I don't understand what is being meant by that.
Could someone give me a few pointers on how to make this code work?
using UnityEngine; using System.Collections;
public class IvyMeeting : MonoBehaviour {
public AudioClip AudioClipStart; //This is an audio file (compressed MP3 in this example) that we will modify. This will be set using the unity editor.
private AudioClip AudioClipNew; //This is what the modified clip will be saved as, and we will then play it.
public bool alreadyPlayed = false;
public float Volume;
public float samples = new float[AudioClipStart.samples * AudioClipStart.channels]; //Build a list of all the sound data in the audio clip based on the original.
public float TimeReal = AudioClipStart.length; //The number we will use to offset the audioclip will not actually be in seconds, it will be in the segments the compression slices it into.
private int SegmentNumber = AudioClipStart.samples; //This is the actual number of segments of the audio clip.
private float TimePerSegment = TimeReal / SegmentNumber;
void Start()
{
AudioClipStart.GetData(samples, 20 / TimePerSegment); //Pull the data from the clip with an offset of 20 seconds. We devide by the time per second to actually offset by a perfect 20 seconds instead of something shorter or longer.
AudioClipNew.SetData(samples, 0); //We pulled the data from the original with an offset of 20 seconds, now we apply it to the new with no offset, making this audio clip 20 seconds ahead of the original.
audio.clip = AudioClipNew; //Set the audio source's clip to the new audioclip.
}
private void OnTriggerEnter(Collider other)
{
if (!alreadyPlayed)
if (other.CompareTag("Player"))
{
audio.PlayOneShot(AudioClipNew, Volume);
alreadyPlayed = true;
Debug.Log("Hier ontmoet Sam Ivy.");
this.gameObject.SetActive(false);
}
}
}