...

The Solution to CS50 Lab 04 Volume Problem (2022)

We can use C language to modify audio files. In this lab 4 problem, we have to write a C program to increase the volume of an audio file. The input audio file is given to us in .wav format (INPUT.wav). We need to write the program so that when the user executes the following command in the terminal will provide another .wav file which includes the Audio increased output.

$ ./volume INPUT.wav OUTPUT.wav 2.0

Here “volume” is the program that executes. “OUTPUT.wav” is the output file. And 2.0 is the factor in which the volume should be increased of the input file.

Solution for the cs50 lab 04

We have two tasks to do in this lab. The first one is to copy the header from input files to output files. The second task is to read samples from the input file and write updated data to the output file.

Copy the header from input file to output file

    uint8_t header[HEADER_SIZE];
    fread(&header, HEADER_SIZE, 1, input);
    fwrite(&header, HEADER_SIZE, 1, output);

Read samples from the input file and write updated data to the output file.

    int16_t buffer;
    while (fread(&buffer, sizeof(int16_t), 1, input))
    {
        // Apply factor to the output file
        buffer *= factor;
        fwrite(&buffer, sizeof(int16_t), 1, output);
    }

Full code

// Modifies the volume of an audio file

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

// Number of bytes in .wav header
const int HEADER_SIZE = 44;

int main(int argc, char *argv[])
{
    // Check command-line arguments
    if (argc != 4)
    {
        printf("Usage: ./volume input.wav output.wav factor\n");
        return 1;
    }

    // Open files and determine scaling factor
    FILE *input = fopen(argv[1], "r");
    if (input == NULL)
    {
        printf("Could not open file.\n");
        return 1;
    }

    FILE *output = fopen(argv[2], "w");
    if (output == NULL)
    {
        printf("Could not open file.\n");
        return 1;
    }

    float factor = atof(argv[3]);

    // TODO: Copy header from input file to output file
    uint8_t header[HEADER_SIZE];
    fread(&header, HEADER_SIZE, 1, input);
    fwrite(&header, HEADER_SIZE, 1, output);

    // TODO: Read samples from input file and write updated data to output file
    int16_t buffer;
    while (fread(&buffer, sizeof(int16_t), 1, input))
    {
        // Apply factor to the output file
        buffer *= factor;
        fwrite(&buffer, sizeof(int16_t), 1, output);
    }

    // Close files
    fclose(input);
    fclose(output);
}

Hope this helps! Leave a comment if you want more clarification on this!

(Visited 109 times, 1 visits today)
Share on facebook
Share on twitter
Share on linkedin
Share on pinterest
Share on reddit
Share on tumblr
Share on telegram
Share on pocket
Share on whatsapp
Share on email

Leave a Reply

Seraphinite AcceleratorOptimized by Seraphinite Accelerator
Turns on site high speed to be attractive for people and search engines.