0

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.

Community
  • 1
  • 1
Niyaz
  • 2,677
  • 3
  • 21
  • 40
  • Hi @mikeb i did a research on it but with javascript we can accomplish with web audio api , and i am looking for that process in php. – Niyaz May 05 '16 at 12:41

3 Answers3

5

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.

Community
  • 1
  • 1
LSerni
  • 55,617
  • 10
  • 65
  • 107
2

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.

David
  • 609
  • 1
  • 4
  • 11
  • document.getElementById("audio").playbackRate=playbackspeed this will not maintain the pitch of the song. –  May 09 '16 at 13:25
  • You can't maintain the pitch of the song and speed it up that's impossible. Speeding the sound wave up aka changing the tempo also changes the frequency of the sound wave. – David May 09 '16 at 14:07
  • So there is no way to do this with javascript, right ? Gonna try with doing from backend server, can u suggest me which programming language is fleible to do this ? –  May 10 '16 at 07:01
0

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>
s.abbaasi
  • 952
  • 6
  • 14