Javascript HTML5 <audio> 播放淡入淡出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7451508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML5 <audio> playback with fade in and fade out
提问by Mikko Ohtamaa
I'd like to start and stop HTML5 playback in a random position with fade in and fade out periods to smooth the listening experience.
我想在随机位置开始和停止 HTML5 播放,并带有淡入和淡出周期,以平滑收听体验。
What kind of mechanisms exists for this? Manually ramp up the volume with setTimeout()?
为此存在什么样的机制?使用 setTimeout() 手动增大音量?
回答by jedmao
The jQuery way...
jQuery的方式...
$audio.animate({volume: newVolume}, 1000);
Edit: where $audio is a jQuery-wrapped audio element and newVolume is a double between 0 and 1.
编辑:其中 $audio 是一个 jQuery 包装的音频元素,而 newVolume 是一个介于 0 和 1 之间的双精度值。
Edit: The element's effective media volume is volume, interpreted relative to the range 0.0 to 1.0, with 0.0 being silent, and 1.0 being the loudest setting, values in between increasing in loudness. The range need not be linear. http://www.w3.org/html/wg/drafts/html/master/embedded-content.html#effective-media-volume
编辑:元素的有效媒体音量是音量,相对于 0.0 到 1.0 的范围进行解释,0.0 表示静音,1.0 表示最响亮的设置,介于两者之间的值随着响度的增加而增加。范围不必是线性的。http://www.w3.org/html/wg/drafts/html/master/embedded-content.html#effective-media-volume
Edit: People are posting vanilla JavaScript implementations, so I'll post a vanilla TypeScript one that preserves the jQuery swing animation (just strip out the type info if you want to run this in JavaScript). Disclaimer, this is completely untested:
编辑:人们正在发布普通的 JavaScript 实现,所以我将发布一个保留 jQuery 摆动动画的普通 TypeScript(如果你想在 JavaScript 中运行它,只需去掉类型信息)。免责声明,这是完全未经测试的:
export async function adjustVolume(
element: HTMLMediaElement,
newVolume: number,
{
duration = 1000,
easing = swing,
interval = 13,
}: {
duration?: number,
easing?: typeof swing,
interval?: number,
} = {},
) {
const originalVolume = element.volume;
const delta = newVolume - originalVolume;
if (!delta || !duration || !easing || !interval) {
element.volume = newVolume;
return Promise.resolve();
}
const ticks = Math.floor(duration / interval);
let tick = 1;
return new Promise<void>((resolve) => {
const timer = setInterval(() => {
element.volume = originalVolume + (
easing(tick / ticks) * delta
);
if (++tick === ticks) {
clearInterval(timer);
resolve();
}
}, interval);
});
}
export function swing(p: number) {
return 0.5 - Math.cos(p * Math.PI) / 2;
}
回答by user801985
Old question but if anyone is looking for a vanilla JS way to do this I just wrote something up for project and thought I'd post it here since my search for a solution was in vain. If you are already working with a video or audio element, there's a good chance you don't really need to use jQuery to control the object anyways.
老问题,但如果有人正在寻找一种香草 JS 方法来做到这一点,我只是为项目写了一些东西,并认为我会在这里发布它,因为我对解决方案的搜索是徒劳的。如果您已经在处理视频或音频元素,那么您很有可能实际上并不需要使用 jQuery 来控制对象。
function getSoundAndFadeAudio (audiosnippetId) {
var sound = document.getElementById(audiosnippetId);
// Set the point in playback that fadeout begins. This is for a 2 second fade out.
var fadePoint = sound.duration - 2;
var fadeAudio = setInterval(function () {
// Only fade if past the fade out point or not at zero already
if ((sound.currentTime >= fadePoint) && (sound.volume != 0.0)) {
sound.volume -= 0.1;
}
// When volume at zero stop all the intervalling
if (sound.volume === 0.0) {
clearInterval(fadeAudio);
}
}, 200);
}
This version doesn't allow for editing the fadeout time (set to 2 seconds) but you could pretty easily argumentize it. To fully generisize this, extra logic would be needed to also first check what the volume was set to in order to know the factor by which to fade it out. In our case, we preset the volume to 1 already and browser volume control is out of the users hands as it's for a slideshow thing so it wasn't needed.
此版本不允许编辑淡出时间(设置为 2 秒),但您可以很容易地对其进行论证。为了完全通用,还需要额外的逻辑来首先检查音量设置为什么,以便知道淡出它的因素。在我们的例子中,我们已经将音量预设为 1,并且浏览器音量控制不在用户手中,因为它用于幻灯片放映,因此不需要它。
To get to a specific part of the audio you'd want to check the seekable timerange and just set the currentTime randomly based on what's available.
要访问音频的特定部分,您需要检查可搜索的时间范围,并根据可用内容随机设置 currentTime。
回答by Mikko Ohtamaa
I created a simple lib for this using setTimeout().
我使用 setTimeout() 为此创建了一个简单的库。
Source code is available here:
源代码可在此处获得:
https://github.com/miohtama/Krusovice/blob/master/src/tools/fade.js
https://github.com/miohtama/Krusovice/blob/master/src/tools/fade.js
回答by user3126867
Here are a couple of functions to fade-out current song and fade-in new song.
这里有几个功能可以淡出当前歌曲和淡入新歌曲。
HTML:
HTML:
<audio loop autoplay="1" onPlay="audioVolumeIn(this);"><br>
<source src="/test/new/imgs/audio_bg.ogg" type="audio/ogg; codecs=vorbis"><br>
<source src="/test/new/imgs/audio_bg.wav" type="audio/wav"><br>
<source src="/test/new/imgs/audio_bg.mp3" type="audio/mpeg"><br>
Javascript:
Javascript:
function audioVolumeIn(q){
if(q.volume){
var InT = 0;
var setVolume = 0.2; // Target volume level for new song
var speed = 0.005; // Rate of increase
q.volume = InT;
var eAudio = setInterval(function(){
InT += speed;
q.volume = InT.toFixed(1);
if(InT.toFixed(1) >= setVolume){
clearInterval(eAudio);
//alert('clearInterval eAudio'+ InT.toFixed(1));
};
},50);
};
};
function audioVolumeOut(q){
if(q.volume){
var InT = 0.4;
var setVolume = 0; // Target volume level for old song
var speed = 0.005; // Rate of volume decrease
q.volume = InT;
var fAudio = setInterval(function(){
InT -= speed;
q.volume = InT.toFixed(1);
if(InT.toFixed(1) <= setVolume){
clearInterval(fAudio);
//alert('clearInterval fAudio'+ InT.toFixed(1));
};
},50);
};
};
回答by jibbon
This is a simple timeout function for fading the audio (from 0 to 100 in this case). It uses a global variable. Still struggling with a whole package though. I'll definitely be checking out sfjedi's jQuery way.
这是一个用于淡入淡出音频的简单超时函数(在本例中为 0 到 100)。它使用全局变量。尽管如此,仍然在为整个包裹而苦苦挣扎。我肯定会检查 sfjedi 的 jQuery 方式。
function FadeIn() {
var sound = document.getElementById('audiosnippet');
var vol = $.global.volume;
if ( vol < 100 )
{
sound.volume = (vol / 100);
$.global.volume = $.global.volume + 10;
setInterval(function() { FadeIn() }, 1200);
}
}
}