最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to have fade inout on audio HTML5 - Stack Overflow

programmeradmin1浏览0评论

I am creating a simple background music which has only one button to play and stop the music. But I would like to add fade to it. But does not work.

My code:

var beepTwo = $("#musicBeat")[0];
beepTwo.play();



$("#dan").click(function() {
  if (beepTwo.paused == false) {
      beepTwo.pause();

  } else {
      beepTwo.play();
  }
});


$beepTwo.animate({volume: newVolume}, 1000);

JSFiddle

I found $audio.animate({volume: newVolume}, 1000);in another post but does not work for me or maybe I didnt use it correctly. Anyway I want to have a fade in and fade out when the button is pressed. So it plays with fadeIn and stops with fadeOut. How can I do that?

I am creating a simple background music which has only one button to play and stop the music. But I would like to add fade to it. But does not work.

My code:

var beepTwo = $("#musicBeat")[0];
beepTwo.play();



$("#dan").click(function() {
  if (beepTwo.paused == false) {
      beepTwo.pause();

  } else {
      beepTwo.play();
  }
});


$beepTwo.animate({volume: newVolume}, 1000);

JSFiddle

I found $audio.animate({volume: newVolume}, 1000);in another post but does not work for me or maybe I didnt use it correctly. Anyway I want to have a fade in and fade out when the button is pressed. So it plays with fadeIn and stops with fadeOut. How can I do that?

Share Improve this question asked Feb 6, 2014 at 18:50 DanielDaniel 814 silver badges13 bronze badges 1
  • 1 you have to set a value in newVolume, and the logic is incorrect. – clouddreams Commented Feb 6, 2014 at 19:00
Add a ment  | 

1 Answer 1

Reset to default 5

You have to watch out for the difference between the HTMLAudioElement ($('#musicBeat')[0]) and the jQuery Object ($('#musicBeat')).

play is a method of the HTMLAudioElement, so you'll have to access it over that (as you did), but .animate is a jQuery method and can only be called on a jQuery object.

And you have to specify newVolume (can't leave it empty).

var beepTwo = $("#musicBeat");
beepTwo[0].play();

$("#dan").click(function() {  
    if (beepTwo[0].paused == false) {
        beepTwo.animate({volume: 0}, 2000, 'swing', function() {
            // really stop the music 
            beepTwo[0].pause();   
        });
     } else {
         beepTwo[0].play();  
         beepTwo.animate({volume: 1}, 2000);
     }
});
发布评论

评论列表(0)

  1. 暂无评论