An Audio Function Generator...

Login or Register for Dates, Times and to Reply

 
Thread Tools Search this Thread
Operating Systems OS X (Apple) An Audio Function Generator...
# 1  
An Audio Function Generator...

Ok guys, gals and geeks...

As from today I am starting to learn awk in earnest doing something totally different.

I am going to create a pseudo-Audio_Function Generator centred around OSX 10.11.x minimum. The code below is a tester to see what the possibilities are.

All waveforms will be 6+ bit depth using ASCII characters decimal 32 - space to decimal 126 - tilde.

It requires SOX and I am not going to use any other source.

The code below is my starting point. All criticisms welcome...

I am now getting my head around making it fully programmable using awk.
The shell is SOOOO easy but this is new to me and I want to learn...

If you try it out the simple sinewave.raw file generated will only go from 500Hz to 6KHz...

Have fun... ;o)
Code:
#!/bin/sh
# FG.sh
awk '
# Clear the terminal window.
function cls()
{
	printf "\x1B[2J\x1B[H";
}

# User keyboard interrupt.
function keyboard( COMMAND )
{
	printf "Press <CR> to continue or QUIT<CR>:- ";
	getline COMMAND;
	if ( COMMAND == "QUIT" ) { exit 0 };
}
 
# Adjust the sample rate for SOX WRT its frequency.
function setrate( RATE )
{
	cls();
	FREQ=500;
	BYTES=8;
	RATE=16000;
	printf "Enter frequency required:- ";
	getline FREQ;
	RATE=(BYTES*FREQ);
	if ( RATE <= 4000 ) { RATE=4000 };
	if ( RATE >= 48000 ) { RATE=48000 };
	return RATE;
}

# Main loop...
function main()
{
	RATE=setrate();
	LOOPS=2;
	for ( LOOP = 1; LOOP <= LOOPS; ++LOOP ) { system ( "~/sox-14.4.2/sox -q -b 8 -r "RATE" -e unsigned-integer /tmp/sinewave8.raw -d trim 0 00:01 > /dev/null 2>&1" ) };
	keyboard( COMMAND );
}

# Now generate a simple sinewave and run the _main_ code.
BEGIN \
{
	system( ">" "/tmp/sinewave8.raw" );
	SINEWAVE8="Op}pN- -";
	for ( LOOP = 1; LOOP <= 16; ++LOOP ) { SINEWAVE8=SINEWAVE8 SINEWAVE8 };
	printf SINEWAVE8 > "/tmp/sinewave8.raw";
	cls();
	while( 1 ) { main() };
}'

# 2  
A more conventional way to terminate a UNIX program is to have it terminate when it hits EOF. In addition to being more conventional, it also allows you to feed a set of frequencies into a pipe or to read them from a file without the danger or going into an infinite read loop if the input to your script is redirected from a file that doesn't contain QUIT on an even numbered line:
Code:
function keyboard() {
	printf "Press <CR> to continue, or ctl-D or QUIT<CR> to exit:- ";
	if ( getline != 1 || $1 == "QUIT" ) { exit 0 }
}

Furthermore, note that the keyboard() function does not take any input parameters (neither in your original code where it declares a local variable in the function declaration nor in the above which uses NR, NF, $0, and $1 through $NF as local variables instead of COMMAND), so the call in main() to keyboard() should be:
Code:
	keyboard();

instead of:
Code:
	keyboard( COMMAND );

