Stream audio from pyaudio with Flask to HTML5

paranerd picture paranerd · Nov 4, 2017 · Viewed 9.8k times · Source

I want to stream the audio of my microphone (that is being recorded via pyaudio) via Flask to any client that connects.

This is where the audio comes from:

    def getSound(self):
        # Current chunk of audio data
        data = self.stream.read(self.CHUNK)
        self.frames.append(data)
        wave = self.save(list(self.frames))

        return data

Here's my flask-code:

@app.route('/audiofeed')
def audiofeed():
    def gen(microphone):
        while True:
            sound = microphone.getSound()
            #with open('tmp.wav', 'rb') as myfile:
            #   yield myfile.read()

            yield sound

    return Response(stream_with_context(gen(Microphone())))

And this is the client:

    <audio controls>
        <source src="{{ url_for('audiofeed') }}" type="audio/x-wav;codec=pcm">
        Your browser does not support the audio element.
    </audio>

It does work sometimes, but most of the times I'm getting "[Errno 32] Broken pipe"

When uncommenting that with open("tmp.wav")-part (the self.save() optionally takes all previous frames and saves them in tmp.wav), I kind of get a stream, but all that comes out of the speakers is a "clicking"-noise.

I'm open for any suggestions. How do I get the input of my microphone live-streamed (no pre-recording!) to a webbrowser?

Thanks!

Answer

Shantanu Sharma picture Shantanu Sharma · Feb 14, 2019

Try This its worked for me. shell cmd "cat" is working perfect see the code iam using FLASK

import subprocess
import os
import inspect
from flask import Flask
from flask import Response

@app.route('/playaudio')
    def playaudio():
        sendFileName=""
        def generate():

            #  get_list_all_files_name this function gives all internal files inside the folder

   filesAudios=get_list_all_files_name(currentDir+"/streamingAudios/1")

            # audioPath is audio file path in system 
            for audioPath in filesAudios:
                data=subprocess.check_output(['cat',audioPath])
                yield data
        return Response(generate(), mimetype='audio/mp3')