Coder Social home page Coder Social logo

jaysalvat / buzz Goto Github PK

View Code? Open in Web Editor NEW
1.2K 45.0 227.0 933 KB

Buzz is a small but powerful Javascript library that allows you to easily take advantage of the new HTML5 audio element. It tries to degrade silently on non-modern browsers.

Home Page: http://buzz.jaysalvat.com

License: MIT License

JavaScript 99.49% HTML 0.51%

buzz's Introduction

Buzz, a Javascript HTML5 Audio library

Buzz is a small but powerful Javascript library that allows you to easily take advantage of the new HTML5 audio element. It tries to degrade properly on non-modern browsers.

var mySound = new buzz.sound("/sounds/myfile", {
    formats: [ "ogg", "mp3", "aac" ]
});

mySound.play()
    .fadeIn()
    .loop()
    .bind("timeupdate", function () {
        document.querySelector("#timer").innerHTML = buzz.toTimer(this.getTime());
    });

Official website

http://buzz.jaysalvat.com/

Real life demo

http://buzz.jaysalvat.com/demo/

Documentation

http://buzz.jaysalvat.com/documentation/

Contributing

Please don't edit files in the dist subdirectory as it is generated via Grunt. You'll find source code in the src subdirectory! Regarding code style like indentation and whitespace, follow the conventions you see used in the source already.

PLEASE DO NOT use Gruntfile. I will. :)

License

The MIT License (MIT)

Copyright (c) 2021 Jay Salvat

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

buzz's People

Contributors

auchenberg avatar cha0s avatar dexteryy avatar florentchauveau avatar foolip avatar fusioneer-github avatar gido avatar jaysalvat avatar jeanphix avatar konsumer avatar lordjabez avatar micahscopes avatar peterdavehello avatar shennan avatar stephanebachelier avatar urcadox avatar victorjonsson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

buzz's Issues

Use bower.json for bower

When doing a bower install there appears a message:

bower warn Package buzz is still using the deprecated "component.json" file

Solution is to create a bower.json file.

loop doesn't work in chrome

loop works well in firefox latest, but not in chrome latest. In chrome, the music is just played once.

var mySound = new buzz.sound( "music", {
    formats: [ "mp3", "ogg" ],
    preload: true,
    autoplay: false,
    loop: true
});

mySound
    .setVolume( 0 )
    .fadeTo(25, 15000)
    .loop()
    .bind( "timeupdate", function() {
        var timer = buzz.toTimer( this.getTime() );
        document.getElementById( "timer" ).innerHTML = timer;
    });

Issue for a perfect Loop ?

Hi,

did you have a issue for a perfect loop ? ... currently on all navigator, my loop have little blank sound

Thanks,
Richard

component.json gone... why?

It was quite useful having a component.json within the repo. It's now been removed. Is there a good reason for this?

setTimeout not working for audio files in iOS simulator

Hi,
I have to play two sounds one after the other - the first sound plays on click event and the other should play after some time delay - using setTimeout function. I have included buzz.js file. The code that I have applied to play the sound files is as follows:

var gameSound = new buzz.sound('/demo/sounds/elephant');// dummy initialization
gameSound = new buzz.sound('sound_src_1');
var result = gameSound.play();
setTimeout(function () {
gameSound = new buzz.sound('sound_src_2');
var result = gameSound.play();
}, 2500); //delay of 2.5 seconds to play this sound

Also tried the following code:

var gameSound = new buzz.sound(sound_src_1);
var gameSound1 = new buzz.sound(sound_src_2);
var sgroup=new buzz.group([gameSound,gameSound1]);
sgroup.loop.play();
setTimeout(function(){
sgroup.unloop();
},5000);

The code works fine in Chrome and Firefox on Windows. But on iOS Simulator, only the first sound file 'sound_src_1' is played but the second sound doesn't play. Any suggestions for this?

Thank you

Browser support?

What browsers are supported? An overview in docu or so would be nice.

Update

Ok is clear! All who support the audio-tag.

Minified Version

Hello Jay,

I was wondering if you could try minifying the file and see if you get any errors. I tried it and my script started malfunctioning, perhaps due to a semicolon missing somewhere when minified.

Other than that, this library kicks ass.

Best

-Jafar