When looking for a restricted range of numbers, it would also be nice if you told your users what the range of allowable numbers is (or at least print a warning if you set RATE in setrate() because FREQ was out of range. And, there is no need to define hard-coded values for FREQ and RATE in your function before reading a value for FREQ and calculating the value for RATE based on that:
Code:
function setrate( RATE )
{
	cls();
	BYTES=8;
	printf("Enter frequency required (%d <= frequency <= %d):- ",
	    int((4000 + BYTES - 1) / BYTES), ((48000 + BYTES - 1) / BYTES))
	getline FREQ;
	RATE=(BYTES*FREQ);
	if ( RATE <= 4000 ) { RATE=4000 };
	if ( RATE >= 48000 ) { RATE=48000 };
	return RATE;
}

If I was writing this, I would probably get rid of the keyboard() function completely, and have setrate() exit if EOF is found or 0 is entered for the frequency. That way you can just feed your program a file containing the frequencies you want it to process if you'd like to feed it data non-interactively (without having to worry about putting the frequencies you want on odd lines and empty even numbered lines (except for the last even numbered line that must contain only QUIT):
Code:
function setrate(	FREQ, RATE )
{
	cls()
	BYTES = 8
	printf("Enter frequency to continue or ctl-D to exit.\n")
	printf("Valid frequency range: %d <= frequency <= %d:- ",
	    int((4000 + BYTES - 1) / BYTES), ((48000 + BYTES - 1) / BYTES))
	if(getline FREQ != 1 || (FREQ + 0) == 0) {
		print "Good bye."
		exit 0
	}
	RATE = (BYTES * FREQ)
	if(RATE <= 4000) RATE=4000
	if(RATE >= 48000) RATE=48000
	return RATE
}

Note that when I write functions in awk I use the convention that parameters immediately follow the open parenthesis in the declaration and local variables declared in the function definition are separated from parameters (if there are any) by a tab.

Note also that since BYTES is not declared as a variable in the function definition line, it is a global variable. Therefore, it would be better if it were defined once in your BEGIN clause instead of redefining its constant value every time you call the function. (The same applies to LOOPS in function main().)

And note that the syntax for assigning values to variables in awk does not require that there be no spaces surrounding the equal sign operator (although that is a requirement in the shell programming language). So, if you're going to surround all of the other awk operators with spaces, you should be consistent and do it that way in assignments as well.

But, if you are trying to learn how to write an awk program, take advantage of the inherent looping awk structure instead of trying to use the awk command language to write something that looks like a shell script or a C program. Consider something more like:
Code:
#!/bin/sh
awk '
# Now generate a simple sinewave and run the _main_ code.
BEGIN {	# Initialize variables.
	BYTES = 8
	LOOPS = 2;
	MaxRATE = 48000
	MinRATE = 4000
	SINEWAVE8 = "Op}pN- -";
	TMPFILE = "/tmp/sinewave8.raw"

	COMMANDpt1 = "~/sox-14.4.2/sox -q -b " BYTES " -e unsigned-integer -r "
	COMMANDpt2 = " " TMPFILE " -d trim 0 00:01 > /dev/null 2>&1"

	# Create waveform file.
	for(LOOP = 1; LOOP <= 16; ++LOOP) {
		SINEWAVE8 = SINEWAVE8 SINEWAVE8
	}
	printf("%s", SINEWAVE8) > TMPFILE

	# Prompt user for first input.
	prompt()
}

# Clear the terminal window.
function cls() {
	printf "\x1B[2J\x1B[H";
}

# Prompt user for input.
function prompt() {
	# Clear the screen.
	cls()

	# Issue the prompt.
	printf("Enter frequency to continue or ctl-D to exit.\n")
	printf("Valid frequency range: %d <= frequency <= %d:- ",
	    int((MinRATE + BYTES - 1) / BYTES), ((MaxRATE + BYTES - 1) / BYTES))
}

# Process a line of user supplied input.
{	# Exit if input frequency is 0 or non-numeric.
	if($1 + 0 == 0) exit
	
	# Convert input frequency to rate.
	RATE = BYTES * $1
	if(RATE <= MinRATE) {
		RATE = MinRATE
	}
	if(RATE >= MaxRATE) {
		RATE = MaxRATE
	}

	# Print the waveform.
	for(LOOP = 1; LOOP <= LOOPS; ++LOOP) {
		system(COMMANDpt1 RATE COMMANDpt2)
	}

	# Prompt for the next input frequency.
	prompt()
}

END {	# Clear screen and print exit message.
	cls()
	print "Goodbye."

	# Remove waveform file.
	exit system("rm -rf " TMPFILE)
}'

Note that I do not have sox installed on my system, so when I run this, it immediately clears the screen and prints a new prompt after system() reports that it can't find sox. If sox doesn't include a delay after producing its output, you might want to add a sleep command after the sox command in the command string you pass to system().

Last edited by Don Cragun; 04-01-2016 at 08:11 PM.. Reason: Fix typo pointed out in post #9: s/Commandpt2/COMMANDpt2/
This User Gave Thanks to Don Cragun For This Post:
# 3  
Hi Don...

(Apologies for any typos.)

Cool.

Many thanks for your comments, it will keep me occupied for a while. ;o)

As for the keyboard() this will be a COMMAND function to change many factors of the code as it evolves much like AudioScope, (I am still slowly working on AudioScope BTW).

