Johannes Mayrhofer
Johannes Mayrhofer

Reputation: 21

Unity set Script as AudioSource

Is there a way in Unity to set a Script as an AudioSource? I have a Script which produces Sound, i now want to Visualize this, but with GetComponent i only get a null value.

I have tried with GetComponent but for that i need to set the Script as the Source, and it already worked with AudioListeners but i need the AudioSource to also visualize it. I have used several online tutorials, but no one uses a Script as Source.

I can only see one solution left, which i want to avoid ,which would be writing the data from the AudioSource in a file, and generating the Visualization that way.

Edit: I have tried what DareerAhmadMufti suggested: enter image description here

Sadly it still doesn't work.

    public class AudioGaudioGenerator : MonoBehaviour
{
    private Graph graph;
    public AudioSource _audioSource;
    float[] farr = new float[4096];
    void Start()
    {
        graph = this.GetComponentInChildren<Graph>();
        _audioSource = GetComponent<AudioSource>();
    }

    // Update is called once per frame
    void Update()
    {

        GetSpectrumAudioSource();
        if (graph.showWindow0)
        {
            graph.SetValues(farr);
        }
    }

    void GetSpectrumAudioSource()
    {
        _audioSource.GetOutputData(farr, 0);
    }

This is the Script for the AudioGenerator

Upvotes: 0

Views: 636

Answers (3)

Housheng-MSFT
Housheng-MSFT

Reputation: 762

You want to use a script for audio visualization, but you only get a null value using the "GetComponent" method. You can create an empty object in the scene with position coordinates (0,0,0) and rename it Audio Visualization, and add LineRenderer and AudioSource components to it.Create a red shader and assign it to LineRenderer.

enter image description here

Create a cube, then create a green shader and assign it to the cube, drag it into a prefab cube.

write scripts:

   public class AudioVisualization : MonoBehaviour
  {
      AudioSource audio;//Sound source
      float[] samples = new float[128];//The length of the array to store the spectrum data
      LineRenderer linerenderer;//Draw line
      public GameObject cube;//cube prefab
      Transform[] cubeTransform;//Position of cube prefab
      Vector3 cubePos;//The middle position, used to compare the cube position with the spectral data of this frame
      // Use this for initialization
      void Start()
     {
          GameObject tempCube;
          audio = GetComponent<AudioSource>();//Get the sound source component
          linerenderer = GetComponent<LineRenderer>();//Get the line drawing component
          linerenderer.positionCount = samples.Length;//Set the number of segments of the line segment
          cubeTransform = new Transform[samples.Length];//Set the length of the array
          //Move the gameobject mounted by the script to the left, so that the center of the generated object is facing the camera
          transform.position = new Vector3(-samples.Length * 0.5f, transform.position.y, transform.position.z);
          //Generate the cube, pass its position information into the cubeTransform array, and set it as the child object of the gameobject mounted by the script
          for (int i = 0; i < samples.Length; i++)
         {
             tempCube=Instantiate(cube,new Vector3(transform.position.x+i,transform.position.y,transform.position.z),Quaternion.identity);
             cubeTransform[i] = tempCube.transform;
             cubeTransform[i].parent = transform;
          }
       }

       // Update is called once per frame
       void Update()
      {
         //get spectrum
         audio.GetSpectrumData(samples, 0, FFTWindow.BlackmanHarris);
         //cycle
          for (int i = 0; i < samples.Length; i++)
         {
            //Set the y value of the middle position according to the spectrum data, and set the x and z values ​​according to the position of the corresponding cubeTransform
            //Use Mathf.Clamp to limit the y of the middle position to a certain range to avoid being too large
            //The more backward the spectrum is, the smaller
             cubePos.Set(cubeTransform[i].position.x, Mathf.Clamp(samples[i] * ( 50+i * i*0.5f), 0, 100), cubeTransform[i].position.z);
            //Draw a line, in order to prevent the line from overlapping with the cube, the height is reduced by one
             linerenderer.SetPosition(i, cubePos-Vector3.up);
             //When the y value of the cube is less than the y value of the intermediate position cubePos, the position of the cube becomes the position of the cubePos
             if (cubeTransform[i].position.y < cubePos.y)
             {
               cubeTransform[i].position = cubePos;             
             }
            //When the y value of the cube is greater than the y value of the cubePos in the middle position, the position of the cube slowly falls down
             else if (cubeTransform[i].position.y > cubePos.y)
             {
                cubeTransform[i].position -= new Vector3(0, 0.5f, 0);
             }
          }
       }
    }

Hook the script on Audio Visualization and assign the prefab cube to the script. Import an audio resource and assign the audio resource to the audiosouce component. The playback effect is as follows

enter image description here

Upvotes: 1

DareerAhmadMufti
DareerAhmadMufti

Reputation: 46

Your question is quite ambiguous. you can't use your custom script as AudioSource, as it is a sealed class.

If you want to get access data of the audioClip or audioSource, add AudioSource component to same object in which your script is attached. like: enter image description here

make a public AudioSource variable in your script and assign the AudioSource component, as shown above in screenshot. In this way you will be able to access the data you want in you custom scripts via that variable.

Upvotes: 0

CorrieJanse
CorrieJanse

Reputation: 2598

You cannot use a script as an AudioSource. There is already an AudioSource script. If an object contains the AudioSource script, then you are able to access with GetComponent<AudioSource>(). But it ust already be on the object.

Upvotes: 1

Related Questions