我工作的一个程序,文本转换成莫尔斯电码的音频。
说我在sos
类型。我的计划会变成数组[1, 1, 1, 0, 2, 2, 2, 0, 1, 1, 1]
这一点。凡s = dot dot dot
(或1,1,1
),和o = dash dash dash
(或2,2,2
)。这部分是很容易的。
接下来,我有两个声音文件:
var dot = new Audio('dot.mp3');
var dash = new Audio('dash.mp3');
我的目标是有一个函数,当它看到一个dot.mp3
,并1
当它看到一个dash.mp3
,将发挥2
,并且当它看到一个0
暂停。
以下排序的/样/时而工作,但我认为这是根本性的缺陷,我不知道如何解决它。
function playMorseArr(morseArr) {
for (let i = 0; i < morseArr.length; i++) {
setTimeout(function() {
if (morseArr[i] === 1) {
dot.play();
}
if (morseArr[i] === 2) {
dash.play();
}
}, 250*i);
}
}
问题:
我可以在阵列上循环,并播放声音文件,但时间是一个挑战。如果我不设置setTimeout()
间隔恰到好处,如果没有完成最后的音频文件播放和250ms
已过,数组中的下一个元素将被跳过。所以dash.mp3
比dot.mp3
更长。如果我的时间太短了,我可能会听到[dot dot dot pause dash dash pause dot dot dot]
,或诸如此类的话。
我想要的效果
我希望该计划是这样的(伪代码):
ith
数组元素1
或2
,开始播放声音文件或者建立一个暂停i
并回到步骤1我已经想到了,但不知道如何实现
所以泡菜是,我希望循环同步进行。我用承诺在那里我有,我在一个特定的顺序执行通缉多种功能的情况,但我会怎样链上的数目不详的功能是什么?
我使用自定义事件也考虑过,但我有同样的问题。
不要使用HTMLAudioElement为一种应用。
该HTMLMediaElements本质上是异步的,一切从play()
方法将pause()
之一,经历了明显的资源获取和不太明显currentTime
设置是异步的。
这意味着,对于那些需要完美的时机(如莫尔斯电码阅读器)应用程序,这些元素是纯粹不可靠的。
取而代之的是,使用网络音频API,它AudioBufferSourceNodes对象,你可以用微秒精度控制。
需要生成并从这些ArrayBuffers发挥AudioBufferSourceNodes时,首先获取所有资源为ArrayBuffers,然后。
你就可以开始同步播放这些,或将它们与比setTimeout的精度更高的调度会为您提供(AudioContext使用自己的时钟)。
担心有几个AudioBufferSourceNodes打你们的样品内存的影响?不要。该数据只存储一次在内存中,在AudioBuffer。 AudioBufferSourceNodes只是欣赏这个数据和占用的地方。
// I use a lib for Morse encoding, didn't tested it too much though
// https://github.com/Syncthetic/MorseCode/
const morse = Object.create(MorseCode);
const ctx = new (window.AudioContext || window.webkitAudioContext)();
(async function initMorseData() {
// our AudioBuffers objects
const [short, long] = await fetchBuffers();
btn.onclick = e => {
let time = 0; // a simple time counter
const sequence = morse.encode(inp.value);
console.log(sequence); // dots and dashes
sequence.split('').forEach(type => {
if(type === ' ') { // space => 0.5s of silence
time += 0.5;
return;
}
// create an AudioBufferSourceNode
let source = ctx.createBufferSource();
// assign the correct AudioBuffer to it
source.buffer = type === '-' ? long : short;
// connect to our output audio
source.connect(ctx.destination);
// schedule it to start at the end of previous one
source.start(ctx.currentTime + time);
// increment our timer with our sample's duration
time += source.buffer.duration;
});
};
// ready to go
btn.disabled = false
})()
.catch(console.error);
function fetchBuffers() {
return Promise.all(
[
'https://dl.dropboxusercontent.com/s/1cdwpm3gca9mlo0/kick.mp3',
'https://dl.dropboxusercontent.com/s/h2j6vm17r07jf03/snare.mp3'
].map(url => fetch(url)
.then(r => r.arrayBuffer())
.then(buf => ctx.decodeAudioData(buf))
)
);
}
<script src="https://cdn.jsdelivr.net/gh/mohayonao/promise-decode-audio-data@eb4b1322113b08614634559bc12e6a8163b9cf0c/build/promise-decode-audio-data.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/Syncthetic/MorseCode@master/morsecode.js"></script>
<input type="text" id="inp" value="sos"><button id="btn" disabled>play</button>
Audio
s有,你可以听,这样你就可以ended
解析当事件触发一个await
的Promise
事件:
const audios = [undefined, dot, dash];
async function playMorseArr(morseArr) {
for (let i = 0; i < morseArr.length; i++) {
const item = morseArr[i];
await new Promise((resolve) => {
if (item === 0) {
// insert desired number of milliseconds to pause here
setTimeout(resolve, 250);
} else {
audios[item].onended = resolve;
audios[item].play();
}
});
}
}
我将使用递归的方法,将监听音频ended事件。所以,每一次当前播放的音频停止,该方法被再次调用播放下一个。
function playMorseArr(morseArr, idx)
{
// Finish condition.
if (idx >= morseArr.length)
return;
let next = function() {playMorseArr(morseArr, idx + 1)};
if (morseArr[idx] === 1) {
dot.onended = next;
dot.play();
}
else if (morseArr[idx] === 2) {
dash.onended = next;
dash.play();
}
else {
setTimeout(next, 250);
}
}
您可以初始化调用playMorseArr()
与阵列和开始索引的过程:
playMorseArr([1, 1, 1, 0, 2, 2, 2, 0, 1, 1, 1], 0);
测试示例(从Kaiido的答案使用虚拟mp3
文件)
let [dot, dash] = [
new Audio('https://dl.dropboxusercontent.com/s/1cdwpm3gca9mlo0/kick.mp3'),
new Audio('https://dl.dropboxusercontent.com/s/h2j6vm17r07jf03/snare.mp3')
];
function playMorseArr(morseArr, idx)
{
// Finish condition.
if (idx >= morseArr.length)
return;
let next = function() {playMorseArr(morseArr, idx + 1)};
if (morseArr[idx] === 1) {
dot.onended = next;
dot.play();
}
else if (morseArr[idx] === 2) {
dash.onended = next;
dash.play();
}
else {
setTimeout(next, 250);
}
}
playMorseArr([1,1,1,0,2,2,2,0,1,1,1], 0);
async
& await
尽管它们用于异步操作它们可以用于同步任务为好。你做了承诺为每个功能,在async function
包住它们,然后在时间await
一个给他们打电话。以下是async function
作为演示一个名为函数的文档中,一个在实际演示是一个箭头的功能,但无论哪种方式,他们是在同一个:
/** * async function sequencer(seq, t) * * @param {Array} seq - An array of 0s, 1s, and 2s. Pause. Dot, and Dash respectively. * @param {Number} t - Number representing the rate in ms. */
注意:如果堆栈摘录不工作,审查Plunker
<!DOCTYPE html>
<html>
<head>
<style>
html,
body {
font: 400 16px/1.5 Consolas;
}
fieldset {
max-width: fit-content;
}
button {
font-size: 18px;
vertical-align: middle;
}
#time {
display: inline-block;
width: 6ch;
font: inherit;
vertical-align: middle;
text-align: center;
}
#morse {
display: inline-block;
width: 30ch;
margin-top: 0px;
font: inherit;
text-align: center;
}
[name=response] {
position: relative;
left: 9999px;
}
</style>
</head>
<body>
<form id='main' action='' method='post' target='response'>
<fieldset>
<legend>Morse Code</legend>
<label>Rate:
<input id='time' type='number' min='300' max='1000' pattern='[2-9][0-9]{2,3}' required value='350'>ms
</label>
<button type='submit'>
🔘➖
</button>
<br>
<label><small>0-Pause, 1-Dot, 2-Dash (no delimiters)</small></label>
<br>
<input id='morse' type='number' min='0' pattern='[012]+' required value='111000222000111'>
</fieldset>
</form>
<iframe name='response'></iframe>
<script>
const dot = new Audio(`https://od.lk/s/NzlfOTYzMDgzN18/dot.mp3`);
const dash = new Audio(`https://od.lk/s/NzlfOTYzMDgzNl8/dash.mp3`);
const sequencer = async(array, FW = 350) => {
const pause = () => {
return new Promise(resolve => {
setTimeout(() => resolve(dot.pause(), dash.pause()), FW);
});
}
const playDot = () => {
return new Promise(resolve => {
setTimeout(() => resolve(dot.play()), FW);
});
}
const playDash = () => {
return new Promise(resolve => {
setTimeout(() => resolve(dash.play()), FW + 100);
});
}
for (let seq of array) {
if (seq === 0) {
await pause();
}
if (seq === 1) {
await playDot();
}
if (seq === 2) {
await playDash();
}
}
}
const main = document.forms[0];
const ui = main.elements;
main.addEventListener('submit', e => {
let t = ui.time.valueAsNumber;
let m = ui.morse.value;
let seq = m.split('').map(num => Number(num));
sequencer(seq, t);
});
</script>
</body>
</html>