Skip to content

Commit

Permalink
sol: lab4/volume
Browse files Browse the repository at this point in the history
  • Loading branch information
jfvillablanca committed Nov 2, 2023
1 parent ac8dd41 commit b311e58
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
1 change: 1 addition & 0 deletions lab4/volume/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
https://cs50.harvard.edu/x/2023/labs/4/volume/
57 changes: 57 additions & 0 deletions lab4/volume/volume.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// 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]);

uint8_t header[HEADER_SIZE];
size_t read_bytes = fread(header, 1, HEADER_SIZE, input);
size_t written_bytes = fwrite(header, 1, read_bytes, output);

if (written_bytes != read_bytes)
{
printf("Error writing to file\n");
return 1;
}

int16_t sample;
while (fread(&sample, sizeof(int16_t), 1, input))
{
// ASSUMPTION: does not go beyond UINT16_MAX
sample *= factor;
fwrite(&sample, sizeof(int16_t), 1, output);
}

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

0 comments on commit b311e58

Please sign in to comment.