user1714819
user1714819

Reputation: 131

How can I change playback speed of an audio file in python whilst it is playing?

I've done alot of searching to try and find a way to achieve this but the solutions I've found either don't do what I need or I don't understand them.

I'm looking for a way of playing a sound in python (non-blocking) that allows me to change the playback speed in real time, as it's playing, with no gaps or cutouts.

Changing the pitch is fine. Audio quality isn't even that important.

Most of the solutions I've found only allow setting the playback speed once, before the file is played.

Upvotes: 6

Views: 2926

Answers (2)

Colin Curtain
Colin Curtain

Reputation: 267

I have done this in my python project. I use VLC to present audio/video within a PyQt5 GUI. The GUI has controls to slow or speed the A/V while it is playing. https://github.com/ccbogel/QualCoder The main python file for displaying audio/video is in: view_av.py and in there is the Class DialogViewAV It imports some additional modules for the GUI and vlc integration, if it helps you get your head around it and extract the bits of code you need.

I have a video explaining using the A/V part of the software and at 45 seconds in I mention the playback speed changing option. https://www.youtube.com/watch?v=TjOfPvvXh7U&t=0s

If I get time, maybe, I can prepare a script to do what you are after.

A/V controls

Upvotes: 1

user1714819
user1714819

Reputation: 131

I've found a solution, using python-mpv, a wrapper for mpv.io

from pynput.keyboard import Key, Listener
import mpv
speed=1

#quick function to change speed via keyboard. 
def on_press(key):

    global speed

    if key.char == 'f' :
        speed=speed-0.1
        player.speed=speed
    if key.char == 'g' :
        speed=speed+0.1
        player.speed=speed

player = mpv.MPV(ytdl=True)
player.play('/Users/regvardy/mediapipe_faceswap-main/test.wav')
with Listener(
        on_press=on_press) as listener:
    listener.join()
while True:
    
    player.speed=speed

I haven't tested it for stability yet.

It feels like a workaround rather than me actually finding out how to do it so I may try and find a different solution.

Upvotes: 0

Related Questions