Files
godot-demo-projects/audio/spectrum/show_spectrum.gd
Hugo Locurcio 6df3667072 Improve Audio Spectrum demo
- Draw fake reflections for spectrum bars.
- Increase the bars' height to better make use of the window space.
- Use Compatibility rendering method for greater performance
  and compatibility.
- Update screenshot and icon.
- Remove a stray `.import` file.
2023-02-26 18:25:37 +01:00

57 lines
1.4 KiB
GDScript

extends Node2D
const VU_COUNT = 16
const FREQ_MAX = 11050.0
const WIDTH = 800
const HEIGHT = 250
const MIN_DB = 60
var spectrum
func _draw():
@warning_ignore("integer_division")
var w = WIDTH / VU_COUNT
var prev_hz = 0
for i in range(1, VU_COUNT + 1):
var hz = i * FREQ_MAX / VU_COUNT
var magnitude = spectrum.get_magnitude_for_frequency_range(prev_hz, hz).length()
var energy = clampf((MIN_DB + linear_to_db(magnitude)) / MIN_DB, 0, 1)
var height = energy * HEIGHT
draw_rect(
Rect2(w * i, HEIGHT - height, w - 2, height),
Color.from_hsv(float(VU_COUNT * 0.6 + i * 0.5) / VU_COUNT, 0.5, 0.6)
)
draw_line(
Vector2(w * i, HEIGHT - height),
Vector2(w * i + w - 2, HEIGHT - height),
Color.from_hsv(float(VU_COUNT * 0.6 + i * 0.5) / VU_COUNT, 0.5, 1.0),
2.0,
true
)
# Draw a reflection of the bars with lower opacity.
draw_rect(
Rect2(w * i, HEIGHT, w - 2, height),
Color.from_hsv(float(VU_COUNT * 0.6 + i * 0.5) / VU_COUNT, 0.5, 0.6) * Color(1, 1, 1, 0.125)
)
draw_line(
Vector2(w * i, HEIGHT + height),
Vector2(w * i + w - 2, HEIGHT + height),
Color.from_hsv(float(VU_COUNT * 0.6 + i * 0.5) / VU_COUNT, 0.5, 1.0) * Color(1, 1, 1, 0.125),
2.0,
true
)
prev_hz = hz
func _process(_delta):
# Sound plays back continuously, so the graph needs to be updated every frame.
queue_redraw()
func _ready():
spectrum = AudioServer.get_bus_effect_instance(0, 0)