1# Copyright 2024 Google LLC 2# 3# Licensed under the Apache License, Version 2.0 (the 'License'); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# https://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an 'AS IS' BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15SOX_PATH = 'sox' 16 17 18def _raw_format_args(channels, bits, rate): 19 """Gets raw format args used in sox. 20 21 Args: 22 channels: Number of channels. 23 bits: Bit length for a sample. 24 rate: Sampling rate. 25 26 Returns: 27 A list of args. 28 """ 29 args = ['-t', 'raw', '-e', 'signed'] 30 args += _format_args(channels, bits, rate) 31 return args 32 33 34def _format_args(channels, bits, rate): 35 """Gets format args used in sox. 36 37 Args: 38 channels: Number of channels. 39 bits: Bit length for a sample. 40 rate: Sampling rate. 41 42 Returns: 43 A list of args. 44 """ 45 return ['-c', str(channels), '-b', str(bits), '-r', str(rate)] 46 47 48def generate_sine_tone_cmd(filename, 49 channels=2, 50 bits=16, 51 rate=48000, 52 duration=None, 53 frequencies=440, 54 gain=None, 55 vol=None, 56 raw=True): 57 """Gets a command to generate sine tones at specified frequencies. 58 59 Args: 60 filename: The name of the file to store the sine wave in. 61 channels: The number of channels. 62 bits: The number of bits of each sample. 63 rate: The sampling rate. 64 duration: The length of the generated sine tone (in seconds). 65 frequencies: The frequencies of the sine wave. Pass a number or a list to specify frequency for each channel. 66 gain: The gain (in db). 67 vol: A float for volume scale used in sox command. 68 E.g. 1.0 is the same. 0.5 to scale volume by 69 half. -1.0 to invert the data. 70 raw: True to use raw data format. False to use what filename specifies. 71 """ 72 args = [SOX_PATH, '-n'] 73 if raw: 74 args += _raw_format_args(channels, bits, rate) 75 else: 76 args += _format_args(channels, bits, rate) 77 args.append(filename) 78 args.append('synth') 79 if duration is not None: 80 args.append(str(duration)) 81 if not isinstance(frequencies, list): 82 frequencies = [frequencies] 83 for freq in frequencies: 84 args += ['sine', str(freq)] 85 if gain is not None: 86 args += ['gain', str(gain)] 87 if vol is not None: 88 args += ['vol', str(vol)] 89 return args 90