精通
英语
和
开源
,
擅长
开发
与
培训
,
胸怀四海
第一信赖
锐英源精品原创文章,禁止转载和任何形式的非法内容使用,违者必究
最近学习pytorch,看到下面的Python高难度代码例子和Python最复杂代码例子:
from google.colab import output as colab_output
from base64 import b64decode
from io import BytesIO
from pydub import AudioSegment
RECORD = """
const sleep = time => new Promise(resolve => setTimeout(resolve, time))
const b2text = blob => new Promise(resolve => {
const reader = new FileReader()
reader.onloadend = e => resolve(e.srcElement.result)
reader.readAsDataURL(blob)
})
var record = time => new Promise(async resolve => {
stream = await navigator.mediaDevices.getUserMedia({ audio: true })
recorder = new MediaRecorder(stream)
chunks = []
recorder.ondataavailable = e => chunks.push(e.data)
recorder.start()
await sleep(time)
recorder.onstop = async ()=>{
blob = new Blob(chunks)
text = await b2text(blob)
resolve(text)
}
recorder.stop()
})
"""
def record(seconds=1):
display(ipd.Javascript(RECORD))
print(f"Recording started for {seconds} seconds.")
s = colab_output.eval_js("record(%d)" % (seconds * 1000))
print("Recording ended.")
b = b64decode(s.split(",")[1])
fileformat = "wav"
filename = f"_audio.{fileformat}"
AudioSegment.from_file(BytesIO(b)).export(filename, format=fileformat)
return torchaudio.load(filename)
waveform, sample_rate = record()
print(f"Predicted: {predict(waveform)}.")
ipd.Audio(waveform.numpy(), rate=sample_rate)
js 的Promise函数对象编程,字符串javascript函数对象,IPython解释js对象,解释结果和python代码结合,IPython Shell显示非字符串数据,python音频使用IPython简单调用。
复杂Python模块下的多知识点结合代码,是Python高难度代码的体现。
Js的Promise理解为动态函数,比C++的类成员函数和全局函数这类静态形式的函数处理灵活,不过初学者理解起来麻烦。代码里sleep和b2text都代表一些处理函数,也就是几行代码,而不是数据。通常来讲,变量一般代表数据,但是这里代表了指令。