1 ardour { ["type"] = "Snippet", name = "Set Region Gain" }
3 function factory () return function ()
4 -- get Editor GUI Selection
5 -- http://manual.ardour.org/lua-scripting/class_reference/#ArdourUI:Selection
6 local sel = Editor:get_selection ()
8 -- allocate a buffer (float* in C)
9 -- http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:DSP:DspShm
10 local cmem = ARDOUR.DSP.DspShm (8192)
12 -- prepare undo operation
13 Session:begin_reversible_command ("Lua Region Gain")
14 local add_undo = false -- keep track if something has changed
16 -- iterate over selected regions
17 -- http://manual.ardour.org/lua-scripting/class_reference/#ArdourUI:RegionSelection
18 for r in sel.regions:regionlist ():iter () do
19 -- test if it's an audio region
20 if r:to_audioregion ():isnil () then
24 -- to read the Region data, we use the Readable interface of the Region
25 -- http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:Readable
26 local rd = r:to_readable ()
28 local n_samples = rd:readable_length ()
29 local n_channels = rd:n_channels ()
31 local peak = 0 -- the audio peak to be calculated
33 -- iterate over all channels in Audio Region
34 for c = 0, n_channels do
37 -- read at most 8K samples of channel 'c'
38 local s = rd:read (cmem:to_float (0), pos, 8192, c)
40 -- access the raw audio data
41 -- http://manual.ardour.org/lua-scripting/class_reference/#C:FloatArray
42 local d = cmem:to_float (0):array()
43 -- iterate over the audio sample data
45 if math.abs (d[i]) > peak then
46 peak = math.abs (d[i])
53 print ("Region:", r:name (), "peak:", 20 * math.log (peak) / math.log(10), "dBFS")
55 print ("Region:", r:name (), " is silent")
61 r:to_stateful ():clear_changes ()
63 r:to_audioregion (): set_scale_amplitude (1 / peak)
64 -- save changes (if any) to undo command
65 if not Session:add_stateful_diff_command (r:to_statefuldestructible ()):empty () then
73 -- all done. now commit the combined undo operation
75 -- the 'nil' command here means to use all collected diffs
76 Session:commit_reversible_command (nil)
78 Session:abort_reversible_command ()