07
Thu, Nov
10 New Articles

Easily Manage WAV Files with PHP

Web Languages
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Here, we look at one of the file formats that you can manage easily with PHP.

 

Editor's note: This article is an excerpt from You Want to Do WHAT with PHP?, a new book from MC Press.

  

The second file format we'll look at is WAV, the Waveform Audio File Format. WAV is a relatively simple format for storing uncompressed audio data. It is easy to interpret, and I happen to have a WAV file on my desktop, so it makes good sense for me to use it as an example.

 

The key to working with almost any binary file structure is interpreting that structure. That is what we will do with our unpack() function call. By looking at the WAV file specifications, we are told the sizes of the fields and the fact that the WAV file format uses little-endian byte ordering. From there, we can figure out which format characters we need to use. Table 7.4 lists the pack()/unpack() format characters.

 

Code

Description

a

NUL-padded string

A

SPACE-padded string

h

Hex string, low nibble first

H

Hex string, high nibble first

c

Signed char

C

Unsigned char

s

Signed short (always 16-bit, machine byte order)

S

Unsigned short (always 16-bit, machine byte order)

n

Unsigned short (always 16-bit, big-endian byte order)

v

Unsigned short (always 16-bit, little-endian byte order)

i

Signed integer (machine-dependent size and byte order)

I

Unsigned integer (machine-dependent size and byte order)

l

Signed long (always 32-bit, machine byte order)

L

Unsigned long (always 32-bit, machine byte order)

N

Unsigned long (always 32-bit, big endian byte order)

V

Unsigned long (always 32-bit, little endian byte order)

f

Float (machine-dependent size and representation)

d

Double (machine-dependent size and representation)

x

NUL byte

X

Back up one byte

@

NUL-fill to absolute position

Table 7.4: Format constants for the pack() and unpack() functions

 

For a quick illustration of how endianness works, consider the code in Figure 7.8.

 

$int = 256;

$str = pack('n', $int);

echo "Big Endian: ";

printBytes($str);

 

$str = pack('v', $int);

echo "Little Endian: ";

printBytes($str);

 

$data = unpack('vdata', $str);

echo "\n";

var_dump($data['data']);

 

function printBytes($data)

{

      $len = strlen($data);

      for ($c = 0; $c < $len; $c++) {

            if ($c % 8 === 0) echo "\n";

            $hex = str_pad(dechex(

                 ord($data[$c])), 2  , 0, STR_PAD_LEFT);

 

            echo "0x{$hex} ";

      }

      echo "\n";

}

Figure 7.8: A test demonstrating endianness

 

We use the number 256 because it cannot be represented in a single byte. What this code does is take the 256 value and split it into both a 16-bit (short) little-endian and big-endian formatted value and convert it back. Figure 7.9 shows the output.

 

Big Endian:

0x01 0x00

Little Endian:

0x00 0x01

 

int(256)

Figure 7.9: Output of endian test

 

If the concept of packing and unpacking bytes was a little foggy before, I hope this helps to explain it.

 

One of the nice things about binary files is that they tend to be relatively rigid in their structure. Table 7.5 shows the header for the WAV format.

 

Field

Length

Type

Contents

File type ID

4

String

 "RIFF"

Size

4

Unsigned long

Length + 4

Wave ID

4

String

"WAVE"

Data

n

 

Rest of the file

Table 7.5: Wav file header

 

So let's look at the hex data and compare it with what we've seen so far. Figure 7.10 shows the WAV file raw data.

 

101310SchroederWAVfilesc7f15

Figure 7.10: WAV file raw data

 

As expected, the first four bytes contain the string "RIFF", which stands for Resource Interchange File Format. The next four bytes are the length of the file in little-endian format. The four after that are the string "WAVE".

 

You might be looking at the file size of 0x78CD2704 (positions 4–8) and thinking that this is a huge file because that evaluates to 2,026,710,788 bytes. This is where the concept of endianness is important. We did some basic examination of endianness when we discussed network protocols. But because most IP-implemented protocols use the same endianness as IP, which is big-endian, it hasn't been much of an issue.

 

With WAV files, however, all the integers are in little-endian format, which means that the least significant byte comes first. With big-endian, the most significant byte is first. So, if we were to take the file size stated in the second field and flip it to big-endian, it would look like 0x0427CD78. This size evaluates to 69,717,368 bytes, or about 66.5 MB.

           

To read the bytes from the file and get the proper interpretation of the structure, we will use unpack() and specify the 'V' format. 'V' tells unpack() to read four bytes and return the long value from a little-endian formatted byte array, which we read as a string. Figure 7.11 shows the code to read the WAV header file.

 

$filename = 'test.wav';

$fh = fopen($filename, 'r');

 

$typeId = fread($fh, 4);

$lenP = unpack('V', fread($fh, 4));

$len = $lenP[1];

$waveId = fread($fh, 4);

 

if ($typeId === 'RIFF' && $waveId === 'WAVE') {

      echo "We have a WAV file\n";

      echo "Chunk length: {$len}\n";

} else {

      die("Invalid wave file\n");

}

Figure 7.11: Reading the WAV header file

 

Running this code produces the output shown in Figure 7.12.

 

We have a WAV file

Chunk length: 69717368

