最近学习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都代表一些处理函数,也就是几行代码,而不是数据。通常来讲,变量一般代表数据,但是这里代表了指令。
首先,需要安装好编程环境。比如python的idel。其次,要明确需求,根据实际需求编写代码写出要实现的功能逻辑。
然后,对代码进行调试验证,进行执行。
对脚本进行封装,形成可执行文件。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)