doesn't play() after stop()

Hi,

I'm adding sound to a box animation. When the animation finishes I am calling:

sound.stop()

However, when I try to play it again(

sound.play()

) after, I don't get any sound...

Can't play a sound after .load() or .stop() on Safari 5.1.7

Hello,

I define my sound as :

this.scoreCount = new buzz.sound([root+"compatge_points/snd_pg_score.mp3",root+"compatge_points/snd_pg_score.ogg"]);

When I use load(); and after play(); sound does not play on Safari.

When I only use only play() it works.

When I use stop() and after play() the sound does not play either.

Work perfectly on Firefox & Chrome !

Thank for the work

Regards

Problem in Firefox with setTime() and loading ogg audio files

Hi. I found an Issue with Firefox (tested Version 5.0 and 6.0.2 - NOT tested 7, yet)

https://github.com/jaysalvat/buzz/blob/master/buzz.js#L182
If you call setTime(), the code this.sound.currentTime = time; seems to trigger the whenReady() event in Firefox, so we have an endless loop resulting in 100% cpu usage and stuttering sound. This behavior happens, if the soundfile has not finished loading!

Testcase:
Clearcache and click "brakes in firefox" button in firefox and hear the sound or watch the taskmanager/activity monitor.
http://jsfiddle.net/yTQUR/

Ability to play a sound more than once at the same time?

Hey,

Is there any way to achieve this? At the moment I'm creating several times the same sound with different vars.

Also I'm not able to know if a sound is playing or not. I'm missing something?

Thanks for this awesome lib!

Stop loading

Im building an always on web app and when I call .stop() it's still rendering the stream(im using a radio stream) no matter what I do. Is there a way to stop streaming?

SetSpeed does not work

Hello,

I'm trying to use the SetSpeed() method, but it throws this error :

Object [object Object] has no method 'SetSpeed' 

Browsers : latest Firefox and latest Chome.
OS : linux

Thank you

Flash fallback?

I'm developing a web app that needs to work cross-browser. unfortunately this includes IE7 and IE8, which don't support the <audio> element.

Could you implement a flash fallback in buzz that maintains the full functionality and features that'll be automatically used if the user's browser does not support <audio>?

Thanks in advance.

Question: counting sounds in a group

Without having inspected the underlying code yet, is it possible to count the number of sounds in a group? I would like to do this for estimating / controlling preloading of all sounds, for example, the 'startload' event would fire X times if bound to a buzz group containing X sounds. but how do i know that a specific group contains X sounds?

Firefox for Mac not playing my sounds

Sound works on
Safari - Mac and Windows
Chrome - Mac and Windows
Internet Explorer - Windows
Ipads and Androids
Firefox - Windows, But not for mac... even if I add an ogg format only....!!

Any idea?

Thanks!!!

isEnded() broken?

The .isEnded-function seems to always return false. I can check the length of the sound (in my case 0.67 seconds) and check isEnded one second after playing it and it still returns false. I can't see the "ended"-property anywhere else except in this function:

 this.isEnded = function() {
            if ( !supported ) {return null;}

            return this.sound.ended;
        };

which I think is slightly odd? Maybe I'm being stupid?

"for ... in ..." statements

please consider not using "for ... in ..." statement to iterate over arrays. If Array prototype has been extended (e.g.: mootools), this statement fail...

You'd better do things like:

for (i = 0; i < array.length; i++){

}

Creating a buzz.sound throws a NotImplemented error

Hi,

I'm using IE10 on a Windows 2008R2 x64 server.

When I try to create a sound, I have a javascript error : Not Implemented.

The error is raised when the browser call "this.audio.preload = ...".

Edit : No audio card on the machine, windows service sound is disabled.

Play a song from a group

Hi, its possible to play a specific song from a group?

buzz.defaults.formats = [ 'ogg', 'mp3' ];
buzz.defaults.preload = 'metadata';

var myGroup = new buzz.group([
new buzz.sound("audio/song_1"),
new buzz.sound("audio/song_2"),
]);

myGroup[0].play() ?

Thanks!

[iOS] playing muliple audio files at the same time.

Hi,

Thank you for this great library.
I have made some tests on my iPhone. I would like to play 2 sounds at the same time. I used this code :

var mySound1 = new buzz.sound("1.mp3"),
    mySound2 = new buzz.sound("2.mp3");

var myGroup = new buzz.group([  
 mySound1, 
 mySound2
]); 

var myGroup = new buzz.group(mySound1, mySound2);   

$(document).ready(function() {

 $('#jouer').click(function() {
  myGroup.loop().play().fadeIn();
  return false;
}); 

$('#stop').click(function() {

  myGroup.stop();
  return false;
  });
});

Unfortunately, on iOS, i can only hear one song playing.

Is there any solutions for that ?

Thanks
David.

Implement "playAny" method

Feature: Play any sound of group

In order to keep sound logic in a single abstraction
As a library user
I want to play any random sound of a given group

Scenario: Successful playback
Given I have initialized a buzz group of gunshots
When I call playAny method of it
Then library starts playing any gunshot

How to "change audio src" properly ?

How to change audio src properly and how to init an empty buzz object ?

I have a player service, like this:

@railsmusic.factory 'player', ['$rootScope', ($rootScope) ->
  playlist = []
  sound = null

  player =
    playlist: playlist
    playing: false
    ready: false
    current: null
    duration: 0
    progress: 0
    progress_percent: 0

    load: () ->
      sound = new buzz.sound('/songs/' + player.current.id + player.current.file_ext)
      sound.load

    play: (song) ->
      player.pause() if player.playing

      if song?
        player.current = song
        player.load
      if not player.current?
        player.current = player.playlist[0]
        player.load

      sound.play
      player.playing = true

    pause: ->
      if player.playing
        sound.pause()
        player.playing = false

    stop: ->
      if player.playing
        sound.pause()
        player.playing = player.ready = false
        player.current = null
        player.duration = player.progress = player.progress_percent = 0

    next: ->
      return false if not playlist.length

      nextIndex = playlist.indexOf(player.current) + 1
      if nextIndex < playlist.length
        player.play(playlist[nextIndex])
      else
        false

    previous: ->
      return false if not playlist.length

      previousIndex = playlist.indexOf(player.current) - 1
      if previousIndex >= 0
        player.play(playlist[previousIndex])
      else
        false

    seekTo: (time) ->
      console.log('seekTo')
      # console.debug audio.currentTime = parseInt(time, 10)

    updateProgress: ->
      player.progress = sound.getTime
      player.duration = sound.getDuration
      player.progress_percent = sound.getPercent()

  # Sound events
  sound.addEventListener 'canplay', (evt) ->
    $rootScope.$apply(-> player.ready = true)

  sound.addEventListener 'ended', ->
    $rootScope.$apply(->
      player.stop() if not player.next()
    )

  sound.addEventListener 'timeupdate', (evt) ->
    $rootScope.$apply(player.updateProgress)

  sound.addEventListener 'seeking', (evt) ->
    console.debug('seeking')

  sound.addEventListener 'seeked', (evt) ->
    console.debug('seeked')

  # Playlist methods
  playlist.add = (song) ->
    playlist.push(angular.copy(song))
    player.play() if not player.playing

  playlist.remove = (song) ->
    index = playlist.indexOf(song)
    playlist[index...1]

  player
]

Obviously, the app raise error TypeError: Cannot read property 'addEventListener' of null concerning the sound object which is definitely null.

Or maybe I'm doing wrong ? What is your advise for that ?

Thanks in advance. :)

Sound plays always every 2nd time

Hi,

i simply try to use this:

var jump1 = new buzz.sound('snd/jump1');
///
jump1.play();

That's fine. However, it's expected to play every second but i just hear every 2nd. So, how can i get rid of this? Btw., this does not just affect my project. Every project which uses Buzz has it (also your example).

I guess it's some sort of timer, but in my case, it's unwanted.

PS: The soundfile has a length of 00:00:01.

sounds only play once ?

my code blow:

<script type="text/javascript" src="../js/jquery-1.7.1.js"></script>
<script type="text/javascript" src="../js/buzz.js"></script>
<script>
        $(document).ready(function () {
            var win = new buzz.sound("audio/win", {formats: ["ogg", "mp3"]})
            var truck = new buzz.sound("audio/truck", {formats: ["ogg", "mp3"]})
            $("input").click(function () {
                if(this.id === "win"){
                    win.play()
                }else{
                    truck.play()
                }
            })
        })
