如何在Azure Function中安装Librosa重采样所需的Libsndfile与Libsamplerate依赖
解决方案
针对Azure Function Linux环境下安装Libsndfile和Libsamplerate依赖的需求,可选择以下两种方案:
方案1:自定义Docker镜像部署(推荐,稳定性最高)
该方案将系统依赖打包进镜像,不会增加冷启动时间,适用于所有Azure Function Linux托管计划。
步骤如下:
- 在函数项目根目录新建
Dockerfile,内容参考(可根据你使用的Python版本调整基础镜像标签):
FROM mcr.microsoft.com/azure-functions/python:4-python3.10-appservice # 切换root权限安装系统依赖 USER root RUN apt-get update && apt-get install -y --no-install-recommends \ libsndfile1 \ libsndfile1-dev \ build-essential \ wget \ && rm -rf /var/lib/apt/lists/* # 编译安装Libsamplerate RUN wget https://github.com/libsndfile/libsamplerate/archive/refs/tags/0.2.2.tar.gz \ && tar -xzf 0.2.2.tar.gz \ && cd libsamplerate-0.2.2 \ && ./configure \ && make \ && make check \ && make install \ && cd .. && rm -rf libsamplerate-0.2.2 0.2.2.tar.gz # 切换回默认函数运行用户 USER app # 安装Python依赖 COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt # 复制函数代码 COPY . /home/site/wwwroot
- 按照Azure Function自定义容器部署流程,将镜像推送到容器注册表后部署即可。
方案2:启动脚本动态安装依赖(无需修改部署流程,仅支持Linux计划)
该方案无需打包镜像,通过自定义启动命令在函数实例启动时安装依赖,适合测试场景,缺点是会增加冷启动耗时。
步骤如下:
- 在函数项目根目录新建
startup.sh脚本,内容如下:
#!/bin/bash # 安装基础系统依赖 apt-get update apt-get install -y libsndfile1 libsndfile1-dev build-essential wget # 编译安装libsamplerate wget https://github.com/libsndfile/libsamplerate/archive/refs/tags/0.2.2.tar.gz tar -xzf 0.2.2.tar.gz cd libsamplerate-0.2.2 ./configure make make check make install cd .. && rm -rf libsamplerate-0.2.2 0.2.2.tar.gz # 刷新动态库配置 ldconfig # 执行函数默认启动命令 exec azure-functions-runtime
- 本地给脚本添加执行权限:
chmod +x startup.sh - 进入Azure Function门户,依次打开「配置」→「通用设置」,在「启动命令」字段填写
/home/site/wwwroot/startup.sh,保存配置。 - 将
startup.sh和函数代码一起打包部署即可。
可选优化
如果你对重采样精度要求不高,可将librosa.resample的res_type参数修改为kaiser_best或kaiser_fast,这两个后端基于scipy实现,不需要依赖Libsamplerate,可减少一个系统依赖的安装。
内容的提问来源于stack exchange,提问作者user14834847
相关产品推荐
相关产品推荐

