使用 Flask 保存音频文件,然后立即打印其持续时间会给出错误的持续时间

问题描述 投票:0回答:1

我正在使用 Flask 作为网络应用程序。我的前端录制一些音频并将其发送到 Flask 路由。在路线中,我将 wav 音频文件保存到上传文件夹中:

    # Save the audio file to a unique file
    filename = f"audio_{datetime.now().strftime('%Y%m%d%H%M%S')}{extension}"
    audio_path = os.path.join('uploads', filename)
    audio_file.save(audio_path)
    print(f"Saved audio file to {audio_path}.")

当我播放上传文件夹中的文件时,它似乎已正确保存,并且音频持续时间为 3 秒长。

然后,我立即使用 ffprobe 函数验证音频文件的持续时间:

    # Verify the duration of the original WAV file
    if extension == '.wav':
        print("Verifying the duration of the original WAV file...")
        duration_before_conversion = get_audio_duration(audio_path)
        print(f"Original WAV file duration: {duration_before_conversion} seconds")

它打印出该文件的长度不到 1 秒(总是在 1 秒的 0.05 秒之内)。

想知道是什么原因导致它说文件长 1 秒,而上传文件夹中的文件长度肯定是 3 秒?

当我之后尝试使用音频文件(将其转换为不同的采样率)时,它只有 1 秒长。


当我从终端使用 ffprobe 显示文件的持续时间时,它显示 ~0.99 秒,尽管当我下载文件时,它肯定是 3 秒长。

编辑:我有一个理论,即前端将音频传递到后端时元数据不正确。有趣的是,这只是 iOS 上的问题,而不是 Windows 和 Android 上的问题。有其他人在 iOS 上遇到过这个问题吗?这是创建 AudioBlob 并将其发送到后端的函数:

编辑:我尝试下载音频文件,然后使用 ffprobe 在本地检查它的长度。它给出了正确的音频持续时间。

然后,我在生产服务器上的文件上尝试了相同的 ffprobe 命令,但它给出了错误的音频持续时间。

然后我比较了这两个文件的 MD5 哈希值,它们是相同的。

原来我的生产服务器(Python Anywhere)正在运行与我的本地服务器不同版本的 ffprobe,这可以解释其中的差异吗?会回来报告的。

javascript flask audio wav ffprobe
1个回答
0
投票

经过多天的痛苦和困惑后找到了解决方案。我的生产服务器 (PythonAnywhere) 使用旧版本的 ffmpeg/ffprobe (4.7)。由于您无法更新这些服务器,因此我下载了最新的静态版本并将其添加到我的工作目录中。然后我这样引用它:


# Use ffprobe to get the duration of the audio file (for WAV files only)
    if mime_type == 'audio/mp4':
        ffprobe_command = ['./ffmpeg-6.0-amd64-static/ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', audio_path]
        duration_result = subprocess.run(ffprobe_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        duration = float(duration_result.stdout)  # Convert the result to float
        print(f"Duration of the audio file: {duration} seconds")

它给出了文件的正确持续时间。不确定为什么旧版本的 ffmpeg/ffprobe 无法工作,但如果遇到此问题,请检查您的生产服务器。有趣的是,这只是最初由 iOS 设备 (mp4) 录制的音频存在问题,在 Android 和 Windows 设备 (WebM) 上运行良好。

© www.soinside.com 2019 - 2024. All rights reserved.