</script>

when i click the button id is 'win' or 'truck', the related sounds played at the first click, and no more
i wrote this code base on buzz's documents, where is the problem?

Google Chrome 15.0.874.121 (09964)

possible to use buzz.js with already loaded audio?

I'm seeking an HTML5 audio lib that does not include (require) the loading of the audio assets itself. I have a framework that packages page assets into a single JSON data structure, and the audio elements for the page are in that data blob. Due to this, I already have the audio elements in memory. Can buzz.js be used to play these already loaded audio assets?

Make it possible to extend buzz.sound

Hello!

I'm working on a html5 app. I found that the buz.sound.loop does not work on iOS v <= 4.3. The solution was simply to bind an event to "timeupdate" and than play the sound once again when it had finished playing.

I have not analyzed the code to find out why buzz.sound.loop doesn't work for me but I found one thing: The way you have written the class buzz.sound makes it impossible to extend the class. If you would change the if-statement on line 594 in the following way it becomes possible to extend the class:

if ( supported && src ) {

I know that class inheritance is rarely done by javascript programmers but I still think that you should write classes possible to extend.

...and btw, great work with this neat javascript library!

multi-audio problem

Hi,
Thank you for this great library.
my english is such poor...
when i was using this library
i wrote this code
var Audio = {
song : null,
......
play : function(){
Audio.song = new buzz.sound("url");
Audio.song.play();
},
....
}
when i run Audio.play(),beacause of the diffetennt url
there is many song
then all of them plays
hao can i play only one of them?
thx~

.bindOnce() doesn't work?

Tracing the code, I found that when using .bindOnce(), e.g. sound.bindOnce('ended', callback)
It turns out to be binding the event "0ended", "1ended", ...
due to the increasing pid.

It seems that the audio element doesn't have the event "[0-9]+ended", so it just won't work.

My current solution is to manually unbind the event:

sound.bind('ended', function () {
// do something
this.unbind('ended');
});

If i play sound again it is starts from last stopped instead of start from beginning. (ipad1)

I have a HTML list element where every list element has a specific audio. i want to play audio on click event of list and also on next and previous buttons. so i wrote below code for that, it's working on desktop browsers. when i am testing it on mobile safari (ipad1). when i am playing audio second time it is started from where it is stopped on last time. i want to start audio from beginning.

$(document).ready(function(){   

    var mainIntro = new buzz.sound( "audio/intro", {formats: [ "ogg", "mp3", "aac" ], preload: true, autoplay: true, loop: false});
    var slide1 = new buzz.sound( "audio/slide1", {formats: [ "ogg", "mp3", "aac" ], preload: true, autoplay: true, loop: false});

function introAudio() {
        buzz.all().stop();          
        mainIntro.play().bind('ended', function(e){
            document.getElementById("blinkRed").style.visibility="visible";
        }); 
}
    function slide1Audio() {
        buzz.all().stop();  
        slide1.play().bind('ended', function(e){
            document.getElementById("blinkRed").style.visibility="visible";
        });     
    }

$('#navHolder ul li a').click(function() {

        if (myIndex == -1){ 
            $('#slideHolder').attr('src',"introMain.html");         
            myIndex = -1;
            introAudio();

        }       
        else if (myIndex == 0){
            $('#slideHolder').attr('src',"intro.html");
            myIndex = 0;
            slide1Audio();
        }
else if (myIndex == 1){

        }
});

Play sound one after another in a Group

Is there a way to play sounds, one after the other in a group. I find my self having a large number of bind events.

        mySound1.play();

        mySound1.bind("ended", function(e) {
            mySound2.play();
        });
        mySound2.bind("ended", function(e) {
            mySound3.play();
        });

partial content loading

I have created a player with Buzz, but before I even start to "play" the first track, I can see in network inspector that it is loading partial content of all the files in the soundObject. Does anyone know why it is doing that? Am I doing something wrong? Seems a bit inefficient ...
image
http://d.pr/i/8QfP

Loop event binding

Is there an event to bind to so that we know how many times the audio has looped? If anyone knows a workaround, that would also be helpful

Buzz.js works in Safari 5 but not Safari 6

Hi Jay - love Buzz.js, it's awesome. Thanks for your work on it. I noticed a recent issue with a site in production. You may view it here:

http://www.aatsinkiseason.com

We are using buzz.js to play background audio. It works like a charm in all browsers, and in Safari 5. But now with Safari 6 it's not working. For the life of me I can't figure out what the issue is. Do you have any ideas?

[iOS] Playing a sound sequence

Hi,

I would like to play a sequence of 3 sounds using a click trigger and the 'ended' buzz event.
The following code works well on desktop HTML5 browser.

On iOS5 Safari, the first sound is played, the 'ended' event is detected but the second sound doesn't start...
On iOS4 Safari, no sound is played at all.

var sound1 = new buzz.sound("mp3/h5.mp3"),
sound2 = new buzz.sound("mp3/q3.mp3"),
sound3 = new buzz.sound("mp3/m5.mp3");

sound1.bind("ended", function(e) { sound2.play(); });
sound2.bind("ended", function(e) { sound3.play(); });

$(document).ready(function() {
$('#play').click(function() {
sound1.play();
});
});

Does anyone know if it's a iOS limitation?
Any help is welcome!

Thanks in advance.

event object not containing reference to the source sound besides `this`

Apparently every event on buzz sends an event object to the callback, but unfortunately the source object is only accessible with this.


function onMetadata(event) {
        this.getDuration(); //this works fine
        event[source].getDuration(); //could be also available
}

The problem with having only this to refer to the source object is that when using es5 strict mode you will find that the use of the keyword this would be referring to the global context and not the object itself.

As you can see here Douglas Crockford avoids this on JSLint declaring it as a bad coding practice. I am not sure of that, but in any case it might be a good idea to have this helper in case users try to use strict

Otherwise the only solution would be to create a global sound object and keep referring to it instead of this, but that is not very good, too :(

Thanks and congratulations for such a great library

After using $.getScript buzz doesn't work.

Hi I am a phonegap developer.When I use buzz in my project I found a problem.

$.ajax({
url : "....",
dataType : "script",
success : function (){
play_music = new buzz.sound(mp3_link);
}
});

play_music.play() doesn't work.If I remove ajax function,everything works fine.I don't know what cause this problem.I like Buzz.I wish you to kill this issue as quickly as possible.Thank you very much.

If it is not an issue,please tell me the solution of this problem. :-)

Tip on how to abort sound after getting metadata

Hi I am trying to load different sounds from a list but with the only purpose of getting its length

function onMetadata(event) {

    var node = document.getElementById(this.id);
    if (node) {
        node.querySelector('.time').innerText = buzz.toTimer(this.getDuration());
        //OK now I can Abort It
    }
}

function getMetadataForTracks(theTracks) {

    var dummySound, i;

    for (i = 0; i < theTracks.length; i += 1) {

        dummySound = new buzz.sound(db.track(theTracks[i]));
        dummySound.id = theTracks[i];
        dummySound.bind('loadedmetadata', onMetadata);

    }

}

Is there any way I can cancel the request after getting the metadata, it seems that the page keeps loading resources and it doesn't get cancelled.

Thanks :)

Firefox ogg vorbis sound effects - some work, some don't (help, help me Rhonda!)

Hi! I purchased six sound effects in wav format and converted them to mp3 and ogg vorbis using either total audio converter or audacity. The buzz format string is "ogg", "mp3" for all of the sounds. All of the sounds play in chrome and i.e. without any problems. But in Firefox, two of the sounds work with both conversions; one works only when converted by total sound converter; one works only when converted by audacity; and two of them don't work either way. Mediainfo reports the same info (Vorbis, 44.1 khz, 256 bps) for all twelve of the ogg conversions. VLC plays all of the ogg files just fine. Needless to say, this is making me crazy. Can anyone suggest a solution?

0 Missing when time is over 1 min+

There is a Zero missing when you convert getTime -> toTimer

seconds = buzz.toTimer( mySound.getTime());

It works initially in the beginning showing 00:07

But when it gets to say 2 min it looks like 02:7

and the same for other minutes as well

Is this a bug, or did I misconfigure something.

Otherwise this is an awesome library to build HTML5 audio players.

Thank you for your time.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.