I will steal your code once I have gotten my head around it as this is my first reall attempt at awk to create a working app' that interests me. I have only been doing it since yesterday although I have used awk for very small code snippets inside my shell scripts. Again as with UNIX shell scripting this is a steep learning curve for me...

The script size could again approach that of AudioScope who knows. At the moment my attempt is proof of concept. I need to create SINE, SQUARE, SAWTOOTH+, SAWTOOTH-, TRIANGLE, PULSE+, PULSE-, ARBTRARY, and NOISE waveforms first and test. So this will be the next upload...

One good thing is that in uncalibrated output level format no external HW needs to be built except a test lead...

However many thanks, as usual you always respond with useful info along with others on here.
# 4  
Why use shell magic cookie instead of awk one as interpreter ?

Should one use #!/bin/ksh .. awk '.. or just !#/usr/bin/awk -f or even /usr/bin/env awk ?

What should be most portable, preferred and/or standards compliant?

Regards
Peasant.
This User Gave Thanks to Peasant For This Post:
# 5  
Hi Peasant...

I had not even thought about my first line except that I don't know how to create a zero length file > somefile in awk yet.

I use the system() function to do this task at the moment...
# 6  
Try:
Code:
awk 'BEGIN{printf "" >"somefile"}'

This User Gave Thanks to Scrutinizer For This Post:
# 7  
Hi Scrutinizer...

Thanks that is what I needed...

I hadn't researched that yet as it was unimportant at this point in time... :-)
Login or Register for Dates, Times and to Reply

Previous Thread | Next Thread
Thread Tools Search this Thread
Search this Thread:
Advanced Search

Test Your Knowledge in Computers #573
Difficulty: Medium
PHP does not allow you to use arrays as both function parameters and as return types.
True or False?

7 More Discussions You Might Find Interesting

1. OS X (Apple)

A simple variable frequency sinewave audio generator.

Hi all... Well I have not been inactive but working out how to make OSX 10.14.x command line audio player have a variable sample rate. This is a back door as afplay does not have a sample rate flag unlike aplay for ALSA, in Linux flavours. This is a DEMO only but a derivative of it will... (2 Replies)
Discussion started by: wisecracker
2 Replies

2. OS X (Apple)

Variable frequency audio generator...

Hi all... I intend to do an Audio Function Generator using Awk, (already started thanks to Don), but the biggest thing I have struggled with was variable frequency. I was going to generate differing sized waveforms on the fly but that would that would mean the frequencies are dependent on any... (2 Replies)
Discussion started by: wisecracker
2 Replies

3. OS X (Apple)

A Bash Audio Sweep Generator...

This is a small program as a tester for a basic sweep generator for bandwidth testing of AudioScope.sh. This DEMO is only capable of 4KHz down to about 85Hz and back due to the low bit rate, but it is proof of concept for a much wider variant using a much higher bit rate. The file generated... (4 Replies)
Discussion started by: wisecracker
4 Replies

4. Slackware

Problems with audio recording in Audacity 2.0.5. Slackware64 14.1; Intel HD Audio.

I'm trying to record audio using Audacity 2.0.5 installed from SlackBuilds. My system is 64-bit Slackware 14.1 and a sound card is Intel HD Audio. I didn't change my sound system to OSS. (Default sound system in Slackware 14.1 is ALSA, isn't it?) First, I set Internal Microphone slider in KMix... (2 Replies)
Discussion started by: qzxcvbnm
2 Replies

5. Shell Programming and Scripting

Sequence generator

Thanks Guys This really helped (5 Replies)
Discussion started by: robert89
5 Replies

6. Shell Programming and Scripting

A Crude 1KHz Audio Sinewave Generator Demo...

A very simple crude sinewave generator. The file required is generated inside the code, is linear interpolated and requires /dev/audio to work. Ensure you have this device, if not the download oss-compat from your OS's repository... It lasts for about 8 seconds before exiting and saves a... (5 Replies)
Discussion started by: wisecracker
5 Replies

7. Programming

Python, Platform Independent, Pure Audio Sinewave Generator...

IKHz_SW_OSX.py A DEMO mono _pure_ sinewave generator using standard text mode Python 2.6.7 to at least 2.7.3. This code is EASILY modifyable to Python version 3.x.x... This DEMO kids level 1KHz generator is mainly for a MacBook Pro, (13 inch in my case), OSX 10.7.5 and above. See below...... (0 Replies)
Discussion started by: wisecracker
0 Replies

Featured Tech Videos