首页 > 解决方案 > 如何在python3中将音频流写入文件

问题描述

我正在与 Nexmo 合作。我想将直播 Nexmo 通话音频保存到我的磁盘。我已经实现了网络套接字来读取 Nexmo 的流。请在下面找到我将音频附加到现有音频文件的代码。

#!/usr/bin/env python

# WS server example

import asyncio
import websockets

async def nexmoServer(websocket, path):
    audioData = await websocket.recv()

    input_filename = "sample_harshit.wav"
    output_filename = "new_file.wav"
    ifile = open(input_filename,'rb')
    ofile = open(output_filename, 'wb')
    data = audioData
    while data:
        ofile.write(data)
        data = ifile.read(1024*1024)
    ofile.close()
    ifile.close()

音频文件的长度已更新,但音频数据未写入文件中。

标签: pythonwebsocketnexmo

解决方案


至少这工作正常:

def nexmoServer():
    input_filename = "a.wav"
    output_filename = "b.wav"
    ifile = open(input_filename,'rb')
    ofile = open(output_filename, 'wb')
    data = ifile.read(1024*1024)
    while data:
        ofile.write(data)
        data = ifile.read(1024*1024)
    ofile.close()
    ifile.close()

nexmoServer()

推荐阅读