由于您获得的是带有 WAV 数据的缓冲区,因此您可以使用 wav-decoder 库对其进行解析,然后将其提供给 pitchfinder 库以获取音频的频率。
const Pitchfinder = require('pitchfinder')
const WavDecoder = require('wav-decoder')
const detectPitch = new Pitchfinder.YIN()
const frequency = detectPitch(WavDecoder.decode(data).channelData[0])
但是,由于您使用的是 Electron,因此您也可以只使用 Chromium 中的 MediaStream Recording API。
首先,这仅适用于 Electron 1.7+,因为它使用 Chromium 58,这是第一个包含 a bug which prevented the AudioContext from decoding audio data from the MediaRecorder 修复程序的 Chromium 版本。
另外,就这段代码而言,我将使用 ES7 async 和 await 语法,它们应该在 Node.js 7.6+ 和 Electron 1.7+ 上运行良好。
让我们假设您的 Electron 的 index.html 看起来像这样:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Frequency Finder</title>
</head>
<body>
<h1>Tuner</h1>
<div><label for="devices">Device:</label> <select id="devices"></select></div>
<div>Pitch: <span id="pitch"></span></div>
<div>Frequency: <span id="frequency"></span></div>
<div><button id="record" disabled>Record</button></div>
</body>
<script>
require('./renderer.js')
</script>
</html>
现在让我们开始处理renderer 脚本。首先,让我们设置一些我们将要使用的变量:
const audioContext = new AudioContext()
const devicesSelect = document.querySelector('#devices')
const pitchText = document.querySelector('#pitch')
const frequencyText = document.querySelector('#frequency')
const recordButton = document.querySelector('#record')
let audioProcessor, mediaRecorder, sourceStream, recording
好的,现在开始代码的其余部分。首先,让我们使用所有可用的音频输入设备填充 Electron 窗口中的 <select> 下拉列表。
navigator.mediaDevices.enumerateDevices().then(devices => {
const fragment = document.createDocumentFragment()
devices.forEach(device => {
if (device.kind === 'audioinput') {
const option = document.createElement('option')
option.textContent = device.label
option.value = device.deviceId
fragment.appendChild(option)
}
})
devicesSelect.appendChild(fragment)
// Run the event listener on the `<select>` element after the input devices
// have been populated. This way the record button won't remain disabled at
// start.
devicesSelect.dispatchEvent(new Event('change'))
})
最后你会注意到,我们调用了在 Electron 窗口中的 <select> 元素上设置的事件。但是,等等,我们从来没有写过那个事件处理程序!让我们在我们刚刚编写的代码上方添加一些代码:
// Runs whenever a different audio input device is selected by the user.
devicesSelect.addEventListener('change', async e => {
if (e.target.value) {
if (recording) {
stop()
}
// Retrieve the MediaStream for the selected audio input device.
sourceStream = await navigator.mediaDevices.getUserMedia({
audio: {
deviceId: {
exact: e.target.value
}
}
})
// Enable the record button if we have obtained a MediaStream.
recordButton.disabled = !sourceStream
}
})
让我们实际上也为记录按钮编写一个处理程序,因为此时它什么都不做:
// Runs when the user clicks the record button.
recordButton.addEventListener('click', () => {
if (recording) {
stop()
} else {
record()
}
})
现在我们显示音频设备,让用户选择它们,并有一个录制按钮......但我们还有未实现的功能 - record() 和 stop()。
让我们在这里停下来做一个架构决定。
我们可以录制音频,抓取音频数据,并分析它以获得它的音高,所有这些都在renderer.js。然而,分析音高数据是一项昂贵的操作。因此,最好能够在进程外运行该操作。
幸运的是,Electron 1.7 引入了对具有 Node 上下文的 web worker 的支持。创建 Web Worker 将允许我们在不同的进程中运行昂贵的操作,因此它不会在运行时阻塞主进程(和 UI)。
记住这一点,假设我们将在audio-processor.js 中创建一个网络工作者。我们稍后会介绍实现,但我们假设它接受带有对象的消息,{sampleRate, audioData},其中sampleRate 是采样率,audioData 是 Float32Array,我们将传递给pitchfinder.
我们也假设:
- 如果记录处理成功,工作人员将返回带有对象
{frequency, key, octave} 的消息 - 例如 {frequency: 440.0, key: 'A', octave: 4}。
- 如果录制处理失败,工作人员会返回一条带有
null 的消息。
让我们编写record函数:
function record () {
recording = true
recordButton.textContent = 'Stop recording'
if (!audioProcessor) {
audioProcessor = new Worker('audio-processor.js')
audioProcessor.onmessage = e => {
if (recording) {
if (e.data) {
pitchText.textContent = e.data.key + e.data.octave.toString()
frequencyText.textContent = e.data.frequency.toFixed(2) + 'Hz'
} else {
pitchText.textContent = 'Unknown'
frequencyText.textContent = ''
}
}
}
}
mediaRecorder = new MediaRecorder(sourceStream)
mediaRecorder.ondataavailable = async e => {
if (e.data.size !== 0) {
// Load the blob.
const response = await fetch(URL.createObjectURL(data))
const arrayBuffer = await response.arrayBuffer()
// Decode the audio.
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer)
const audioData = audioBuffer.getChannelData(0)
// Send the audio data to the audio processing worker.
audioProcessor.postMessage({
sampleRate: audioBuffer.sampleRate,
audioData
})
}
}
mediaRecorder.start()
}
一旦我们开始使用MediaRecorder 进行录制,我们将不会调用ondataavailable 处理程序,直到录制停止。现在是编写stop 函数的好时机。
function stop () {
recording = false
mediaRecorder.stop()
recordButton.textContent = 'Record'
}
现在剩下的就是在audio-processor.js 中创建我们的工人。让我们继续创建它。
const Pitchfinder = require('pitchfinder')
// Conversion to pitch from frequency based on technique used at
// https://www.johndcook.com/music_hertz_bark.html
// Lookup array for note names.
const keys = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
function analyseAudioData ({sampleRate, audioData}) {
const detectPitch = Pitchfinder.YIN({sampleRate})
const frequency = detectPitch(audioData)
if (frequency === null) {
return null
}
// Convert the frequency to a musical pitch.
// c = 440.0(2^-4.75)
const c0 = 440.0 * Math.pow(2.0, -4.75)
// h = round(12log2(f / c))
const halfStepsBelowMiddleC = Math.round(12.0 * Math.log2(frequency / c0))
// o = floor(h / 12)
const octave = Math.floor(halfStepsBelowMiddleC / 12.0)
const key = keys[Math.floor(halfStepsBelowMiddleC % 12)]
return {frequency, key, octave}
}
// Analyse data sent to the worker.
onmessage = e => {
postMessage(analyseAudioData(e.data))
}
现在,如果你一起运行这一切...... 它不会工作!为什么?
我们需要更新main.js(或任何主脚本的名称),以便在创建主 Electron 窗口时,告诉 Electron 在 web worker 的上下文中提供 Node 支持。否则,require('pitchfinder') 不会做我们希望它做的事情。
这很简单,我们只需要在窗口的webPreferences 对象中添加nodeIntegrationInWorker: true。例如:
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegrationInWorker: true
}
})
现在,如果你运行你的组合,你会得到一个简单的 Electron 应用程序,它可以让你录制一小段音频,测试它的音高,然后将音高显示到屏幕上。
这最适用于音频的小 sn-ps,因为音频越长,处理所需的时间就越长。
如果您想要一个更完整、更深入的示例,例如能够实时收听和返回音高,而不是让用户点击记录并一直停止,请查看我的electron-tuner app我做了。随意查看源代码以了解事情是如何完成的 - 我已尽力确保它得到很好的评论。
这是它的截图:
希望所有这些对您的努力有所帮助。