AudioContext on Safari

AudioContext on Safari

本文关键字:Safari on AudioContext      更新时间:2023-09-26

昨天,我有一个关于AudioContext对象的noteOn方法的问题。我现在已经在这个AudioContext对象上扭转了局面。以下是我在桌面上的Safari中尝试的内容及其相关的错误消息:

	var ctx
//	ctx = new(AudioContext || webkitAudioContext); // ReferenceError: Can't find variable: AudioContext
//	ctx = new(audioContext || webkitAudioContext); // ReferenceError: Can't find variable: audioContext
//	ctx = new(window.AudioContext || webkitAudioContext); // ReferenceError: Can't find variable: webkitAudioContext
	ctx = new(window.AudioContext || window.webkitAudioContext);
// TypeError: 'undefined' is not a constructor (evaluating 'new(window.AudioContext || window.webkitAudioContext)')

Q: 如何定义myAudioContext,使其适用于所有浏览器?

浏览器支持限制

并非所有浏览器都支持Web Audio API(id est AudioContext)。有些浏览器可能会以供应商前缀作为前缀,但较旧的浏览器根本不支持它。因此,为了回答您的问题:您不能在所有浏览器上使用AudioContext

无ethless,您仍然可以使用Web Audio API在支持的浏览器上使用功能检测(见下文),或者只需检查浏览器是否支持它此处。看看你的Safari版本:这个网站告诉你该功能是否可用,如果有前缀,你必须使用哪个前缀。

AudioContext特征检测

为了确保您可以在支持的任何浏览器上使用Web Audio API,您可以使用与vendor-prefixed对象相对回退的功能检测。如果不支持AudioContext对象,您将停止脚本的执行并提醒用户。这里有一个例子:

var AudioContext = window.AudioContext // Default
    || window.webkitAudioContext // Safari and old versions of Chrome
    || false; 
if (AudioContext) {
    // Do whatever you want using the Web Audio API
    var ctx = new AudioContext;
    // ...
} else {
    // Web Audio API is not supported
    // Alert the user
    alert("Sorry, but the Web Audio API is not supported by your browser. Please, consider upgrading to the latest version or downloading Google Chrome or Mozilla Firefox");
}

请注意,到目前为止,webkit是唯一一个现有的vendor-prefixed AudioContext,因为Mozilla和Opera使用常规的非固定对象,而IE还不支持Web Audio API

  var AudioContext = window.AudioContext // Default
      || (window as any).webkitAudioContext;// Safari and old versions of Chrome
    this.audioContext = new AudioContext();