Figure 7.12: Output of reading the WAV header file

 

When we compare the actual length of the file with the chunk length, we get the chunk plus eight. What this means is that the chunk length will be the file length minus the eight bytes that were needed to determine the chunk length. A chunk, if you are not familiar, is just a block of data of a defined length. HTTP can use chunks to start downloading a file of indeterminate length. In HTTP, the length of the next chunk is appended after the end of the last chunk. Chunk, block, they all kind of mean the same thing except chunks tend to be a little more variable in length, though that is by no means a rule.

 

After we have read the header, the next step is to read chunk data. There are three types of chunks in a WAV file: the format chunk, the fact chunk (used for compression), and the data chunk. Right now, we're just interested in the format chunk because it gives us our metadata about the nature of the data in the file.

 

Table 7.6 shows the format of the format chunk.

 

Field

Length

Type (pack)

Contents

Chunk ID

4

String

 "fmt "

Size

4

Unsigned long (V)

0x16, 0x18, or 0x40

Format

2

Unsigned int (v)

 

Channels

2

Unsigned int (v)

 

Sample rate

4

Unsigned long (V)

 

Data rate

4

Unsigned long (V)

 

Block size

2

Unsigned int (v)

 

Bits/sample

2

Unsigned int (v)

 

Extension size

2

Unsigned int (v)

0 or 22

Valid nits/sample

2

Unsigned int (v)

 

Channel mask

4

Unsigned long (V)

 

Subformat

16

Unsigned char (c16)

 

Table 7.6: WAV file metadata format

 

To read the data in that format, we need to unpack() it. To do so, we append the code shown in Figure 7.13 to the code we had before.

 

$chunkId = fread($fh, 4);

if ($chunkId === 'fmt ') {

 

      $size = unpack('V', fread($fh, 4));

      if ($size[1] == 18) {

            $d = fread($fh, 18);

            $data = unpack('vfmt/vch/Vsr/Vdr/vbs/vbis/vext', $d);

            $format = array(

                  0x0001 => 'PCM',

                  0x0003 => 'IEEE Float',

                  0x0006 => 'ALAW',

                  0x0007 => 'MuLAW',

                  0xFFFE => 'Extensible',

            );

            echo "Format: {$format[$data['fmt']]}\n";

            echo "Channels: {$data['ch']}\n";

            echo "Sample Rate: {$data['sr']}\n";

            echo "Data Rate: {$data['dr']}\n";

            echo "Block Size: {$data['bs']}\n";

            echo "Bits/Sample: {$data['bs']}\n";

            echo "Extension Size: {$data['ext']}\n";

      }

}

Figure 7.13: Code to read the metadata

 

First, we read the four bytes to identify the chunk. Then, we read the size. In this case, the size returned is 18 bytes. As we saw in the preceding table, the size can be 16, 18, or 40 bytes long. That table is the 40-byte version of the header. Because my sample file uses only the 18-byte header, we will parse only that one out. That means reading up to and including the extension size field.

 

When we run the code, we get the output shown in Figure 7.14.

 

We have a WAV file

Chunk length: 69717368

Format: PCM

Channels: 2

Sample Rate: 44100

Data Rate: 176400

Block Size: 4

Bits/Sample: 4

Extension Size: 0

Figure 7.14: Output of reading the metadata

 

So we have a PCM (pulse-code modulation) WAV file with two channels, a sample rate of 44.1 KHz, and a bit rate of 176.4 kbit/second.

 

So far, so good. But that was with a relatively simple file format. What we have done here is read the basics of a format that was "more binary" than the tar format. Tar has a structured format, but it is based on structured text fields. The WAV format is structured but has more binary data in it. We could continue on with the WAV file, but because we generally do more Web-based work and the rest of the file is simply chunked data that would be output to an audio interface, the usefulness of the WAV file as an example is a little limited. With that in mind, let's move on to a format that is not so simple.

 

Editor's note: This article is an excerpt from You Want to Do WHAT with PHP?, a new book from MC Press.


 

Kevin Schroeder

Kevin Schroeder has a memory TTL of 10 years, and so he has been working with PHP for longer than he can remember. He is a member of the Zend Certification Advisory Board and is a Magento Certified Developer Plus. He has spoken at numerous conferences, including ZendCon, where he was twice the MC. When his head isn’t in code (if code is poetry, then it is Vogon poetry), Kevin is writing music, having been a guitarist since hair bands were cool (and having survived their welcomed demise). He has recorded two albums, Coronal Loop Safari and Loudness Wars. Kevin’s wisdom is dispensed to his loyal followers on Twitter at @kpschrade and on his blog at www.eschrade.com, where he speaks in the first person.


MC Press books written by Kevin Schroeder available now on the MC Press Bookstore.

Advanced Guide to PHP on IBM i Advanced Guide to PHP on IBM i
Take your PHP knowledge to the next level with this indispensable guide.
List Price $79.95

Now On Sale

The IBM i Programmer’s Guide to PHP The IBM i Programmer’s Guide to PHP
Get to know the PHP programming language and how it can--and should--be deployed on IBM i.
List Price $79.95

Now On Sale

You Want to Do What with PHP? You Want to Do What with PHP?
This book for the creative and the curious explores what’s possible with PHP.
List Price $49.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: