human
I am working on the file "IntroductionStreamingAdaptatif/Introduction au streaming adaptatif.ipynb".
The first task is:
StreamEngine
Le StreamEngine choisi le prochain segment en fonction de la vitesse de transfert
Can you write Python code for it?
 ... Give me a the Python code you requested?
assistant
#Here is the Python code you requested.

class StreamEngine:
    
    currentStream = None
    streamM3 = None
    streams = None
    
    def __init__(self, uri):
        self.streams = sorted([Stream(playlist.stream_info.bandwidth, playlist.uri) 
                               for playlist in m3u8.load(uri).playlists])
        self.currentStream = self.streams[0]
        self.streamM3 = m3u8.load(self.currentStream.uri)
    
    def selectStream(self, speed):
        newStream = self.currentStream
        
        for stream in self.streams:
            if stream.bandwidth < speed:
                newStream = stream
            else:
                break
        
        if newStream != self.currentStream:
            self.currentStream = newStream
            self.streamM3 = m3u8.load(newStream.uri)
            print('Changing Streams: New BitRate %d' %newStream.bandwidth)
        
        return self.streamM3

def getSegment(segment):
    buf = BytesIO()
    r = get(segment.uri, stream=True)
    for chunk in r.iter_content(chunk_size=2048): 
        if chunk:
            buf.write(chunk)
    return buf