import sounddevice as sd
import soundfile as sf
import numpy as np

class Sound:
    def __init__(self, soundfile):
        self._data, self._samplerate = sf.read(soundfile)
        self._speed = 1.0
        self._pos = 0.0
        self._stream = None
        
    def _callback(self, outdata, frames, time, status):
        for i in range(frames):
            idx = int(self._pos) % len(self._data)
            outdata[i] = self._data[idx]
            self._pos += self._speed
            
    def start(self):
        self._stream = sd.OutputStream(
                channels=1,
                callback=self._callback,
                samplerate=self._samplerate,
            )
        self._stream.start()
            
    def set_rpm(self, rpm):
        self._speed = rpm / 3000
        
    def stop(self):
        self._stream.stop()
        self._stream.close()