silence: generating a .wav file of silence under Unix


What is this about?

Recently I needed to insert a certain amount of silence at the beginning of a song, in order to make it sync after the credits of a film. I found this surprisingly inconvenient to do with editors such as snd or xwave, and was unable to locate a way to "fake it" in mplex or otherwise work around the problem.

Fortunately, the sox utilities make it very easy to convert various raw formats to .wav. The following short Perl script generates a .wav file of the desired length, in seconds. Coupled with my catwav script, this allowed me to build the final .wav file I wanted to present to the MP3 encoder.

Directions for Use

The correct syntax is:

silence seconds newfilename.wav
A decimal point is permitted.

Bugs

The arguments are not checked for reasonableness.

The script takes advantage of the convenient text-based .dat format supported by the sox utilities. This is very lazy. It would be almost as easy to output a "raw" audio file of 8-bit bytes and feed that to sox, and it would run a lot faster and use less disk space.

The silence Perl script source code

Directions: copy and paste this script into a file called silence in /usr/local/bin. Make it executable with the command chmod 755 /usr/local/bin/silence. Of course, you don't have to put it in a shared directory if you don't want to; it's just a simple Perl script.

See also catwav.

License Terms

Public domain. Do as you see fit with this script.
#!/usr/bin/perl

$seconds = $ARGV[0];
$file = $ARGV[1];
if ((!$seconds) || ($file eq "")) {
        die "Usage: silence seconds newfilename.wav\n";
}

open(OUT, ">/tmp/$$.dat");
print OUT "; SampleRate 8000\n";
$samples = $seconds * 8000;
for ($i = 0; ($i < $samples); $i++) {
        print OUT $i / 8000, "\t0\n";
}
close(OUT);

system("sox /tmp/$$.dat -b -r 44100 -c 2 -s -w $file");
unlink("/tmp/$$.dat");