python文件写入未创建新文件
我有一个django应用程序,我从一个javascript客户端接收到二进制音频数据,我正试图将其发送到google云语音到文本API。问题在于,python没有将二进制音频数据写入文件。所以我要python文件写入未创建新文件,python,django,python-2.7,Python,Django,Python 2.7,我有一个django应用程序,我从一个javascript客户端接收到二进制音频数据,我正试图将其发送到google云语音到文本API。问题在于,python没有将二进制音频数据写入文件。所以我要 with io.open(file_name, "rb") as f: FileNotFoundError: [Errno 2] No such file or directory: '.........\\gcp_cloud\\blog\\audio_file.wav' 我将路径的第一部分替换为
with io.open(file_name, "rb") as f:
FileNotFoundError: [Errno 2] No such file or directory: '.........\\gcp_cloud\\blog\\audio_file.wav'
我将路径的第一部分替换为
这是客户端代码
rec.ondataavailable = e => {
audioChunks.push(e.data);
if (rec.state == "inactive"){
let blob = new Blob(audioChunks,{type:'audio/wav; codecs=MS_PCM'});
recordedAudio.src = URL.createObjectURL(blob);
recordedAudio.controls=true;
recordedAudio.autoplay=true;
sendData(blob)
}
}
这是我的sendData函数
function sendData(data) {
let csrftoken = getCookie('csrftoken');
let response=fetch("/voice_request", {
method: "post",
body: data,
headers: { "X-CSRFToken": csrftoken },
})
console.log('got a response from the server')
console.log(response)
}
这里是DJango视图,它处理来自客户端的二进制音频数据
def voice_request(request):
#print(request.body)
fw = open('audio_file.wav', 'wb')
fw.write(request.body)
file_name = os.path.join(current_folder, 'audio_file.wav')
#file_name = os.path.join(current_folder, 'Recording.m4a')
client = speech.SpeechClient()
# The language of the supplied audio
language_code = "en-US"
# Sample rate in Hertz of the audio data sent
sample_rate_hertz = 16000
encoding = enums.RecognitionConfig.AudioEncoding.LINEAR16
config = {
"language_code": language_code,
#"sample_rate_hertz": sample_rate_hertz,
#"encoding": 'm4a',
}
with io.open(file_name, "rb") as f:
content = f.read()
audio = {"content": content}
fw.close()
response = client.recognize(config, audio)
print('response')
print(response)
for result in response.results:
# First alternative is the most probable result
alternative = result.alternatives[0]
print(u"Transcript: {}".format(alternative.transcript))
return HttpResponse(response)
您应该使用
和io.open(文件名,“wb”)作为f:
或和io.open(文件名,“ab”)作为f:
因为r
表示只读,w
表示“重写”
您可以参考:为什么不为
'audio\u file.wav'
使用上下文管理器?另外,您在代码中的何处创建文件?我不确定我是否理解问题所在,据我所知,您正在尝试读取一个不存在的文件,这显然会导致错误。在voice_请求视图中保存文件audio_file.wav后,是否保存了有效的wav文件。另外,当使用fw.write(request.body)保存时,您正在写入当前文件夹。那么,为什么不直接从当前文件夹中读取它,而不使用os.path.join指定完整的路径(当前文件夹…@AlexanderCécile我不知道什么是上下文管理器,但我会查找它。我正在写入一个文件,fw.write(request.body)
,我认为这会创建一个不存在的文件,并覆盖一个现有的文件。既然它不工作,我该如何实现这一效果?@bhaskarc我在工作目录中看不到文件。我猜它不是真的在写入文件。我将其更改为直接指定文件,现在我没有收到文件未找到错误,但是oogle cloud API没有返回任何响应。我仍然无法在我的目录中看到该文件。@Rockstar5645据我所知,打开(…,'wb')
如果文件不存在,则应创建该文件。上下文管理器是使用with
语句创建的,您已经在代码中的其他地方使用了一个!请更改它,使其使用上下文管理器,然后查看是否修复了问题?