【发布时间】:2017-08-24 21:17:15
【问题描述】:
我正在尝试将我发现用 Java 编写的一些(非常简单的)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 to produce the sound from the bytes,但这是否允许我控制此处的其他信息(即采样率等)?换句话说:在 JS 中最简单、最准确的方法是什么?
更新
我一直在尝试复制我在this answer 中找到的内容。这是我的代码的相关部分:
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, uncompressed)中运行了几行,通过行5208、5195、5191、5219、5223,最后是 5015,然后再出错。我不知道为什么 jQuery 与它有任何关系,并且该错误让我不知道该尝试什么。有什么想法吗?
【问题讨论】:
-
更新:我尝试在这个解决方案中工作stackoverflow.com/questions/24151121/…,但我得到了
Uncaught (in promise) DOMException: Unable to decode audio data,我真的不了解将字节转换为声音的基础知识以了解原因 -
我想你可能正在寻找网络音频 api
[AudioBuffer](developer.mozilla.org/en-US/docs/Web/API/AudioBuffer)。我没有足够的经验来提供完整的答案,但我想我会发表评论以防万一。 -
应该
var buffer = new Uint8Array( bytes.length )是var buffer = new ArrayBuffer( bytes.length )吗?为什么需要Uint8Array?bytes是什么?
标签: javascript java android html audio