I need some help to add few audio effects to website.

I found some examples like following,

audioOn: true

audio.muted = false

setAudioOn true    

 ref: "audio",
    attrs: {
      "id": "projects-audio"
    }
  }, [_c('source', {
    attrs: {
      "src": "/audio/click.mp3"
    }

     playAudio: function playAudio() {
        this.$parent.$refs.clickAudio.volume = 0.8;
        this.$parent.$refs.clickAudio.play();
    },

I need help to play audio using play() , control volume using volume = 1

What is workClick: ? I found it used with sound properties.

So, basic needs are play various sounds - on click, background music, control volume of background music, play sound on overlay appears

Recommended Answers

All 12 Replies

I found websites little similar with - what I'm trying to do.

offfitalia
20thcenturywomen

Background music
Sound on hover
volume indicator on/off (animated sound control bars)

Both have used greensock

Can anybody help me with using greensock?

Greensock si for animations and has nothing to do with audio. For the rest what rproffitt said.

easyaudioeffects.js is a jQuery plugin for adding sound effects (ogg and mp3) to any html elements that supports custom trigger events and play types.

How to use it:

1. Put jQuery library and the jQuery easyaudioeffects.js script at the bottom of your webpage.

1
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
2
<script src="jquery.easyaudioeffects.1.0.0.js"></script>
2. Call the plugin on the target element and specify the paths to the audio files.

1
$('.button').easyAudioEffects({
2
  ogg : "sound.ogg",
3
  mp3 : "sound.mp3"
4
});
3. By default, the plugin will play the sound effect on hover. You can config the plugin to play the sound effect on click by passing the 'eventType' option during initialization.

1
$('.button').easyAudioEffects({
2
  ogg : "sound.ogg",
3
  mp3 : "sound.mp3",
4
  eventType : 'click',
5
});
4. Change the play type to others.

view source
1
$('.button').easyAudioEffects({
2
  ogg : "sound.ogg",
3
  mp3 : "sound.mp3",
4
  eventType : 'click', // [ hover / click ]
5
  playType : "gate", // [ oneShotPolyphonic / oneShotMonophonic / gate / loop ]
6
});
});

Hope this will help to add a music file in your website.

I'm working on 2-3 theme ideas , for which I need to control volume of background. I need to keep it low. One theme is mystic, for second theme I'm using music Love In the Park , working on third theme .

I'm using different sound effects for each theme along with different background music. To make sound effects effective background music must be in low volume.

I found some websites controlling background music volume & all are using greensock. All are using function to get audio file, control volume of background music, call audio of different action e.g. hover. May be some library they are using but I'm unable to find which one is.

Following is part of script from offfitalia
(you can check app.js)

Start of function

! function(e, n) {
    "use strict";
    var r = e.GreenSockGlobals = e.GreenSockGlobals || e;

Audio control part

 e.Common = function() {
        function t() {
            (0, o.default)(this, t), this.loader = new h.Loader("loader"), this.loaderInternal = new f.LoaderInternal("loader-internal"), this.videoTriggerSelector = "data-video-trigger", this.handleModal(), this.videoResize = this.videoResize.bind(this), this.handleVideoModal(), this.audioToggle = this.audioToggle.bind(this), this.isNotesReady = !1, !m.default.mqTo("desktop") && Modernizr.touchevents || (this.handleGlobalAudio(), this.handleNotes(), (0, d.default)({
                animationTime: 800,
                animationStep: 120,
                accelerationDelta: 50,
                accelerationMax: 1
            }))
        }
        return t.prototype.handleNotes = function() {
            var t = this;
            this.noteUrl = ["/assets/audio/Nota1.mp3", "/assets/audio/Nota2.mp3", "/assets/audio/Nota3.mp3", "/assets/audio/Nota4.mp3", "/assets/audio/Nota5.mp3", "/assets/audio/Nota6.mp3", "/assets/audio/Nota7.mp3", "/assets/audio/Nota8.mp3", "/assets/audio/Nota9.mp3", "/assets/audio/Nota10.mp3"], this.notesCount = this.noteUrl.length, this.notesPlayable = [], this.lastNoteIndex = -1;
            var e = 0;
            this.noteUrl.forEach(function(i) {
                var n = new Audio;
                n.src = i, n.addEventListener(m.default.events.CANPLAYTHROUGH, function() {
                    e++, t.notesPlayable.push(n), e === t.notesCount && (g.default.emit(m.default.events.NOTES_LOADED), t.isNotesReady = !0)
                })
            })
        }, t.prototype.handleGlobalAudio = function() {
            var t = this;
            this.audio = new Audio("/assets/audio/synthesizer.mp3"), this.audio.volume = .5, this.audio.loop = !0, this.assignCorrectIndicators(), this.audio.addEventListener(m.default.events.CANPLAYTHROUGH, function() {
                a.default.bind(document, "[data-volume-indicator]", m.default.events.CLICK, t.audioToggle), t.checkAudioAutoplay()
            })
        },

You can see volume is controlled in audio part like this.audio.volume = .5, also other things are managed with function.

Another example from unknown source ( :( I just have copy of script )
(parts of script are as follows)

audio source

module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
  return _c('div', {
    ref: "projectPage",
    staticClass: "projects-page"
  }, [_c('audio', {
    ref: "caseAudio",
    attrs: {
      "id": "projects-page__case-audio"
    }
  }, [_c('source', {
    attrs: {
      "src": "/static/audio/case-switch.mp3"
    }
  })]), _vm._v(" "), _c('audio', {
    ref: "audio",
    attrs: {
      "id": "projects-page__audio"
    }
  }, [_c('source', {
    attrs: {
      "src": "/static/audio/hover.mp3"
    }
  })]), _vm._v(" "), _c('audio', {
    ref: "clickAudio",
    attrs: {
      "id": "projects-page__click-audio"
    }
  }, [_c('source', {
    attrs: {
      "src": "/static/audio/click-main-page.mp3"
    }
  })])

play audio

 playAudio: function playAudio() {
            if (this.audioOn) {
                this.$refs.clickAudio.play();
            }
        }

toggle audio

toggleSound: function toggleSound() {
            if (this.soundOn === false && this.clickedDetail === false && this.hasMotion === true) {
                this.soundOn = true;

                if (this.audioOn === true) {
                    this.$refs.audio.play();
                }
            } else {
                this.soundOn = false;

                if (this.audioOn === true) {
                    this.$refs.audio.pause();
                    this.$refs.audio.currentTime = 0;
                }
            }
        }

audio volume

this.$refs.audio.volume = 0.8;
this.$refs.audio.play();

I'm looking for something like in second example.

Following is my script (need some help to make it like second example)

var audiotypes = {
    "mp3": "audio/mpeg",
    "mp4": "audio/mp4",
    "ogg": "audio/ogg",
    "wav": "audio/wav"
}

function audio(sound) {
    var audio_element = document.createElement('audio')
    if (audio_element.canPlayType) {
        for (var i = 0; i < arguments.length; i++) {
            var source_element = document.createElement('source')
            source_element.setAttribute('src', arguments[i])
            if (arguments[i].match(/\.(\w+)$/i))
                source_element.setAttribute('type', audiotypes[RegExp.$1])
            audio_element.appendChild(source_element)
        }
        audio_element.load()
        audio_element.playclip = function() {
            audio_element.pause()
            audio_element.currentTime = 0
            audio_element.play()
        }
        return audio_element
    }
}

var playAudio = audio('audio/wav/InThePark.wav', "audio/mp3/InThePark.mp3");

playAudio.playclip();

I revived your post but I still don't see any need for those libraries. HTML5 and Javascript seem to do what you ask.

Your revived post is full of code and such but you need to really nail what the problem is. That is, call out what line of code fails, what the error message is and really reduce it to the smallest possible example. I doubt anyone will install Greensock just to try it out. Maybe but I would not count on it.

Read "Composing a good question" at https://www.daniweb.com/programming/threads/435023/read-this-before-posting-a-question

@All Thanks

As I said I'm working on themes, where I need to use low volume of background music. So I want to control Volume, Play/Stop of background music. (HTML Audio/Video DOM volume Property)

Also I'm adding some sound effects to actions - click, hover as well as appearing/diappearing of overlay. I’ve added my working code(at the end) in my last post. It works, but I need something more, like website examples I provided in my posts.

No need to install Greensock, just try my code in my last post

I'm explaining my goals

Need to create following functions

1. soundOn= (if true play all sounds when they are called,  if false no background music, no sond effects on events/actions)
     Purpose:-  all sound effects on website to play or not. 

2. var audiotypes = { }
    Purpose:-  Code to define  valid audio file type to be played

3. function playAudio() {  }
    Purpose:-  code to play all audio files, it may called as,  
    var sound1 = playAudio({
        if (audioOn) {
            src: ["src/sound1.wav", "src/sound1.mp3"],
            volume: 0.5
           } 
    });

4. function toggleSound() { }
    Purpose:- play, stop all audio (A universal mute/unmute button)

These are some basic requirements

Four Point Summary

1. soundOn = true/false

2. var audiotypes = { }

3. var sound1 = playAudio({
            if (audioOn) {
                    src: ["src/sound1.wav", "src/sound1.mp3"],
                    volume: 0.5
            }  
     });

4. function toggleSound() { }

Hope I’ve cleared goals or points, I'm trying to work on.

It appears as if you want folk to write your code and functions. That's pretty rare. But on topic about your new item 1, it can be simple or complicated.

Simple: Mute all playing items. Too many examples at https://www.google.com/search?q=HTML5+MUTE+SOUND+BUTTON

I worry here you are asking everyone to code this for you. This is usually done with you go with a For Hire type post with a well done RFQ and a price. If you are asking for code, that usually ends badly. Almost all members are to help you learn or to help you past a bad bug. Since muting and such in HTML5 is rather well done I worry you just want code.

Thanks

My Code

var audiotypes = {
    "mp3": "audio/mpeg",
    "mp4": "audio/mp4",
    "ogg": "audio/ogg",
    "wav": "audio/wav"
}

function audio(sound) {
    var audio_element = document.createElement('audio')
    if (audio_element.canPlayType) {
        for (var i = 0; i < arguments.length; i++) {
            var source_element = document.createElement('source')
            source_element.setAttribute('src', arguments[i])
            if (arguments[i].match(/\.(\w+)$/i))
                source_element.setAttribute('type', audiotypes[RegExp.$1])
            audio_element.appendChild(source_element)
        }
        audio_element.load()
        audio_element.playclip = function() {
            audio_element.pause()
            audio_element.currentTime = 0
            audio_element.play()
        }
        return audio_element
    }
}

var playAudio = audio('audio/wav/InThePark.wav', "audio/mp3/InThePark.mp3");

playAudio.playclip();

Working Example

You can here sound when page is loaded. It can be used for actions like click, hover.

jsfiddle adele hello

I'm not asking to write whole code for me. I need help to modify my code. I want to add some more functionalities to my code.
I'm trying something like following.

1. soundOn = true/false
2. var audiotypes = {
        "mp3": "audio/mpeg",
        "mp4": "audio/mp4",
        "ogg": "audio/ogg",
        "wav": "audio/wav"  
    }
3. var sounds = {
      "sound1" : {
        url : "audio/sound1.wav"
      },
      "sound2" : {
        url : "audio/sound2.mp3",
      },
      "sound3" : {
        url : "audio/sound3.ogg"
      },
      "sound4" : {
        url : "audio/sound4.mp4"
      }
    };
4. function loadSound(name){
    //code to initialize sound with name and url
        var sound = //name
        var url = //url

    }
5.  function playAudio(name, options) { 
        var sound = //name
        var soundVolume = //volume

        //code to check soundOn is true
    }
6. function toggleSound() {
    //stop all playing sound and reset them to start position
    //Or Enable all sounds to play  
    //Set soundOn = true/false
    }

7. To play a sound, Call function as follows,

    playAudio("sound1");

        OR

    playAudio("sound1", { volume: .5 });

From Web_Audio_API docs I found that audio can be processed in other way(than I created function), but don't know how to use it -

soundContext.createBufferSource();
soundContext.createGain();
volume.connect(soundContext.destination);
source.connect(volume);

Any help would be greatly appreciated.

With the help of colleague & css-tricks I ended up with following code with some problems.

index.php

<p>Sound Link:- http://soundbible.com/mp3/cartoon-birds-2_daniel-simion.mp3</p>
<a href="#" class="birds">Cartoon Birds</a>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="main.js"></script>

script.js

var src = {
  "birds" : {
    url : "audio/cartoon-birds-2_daniel-simion.mp3"
  } 
};

var soundContext = new AudioContext();

for(var key in src) {
  loadSound(key);
}

function loadSound(name){
    "use strict";
  var sound = src[name];

  var url = sound.url;
  var buffer = sound.buffer;

  var request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.responseType = 'arraybuffer';

  request.onload = function() {
    soundContext.decodeAudioData(request.response, function(newBuffer) {
      sound.buffer = newBuffer;
    });
  };

  request.send();
}

function playAudio(name, options){
    "use strict";
  var sound = src[name];
  var soundVolume = src[name].volume || 1;

  var buffer = sound.buffer;
  if(buffer){
    var source = soundContext.createBufferSource();
    source.buffer = buffer;

    var volume = soundContext.createGain();

    if(options) {
      if(options.volume) {
        volume.gain.value = soundVolume * options.volume;
      }
    } else {
      volume.gain.value = soundVolume;
    }

    volume.connect(soundContext.destination);
    source.connect(volume);
    source.start(0);
  }
}    

main.js

jQuery(document).ready(function($) {
 "use strict";

playAudio("birds"); 

$('a.birds').on('click', function(e) {
  e.preventDefault();
  playAudio("birds", { volume: .5});
});

})(jQuery);

This code is working well for me. Have some issues. See below

  1. struggling with soundOn = true/false checking
  2. struggling with function toggleSound() { } (universal mute/unmute button)
  3. struggling with adding var audiotypes = { }
  4. code for .on('click',function(e) { }); is working well, but for jQuery(document).ready(function($) { playAudio("birds"); })(jQuery); is playing sound only once when window is opened, it does not plays any sound on page refresh.
  5. play any sound only if soundOn = true
  6. struggling with play sound on pageload, page refresh, click, hover

Thanks in advance

Please help

I'm still working on little issues. Following is updated code.

index.php

<p>Sound Link:- http://soundbible.com/mp3/cartoon-birds-2_daniel-simion.mp3</p>
<a href="#" class="birds">Cartoon Birds</a>
<br />
<h4><a href="#" class="ToggleMute">Toggle Mute</a></h4>

main.js

jQuery(document).ready(function($) {
    "use strict";

    var audioOn = true;

    function toggleSound() {
        if (audioOn) {
            audioOn = false;
        } else {
            audioOn = true;
        }
    }

    if (audioOn === true) {
        playAudio("birds");
    }

    $('a.birds').on('click', function(e) {
        e.preventDefault();

        if (audioOn === true) {
            playAudio("birds", {
                volume: .8
            });
        }
    });

    $('a.ToggleMute').on('click', function(event) {
        event.preventDefault();
        toggleSound();
    });

})(jQuery);

I’ve updated code and added toggleSound() function, audioOn = true condition check added. It is working, but it does not stops sound if it is playing. It only checks before playing any sound, is, audioOn = true or false.

Also code does not work on page refresh, it does not play any sound on page refresh

  1. Need help to update code so it can stops any playing sound.
  2. Need help to paly sound on pageload & page refresh
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.