C++ apply volume level on an audio file

48 Views Asked by At

I'm trying to apply a custom volume level for an audio file. My following code runs successfully, but the final .m4a audio does not play.

#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace std;

int main(int argc, char* argv[]) {
    if (argc != 4) {
        cerr << "Usage: " << argv[0] << " <input file> <volume level> <output file>" << endl;
        return 1;
    }

    // Parse arguments
    string input_path = argv[1];
    float volume_level = stof(argv[2]);
    string output_path = argv[3];
    cout << "Input file: " << input_path << endl;
    cout << "Volume level: " << volume_level << endl;
    cout << "Output file: " << output_path << endl;

    // Open input file
    FILE* input_file = fopen(input_path.c_str(), "rb");
    if (input_file == NULL) {
        cerr << "Could not open input file" << endl;
        return 1;
    }

    // Open output file
    FILE* output_file = fopen(output_path.c_str(), "wb");
    if (output_file == NULL) {
        cerr << "Could not open output file" << endl;
        return 1;
    }

    // Read input file and write to output file with volume level
    const int BUFFER_SIZE = 4096;
    char buffer[BUFFER_SIZE];
    while (true) {
        // Read from input file
        size_t bytes_read = fread(buffer, 1, BUFFER_SIZE, input_file);
        if (bytes_read == 0) {
            break;
        }

        // Apply volume level
        for (int i = 0; i < bytes_read; i++) {
            buffer[i] = (char) (buffer[i] * volume_level);
        }

        // Write to output file
        fwrite(buffer, 1, bytes_read, output_file);
    }

    // Close files
    fclose(input_file);
    fclose(output_file);

    cout << "Done" << endl;
    return 0;
}
// to compile this use : g++ -o transcode transcode.cpp
0

There are 0 best solutions below