#๐Ÿ”’ Implementing a pause functionality for audio with the library `sounddevice`

4 messages ยท Page 1 of 1 (latest)

left token
#

Hey guys! I'm trying to use the library called sound device to make, sort of a music player where you can stream out multiple tracks potentially, so I need to implement a pause/ resume feature. My code currently plays the song (a numpy array of samples) using sounddevice in a coroutine.

import sys
from threading import Event
import asyncio
import sounddevice as sd
import numpy as np
from pedalboard import Pedalboard
from pedalboard.io import AudioFile
import aioconsole

filname = "session.mp3"
with AudioFile(filname) as f:
    samples = f.read(f.frames)
    sample_rate = f.samplerate

current_frame = 0
data = samples.T
print(data.shape)
playing = "b"
pause_event = asyncio.Event()

def callback(outdata, frames, time, status):
    global current_frame, playing
    if playing == "a":
        print("you just hit pause")
        return

    if status:
        print(status)
    chunksize = min(len(data) - current_frame, frames)
    outdata[:chunksize, :] = data[current_frame:current_frame + chunksize]
    if chunksize < frames:
        outdata[chunksize:] = 0
        raise sd.CallbackStop()
    current_frame += chunksize

async def get_steam_reader(pipe) -> asyncio.StreamReader:
    loop = asyncio.get_event_loop()
    reader = asyncio.StreamReader(loop=loop)
    protocol = asyncio.StreamReaderProtocol(reader)
    await loop.connect_read_pipe(lambda: protocol, pipe)
    return reader


async def main():
    event = asyncio.Event()
    reader = await get_steam_reader(sys.stdin)
    playing = await reader.readline()
    stream = sd.OutputStream(
        samplerate=sample_rate, channels=data.shape[1],
        callback=callback, finished_callback=event.set)
    with stream:
        await event.wait()

if __name__ == "__main__":
    coroutine = asyncio.run(main())

Right now when I hit either a or b, it just plays the song and never pauses.

bold sinewBOT
#

@left token

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

bold sinewBOT
#

@left token

Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.