'AudioSource.GetOutputData returns 0 every time

I am trying to log the volume of audio that is playing.

Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class visualiser : MonoBehaviour
{
    public float[] samples = new float[256];
    float a;
    AudioSource source;
    // Start is called before the first frame update
    void Start()
    {
        source = GetComponent<AudioSource>();
        source.Play();
    }

    // Update is called once per frame
    void Update()
    {
        source.GetOutputData(samples, 0);
        foreach(float s in samples)
        {
            a += Mathf.Abs(s);
        }
        Debug.Log(a/256f);
    }

No matter what I do it always logs "0". I have tried every solution that I have found. Nothing worked. If anyone knows what is the problem please answer.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source