rserota / wad

Web Audio DAW. Use the Web Audio API for dynamic sound synthesis. It's like jQuery for your ears.
MIT License
1.9k stars 159 forks source link

Add a Sound Iterator #109

Closed frastlin closed 5 years ago

frastlin commented 5 years ago

I have a set of sounds that I would like played alternating, for footsteps mostly. I think this could act very similar to a polywad, just when you call play, it will play the next sound rather than the same sound. Here is some code I have that does this:

import Wad from 'web-audio-daw'

export default class SoundIterator{
    static defaultArgs = {
        files: [], // either sound files or Wad audio objects
        random: false, // either play a random order, or play in the order of a list
        // there could also be how many items should be played before a sound repeats if there is random.
    }

    constructor(args){
        args = Object.assign({}, SoundIterator.defaultArgs, args)
        this.files = args.files
        this.sounds = this.files.map(f=>f.play ? f : new Wad({source:f})) // checks if the item in the list is a wad or not.
        this.random. = args.random
        this.index = 0 // keeps track of what item in the list is playing
    }

    play(){
        if(!this.sounds.length) return 0
        if(this.random){
            const sound = this.sounds[Math.floor(Math.random()*this.sounds.length)]
            sound.play()
        } else {
            if(this.sounds[this.index]) this.sounds[this.index].play()
            this.index += 1
            if(this.index >= this.sounds.length){
                this.index = 0
            }
        }
    }
}
frastlin commented 5 years ago

112

frastlin commented 5 years ago

Closed by: https://github.com/rserota/wad/pull/112