音频流在Flask中使用生成器/生成器不起作用。

huangapple go评论67阅读模式
英文:

audio streaming not working in flask using generator / yield

问题

I'm here to assist with the translation, as requested. Here's the translated code portion:

我正在尝试在Flask中使用生成器/ yield连续播放两个音频文件但它只播放第一个文件而不是另一个以下是我的代码

    from flask import Flask, send_file, Response
    import random
    import time
    import wave
    
    # Flask构造函数以当前模块的名称(__name__)作为参数。
    app = Flask(__name__)
     
    # Flask类的route()函数是一个装饰器,告诉应用程序哪个URL应该调用相关的函数。
    @app.route('/')
    # ‘/’ URL与paadas()函数绑定。
    def paadas():
        方法2不起作用
        def generate(files):
            for file in files:
                yield file.read()
    
        files = []
        number = random.randint(1,10)
        f1 = open("../numbers/" + str(number) + ".wav", 'rb')
        files.append(f1)
        times = random.randint(1,10)
        f2 = open("../times/" + str(times) + ".wav", 'rb')
        files.append(f2)
        return Response(generate(files), mimetype='audio/wav')
    
    # 主驱动程序函数
    if __name__ == '__main__':
     
        # Flask类的run()方法在本地开发服务器上运行应用程序。
        app.run()

Please note that I've translated the code as requested, and I'm not providing any additional information or answers to questions.

英文:

I am trying to stream two audio files one after the other in flask using generator / yield. However it plays only the first file and not the other. Following is my code:

from flask import Flask, send_file, Response
import random
import time
import wave

# Flask constructor takes the name of
# current module (__name__) as argument.
app = Flask(__name__)
 
# The route() function of the Flask class is a decorator,
# which tells the application which URL should call
# the associated function.
@app.route('/')
# ‘/’ URL is bound with paadas() function.
def paadas():
    Approach 2: not working
    def generate(files):
        for file in files:
            yield file.read()

    files = []
    number = random.randint(1,10)
    f1 = open("../numbers/" + str(number) + ".wav", 'rb')
    files.append(f1)
    times = random.randint(1,10)
    f2 = open("../times/" + str(times) + ".wav", 'rb')
    files.append(f2)
    return Response(generate(files), mimetype='audio/wav')

# main driver function
if __name__ == '__main__':
 
    # run() method of Flask class runs the application
    # on the local development server.
    app.run()

What am I missing here? You can see my attempt of three approaches at https://github.com/sameermahajan/PaadasMLFlaskApp Only the first one works but it is not very elegant. If you want to try out the program, you can get the prerecorded audios of "numbers" and "times" from https://github.com/sameermahajan/Paadas These are numbers in marathi (an Indian language) in reciting table format.

答案1

得分: 1

When streaming, the headers from the second file are not properly interpreted, and it might cause the second file not to play.

我们在流媒体时,第二个文件的头部没有被正确解释,这可能会导致第二个文件无法播放。

We could use the wave module to remove the headers from the second file and then concatenate the audio files, notice that it might not work if the file does not have the same sample rate, sample width, and number of channels.

我们可以使用 wave 模块来删除第二个文件的头部,然后将音频文件连接起来,注意如果文件的采样率、采样宽度和声道数不相同,这可能不起作用。

from flask import Flask, Response
import random
import wave
import io

app = Flask(__name__)

@app.route('/')
def paadas():
    def generate(files):
        with wave.open(files[0], 'rb') as f:
            params = f.getparams()
            frames = f.readframes(f.getnframes())

        for file in files[1:]:
            with wave.open(file, 'rb') as f:
                frames += f.readframes(f.getnframes())

        buffer = io.BytesIO()
        with wave.open(buffer, 'wb') as f:
            f.setparams(params)
            f.writeframes(frames)

        buffer.seek(0)
        return buffer.read()

    files = []
    number = random.randint(1, 10)
    files.append("../numbers/" + str(number) + ".wav")
    times = random.randint(1, 10)
    files.append("../times/" + str(times) + ".wav")

    return Response(generate(files), mimetype='audio/wav')

if __name__ == '__main__':
    app.run()

如果您需要进一步的帮助,请随时提问。

英文:

When streaming, the headers from the second file are not properly interpreted it might cause the second file not to play.

We could use the wave module to remove the headers from the second file and then concatenate the audio files, notice that it might not work if the file does not have the same sample rate, sample width, and number of channels.

from flask import Flask, Response
import random
import wave
import io

app = Flask(__name__)

@app.route('/')
def paadas():
    def generate(files):
        with wave.open(files[0], 'rb') as f:
            params = f.getparams()
            frames = f.readframes(f.getnframes())
        
        for file in files[1:]:
            with wave.open(file, 'rb') as f:
                frames += f.readframes(f.getnframes())
        
        buffer = io.BytesIO()
        with wave.open(buffer, 'wb') as f:
            f.setparams(params)
            f.writeframes(frames)
        
        buffer.seek(0)
        return buffer.read()

    files = []
    number = random.randint(1,10)
    files.append("../numbers/" + str(number) + ".wav")
    times = random.randint(1,10)
    files.append("../times/" + str(times) + ".wav")
    
    return Response(generate(files), mimetype='audio/wav')

if __name__ == '__main__':
    app.run()

huangapple
  • 本文由 发表于 2023年5月13日 20:41:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76242791.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定