Play random sound assets

Hi all, I’ve been playing around with random sounds and wondered if this can also be accomplished with imported sound assets? If so can someone please point me to the right place. I’ve had a search of the various discussions but haven’t as yet found anything relevant. Thank you

@Karl I don’t see why you can’t. Where are you trying to get get imported sounds from.

I currently have a series of downloaded .wav files sat in my Dropbox asset folder. Thanks @dave1707

@Karl if you already have them in your Dropbox folder, you should be able to access them just like any other Codea sound file.

Sorry @dave1707 I’ve reread my initial post and it wasn’t particularly clear. I can access the sounds from Dropbox without issue, I’m just not sure how to play a randomised sound from that folder. The reference guide details SOUND_RANDOM for generated sound files, I’m just trying to figure out to apply that concept to imported sound files.

@Karl Here’s something that will play a random sound each time you tap the screen. These are fake names, but replace them with your Dropbox file names. Is this close to what you’re after.

function setup()
    tab={   asset.documents.Dropbox.dog,
            asset.documents.Dropbox.cat,
            asset.documents.Dropbox.owl
        }
end

function draw()
    background()
end

function touched(t)
    if t.state==BEGAN then
        s=math.random(#tab)
        sound(tab[s])       
    end    
end

@Karl Alternatively if you’re hoping to select a file from a folder at random then the following should also work:

function playRandomSound()
    
    -- Get a list of files in an asset pack
    local all = asset.downloaded.Game_Sounds_One.all
    local sounds = {}

    -- Filter the files so only audio remains
    for _,file in ipairs(all) do
        if file.type == SOUNDS then
            table.insert(sounds, file)
        end
    end

    -- Abort if we found no audio files
    if #sounds == 0 then
        return
    end
    
    -- Generate a random index
    local index = math.random(#sounds)
    
    -- Play the sound
    sound(sounds[index])
end

Feel free to factor the generation of the sounds array out of the function as it could be slow with many files.

@dave1707 absolutely spot on, thank you. I already had my touch function working so used your code to create a table of assets and then the variable to call a random sound from the table. I was playing round with tables to call the assets, but hadn’t considered using a variable to enable me to randomise the sound. @Steppers I haven’t yet played with your code, but will do to enable me to learn more. If my sound list gets too big then calling all assets in a folder and filtering by type would be appealing. Thank you both. Top quality help as always in this forum