javascript 提供不同格式的音频文件
Offer Audio file in different formats with javascript
我正在使用以下代码播放声音文件:
var audio = new Audio();
audio.src = 'somePath/filename.ogg';
audio.volume = 10;
audio.autoPlay = false;
audio.preLoad = true;
// ...
audio.play();
而且效果很好。但是,有些浏览器可能不支持 ogg 格式,所以我也想添加 mp3 格式作为替代。我如何使用 javascript 来做到这一点?
供参考,当您提供多种格式时,这就是纯 HTML5 的样子:
<audio volume="10" preload="auto">
<source src="filename.ogg" type="audio/ogg">
<source src="filename.mp3" type="audio/mpeg">
</audio>
所以,基本上我不需要设置 audio.src
,而是需要向 Audio
对象添加 <source>
元素。我该怎么做呢? javascript 中是否有类似 new Source()
的东西我需要在这里使用,我可以以某种方式添加到 audio
?
额外问题:如果浏览器支持 none 提供的源格式,我能否以某种方式执行一些自定义代码,比如向用户打印一条消息,说他们的浏览器很糟糕? :)
也许不完全是您的想法,但是您可以通过 DOM API?
// Create audio instance with different source times by means of the DOM API
function createAudio(sourceData) {
const audio = document.createElement('audio')
// audio.preload = 'auto', Redundant as source children are dynamically created
audio.volume = 10
audio.style.display = 'none'
// Iterate each sourceInfo of input sourceData array
for(var sourceInfo of sourceData) {
const source = document.createElement('source')
source.src = sourceInfo.src
source.type = sourceInfo.type
// Append each source to audio instance
audio.appendChild(source)
}
document.appendChild(audio)
// Update, forgot this - thanks @Kaiido!
audio.load()
return audio
}
// Usage
createAudio([
{ src : 'filename.ogg', type : 'audio/ogg' },
{ src : 'filename.mp3', type : 'audio/mpeg' },
])
我正在使用以下代码播放声音文件:
var audio = new Audio();
audio.src = 'somePath/filename.ogg';
audio.volume = 10;
audio.autoPlay = false;
audio.preLoad = true;
// ...
audio.play();
而且效果很好。但是,有些浏览器可能不支持 ogg 格式,所以我也想添加 mp3 格式作为替代。我如何使用 javascript 来做到这一点?
供参考,当您提供多种格式时,这就是纯 HTML5 的样子:
<audio volume="10" preload="auto">
<source src="filename.ogg" type="audio/ogg">
<source src="filename.mp3" type="audio/mpeg">
</audio>
所以,基本上我不需要设置 audio.src
,而是需要向 Audio
对象添加 <source>
元素。我该怎么做呢? javascript 中是否有类似 new Source()
的东西我需要在这里使用,我可以以某种方式添加到 audio
?
额外问题:如果浏览器支持 none 提供的源格式,我能否以某种方式执行一些自定义代码,比如向用户打印一条消息,说他们的浏览器很糟糕? :)
也许不完全是您的想法,但是您可以通过 DOM API?
// Create audio instance with different source times by means of the DOM API
function createAudio(sourceData) {
const audio = document.createElement('audio')
// audio.preload = 'auto', Redundant as source children are dynamically created
audio.volume = 10
audio.style.display = 'none'
// Iterate each sourceInfo of input sourceData array
for(var sourceInfo of sourceData) {
const source = document.createElement('source')
source.src = sourceInfo.src
source.type = sourceInfo.type
// Append each source to audio instance
audio.appendChild(source)
}
document.appendChild(audio)
// Update, forgot this - thanks @Kaiido!
audio.load()
return audio
}
// Usage
createAudio([
{ src : 'filename.ogg', type : 'audio/ogg' },
{ src : 'filename.mp3', type : 'audio/mpeg' },
])