Niyaz
Niyaz

Reputation: 2893

How to change the tempo of an audio file using PHP?

Is there is any possible way to set the tempo of audio file using PHP?

With the below

How to detect the BPM of a song in php

we can detect the bpm (get bpm) but i couldn't find a way to set the tempo for audio mp3 files.

Upvotes: 0

Views: 1852

Answers (3)

s.abbaasi
s.abbaasi

Reputation: 1114

you may need to put the following script in your code:

    <script>
        var audio = document.querySelector('audio');
        audio.addEventListener('loadedmetadata', function() {
            audio.playbackRate = 2;
        });
    </script>

Upvotes: 0

LSerni
LSerni

Reputation: 57388

One does not simply set the tempo for an audio file. If you increase its playback speed, the same number of soundwave peaks get crammed in less time; they get squashed together, the wavelength has to decrease, which means that the frequency increases proportionally, and as Niyaz and other observed, you hear a higher "pitch".

If you want double speed, you need to squash together the waves in half the time, but then to set them back to the original width you need to drop half of them (one in two). This operation cannot be (easily) done in PHP.

You can do this for example using SoX or ffmpeg (emphasis mine):

FFmpeg has a built-in audio filter for changing the tempo without changing the pitch. We need to encode the file to some format your phone plays. This depends on the phone of course. Many modern smartphones like AAC audio:

ffmpeg -i weird.wma -filter:a "atempo=1.7" -c:a libfaac -q:a 100

final.m4a

You would of course use .mp3, not wma or m4a, as both input and output.

In PHP you simply call ffmpeg:

$results = shell_exec("/path/to/wherever/is/ffmpeg -i '{$inputFile}' -filter:a 'atempo={$newTempo}' -q:a {$percentQuality} '{$outputFile}' 2>&1");

and check $results and whether the output file is OK.

Upvotes: 5

David
David

Reputation: 609

The easiest way is one line of JavaScript.

document.getElementById("audio").playbackRate=playbackspeed

If you want to use php to process the video/audio to a slower speed you can use ffmpeg. https://trac.ffmpeg.org/wiki/How%20to%20speed%20up%20/%20slow%20down%20a%20video

Note that processing the video/audio with php can take a long time if you don't own massive servers.

Upvotes: 2

Related Questions