我正在尝试将一些(非常简单的)Android代码重写为静态HTML5应用程序(我不需要服务器来执行任何操作,我想保持这种方式)。我具有丰富的Web开发背景,但对Java和Android开发的基本理解甚至更少。
该应用程序的唯一功能是获取一些数字并将它们转换为字节的音频鸣叫声。我完全没有问题将数学逻辑转换为JS。我的问题在于实际生成声音时遇到了困难。以下是原始代码的相关部分:
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
// later in the code:
AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, minBufferSize, AudioTrack.MODE_STATIC);
// some math, and then:
track.write(sound, 0, sound.length); // sound is an array of bytes
我该如何在JS中实现这个?我可以使用dataURI从字节中产生声音,但是那是否允许我控制此处的其他信息(例如采样率等)?换句话说:在JS中最简单、最准确的方法是什么?
更新
我一直在尝试复制我在这个答案中找到的内容。 这是我代码的相关部分:
window.onload = init;
var context; // Audio context
var buf; // Audio buffer
function init() {
if (!window.AudioContext) {
if (!window.webkitAudioContext) {
alert("Your browser does not support any AudioContext and cannot play back this audio.");
return;
}
window.AudioContext = window.webkitAudioContext;
}
context = new AudioContext();
}
function playByteArray( bytes ) {
var buffer = new Uint8Array( bytes.length );
buffer.set( new Uint8Array(bytes), 0 );
context.decodeAudioData(buffer.buffer, play);
}
function play( audioBuffer ) {
var source = context.createBufferSource();
source.buffer = audioBuffer;
source.connect( context.destination );
source.start(0);
}
然而,当我运行这个程序时,出现了以下错误:
Uncaught (in promise) DOMException: Unable to decode audio data
我发现这很不寻常,因为它是如此的普遍错误,以至于完全不知道哪里出了问题。更让人惊讶的是,当我逐步调试时,尽管错误链开始于(预料之中的)context.decodeAudioData(buffer.buffer, play);
这一行,但它实际上还会在jQuery文件(3.2.1未压缩版)中经过几行代码(具体是5208、5195、5191、5219、5223和最后一个是5015)才导致错误。 我不知道为什么jQuery会有任何关系,并且错误信息也没有给我任何提示。 有任何想法吗?
[AudioBuffer]
(https://developer.mozilla.org/en-US/docs/Web/API/AudioBuffer)。我对此没有足够的经验来提供完整的答案,但我想评论一下以防万一。 - aberkowvar buffer = new Uint8Array( bytes.length )
应该改为var buffer = new ArrayBuffer( bytes.length )
吗?为什么需要使用Uint8Array
?bytes
是什么? - guest271314