Play random sound

Howdy. I’m having trouble figuring out this problem. Say I have a bunch of different sounds (1, 2, 3, 4) and I want a random one to play when the user touches a button. I can’t seem to figure out how to get Corona to pick a random sound. Does anyone have any suggestions? [import]uid: 35706 topic_id: 6398 reply_id: 306398[/import]

You can stock your sounds in a table and create a function for the random process. For example:

[lua] --Table to stock all sound files
local soundCollection = { “1.caf”, “2.caf”, “3.caf”, “4.caf” }

–Function with random process and play
local function randomSound ()
local choice = math.random( 1, 4 )
media.playEventSound( soundCollection[choice] )
end

–Button
local button = display.newRoundedRect (50, 50, 100, 50, 12)
button:setFillColor (255, 255, 0)
button:addEventListener ( “tap”, randomSound)
[/lua]
[import]uid: 8970 topic_id: 6398 reply_id: 22144[/import]

Awesome! I’ll give it a shot. Thank you! [import]uid: 35706 topic_id: 6398 reply_id: 22239[/import]

I’ve tried it and I’m getting an error that says “WARNING: Failed to create event sound” and then it lists which random sound it didn’t play. So I guess the sound collection and selecting a random sound is working but something else isn’t? [import]uid: 35706 topic_id: 6398 reply_id: 22358[/import]

this is probably not the cleanest coding but i think it will work (i’m at work so can’t test)

i think you have to load each sound first - the following might work…

[code]
– loud sounds
local sound1 = audio.loadSound(“first.caf”);
local sound2 = audio.loadSound(“second.caf”);
local sound3 = audio.loadSound(“third.caf”);
local sound4 = audio.loadSound(“fourth.caf”);

– some function requiring random sound
local function someSound()
local i = math.random(4);
audio.play(“sound”…i);
end
[/code] [import]uid: 24493 topic_id: 6398 reply_id: 22385[/import]

Loading the sounds individually works fine (I’ve tried them on other buttons), but the random selection is working. I’m assuming that “…i” means to take whatever random number is picked and add that number to the end of the word “sound”. I’m not sure why that’s not working… [import]uid: 35706 topic_id: 6398 reply_id: 22595[/import]

Strings are not the same thing as variable references. When you want to collect together multiple things use a table:

[code]
– loud sounds
local sounds = {}
sounds[1] = audio.loadSound(“first.caf”);
sounds[2] = audio.loadSound(“second.caf”);
sounds[3] = audio.loadSound(“third.caf”);
sounds[4] = audio.loadSound(“fourth.caf”);

– some function requiring random sound
local function someSound()
local i = math.random(4);
audio.play(sounds[i]);
end
[/code] [import]uid: 12108 topic_id: 6398 reply_id: 22596[/import]

Jhocking! You figured it out! I guess you’re not all bad :stuck_out_tongue:

Thank you! [import]uid: 35706 topic_id: 6398 reply_id: 22630[/import]

I am the worst. That code is actually a virus. [import]uid: 12108 topic_id: 6398 reply_id: 22687[/import]

Crap. That explains why my MacBook exploded. Now I have an arch-nemesis! [import]uid: 35706 topic_id: 6398 reply_id: 22741[/import]

Hey Guys.
Ive been trying to make random sounds when my Ball hits the wall.

but it doesn’t do shit.

local physics = require(“physics”)
physics.start()
physics.setGravity(0, 0)
display.setStatusBar( display.HiddenStatusBar )

local bkg = display.newImage(“foto1.png”)
local soccer_ball = display.newImage(“soccer_ball.png”)
soccer_ball.x = 160
soccer_ball.y = 200
physics.addBody(soccer_ball, { density = 0.3, friction = 0.6, radius = 50} )

local boings = {}
boings[1] = audio.loadSound(“Space Gun 01.wav”)
boings[2] = audio.loadSound(“dum.aiff”)
boings[3] = audio.loadSound(“Metal Hit 04.wav”)
boings[4] = audio.loadSound(“Arcade Alarm 01.wav”)

local function someSound()
local i = math.random(1, 4)
audio.play(boings[i])
end
local motionx = 0
local motiony = 0

local function moveBall(event)
soccer_ball.x = soccer_ball.x - motionx
soccer_ball.y = soccer_ball.y - motiony
end

Runtime:addEventListener(“enterFrame”, moveBall)
local remote = require(“remote”)

remote.startServer( “8080”)

local function updateAccelerometer()
motionx = 35 * remote.xGravity
motiony = 35 * remote.yGravity
end

– Add Enter Frame Listener
Runtime:addEventListener( “enterFrame” , updateAccelerometer )

borderBodyElement = { friction=0.3, bounce=0.4 }
local borderTop = display.newRect( 0, -10, 320, 20 )
borderTop:setFillColor( 0, 0, 0, 0) – make invisible
physics.addBody( borderTop, “static”, borderBodyElement )

local borderBottom = display.newRect( 0, 500, 320, 20 )
borderBottom:setFillColor( 200, 0, 0, 255)
physics.addBody( borderBottom, “static”, borderBodyElement )

local borderLeft = display.newRect( 0, 10, 10, 460 )
borderLeft:setFillColor( 0, 0, 0, 0) – make invisible
physics.addBody( borderLeft, “static”, borderBodyElement )

local borderRight = display.newRect( 310, 10, 25, 460 )
borderRight:setFillColor( 0, 0, 0, 0) – make invisible
physics.addBody( borderRight, “static”, borderBodyElement )

function onHit(e)
if(e.phase == “began”) then
if(e.object1 == borderBottom) then
audio.play(boing[i])
end
end
end

Runtime:addEventListener(“collision”, onHit)

function onHit(e)
if(e.phase == “began”) then
if(e.object1 == borderRight) then
audio.play(boing[i])
end
end
end
Runtime:addEventListener(“collision”, onHit)

function onHit(e)
if(e.phase == “began”) then
if(e.object1 == borderLeft) then
audio.play(boing[i])
end
end
end
Runtime:addEventListener(“collision”, onHit)

function onHit(e)
if(e.phase == “began”) then
if(e.object1 == borderTop) then
audio.play(boing[i])
end
end
end
Runtime:addEventListener(“collision”, onHit) [import]uid: 51793 topic_id: 6398 reply_id: 33475[/import]

One problem seems to be you create a variable called “boings”, but then try to play “boing” (no ‘s’).
[import]uid: 7563 topic_id: 6398 reply_id: 33477[/import]

Still doesn’t do shit.

local physics = require(“physics”)
physics.start()
physics.setGravity(0, 0)
display.setStatusBar( display.HiddenStatusBar )

local bkg = display.newImage(“foto1.png”)
local soccer_ball = display.newImage(“soccer_ball.png”)
soccer_ball.x = 160
soccer_ball.y = 200
physics.addBody(soccer_ball, { density = 0.3, friction = 0.6, radius = 50} )

local sounds = {}
sounds[1] = audio.loadSound(“Space Gun 01.wav”);
sounds[2] = audio.loadSound(“dum.aiff”);
sounds[3] = audio.loadSound(“Metal Hit 04.wav”);
sounds[4] = audio.loadSound(“Arcade Alarm 01.wav”);
local function someSound()
local i = math.random(4);
audio.play(sounds[i]);
end

local motionx = 0
local motiony = 0

local function moveBall(event)
soccer_ball.x = soccer_ball.x - motionx
soccer_ball.y = soccer_ball.y - motiony
end

Runtime:addEventListener(“enterFrame”, moveBall)
local remote = require(“remote”)

remote.startServer( “8080”)

local function updateAccelerometer()
motionx = 35 * remote.xGravity
motiony = 35 * remote.yGravity
end

– Add Enter Frame Listener
Runtime:addEventListener( “enterFrame” , updateAccelerometer )

borderBodyElement = { friction=0.3, bounce=0.4 }
local borderTop = display.newRect( 0, -10, 320, 20 )
borderTop:setFillColor( 0, 0, 0, 0) – make invisible
physics.addBody( borderTop, “static”, borderBodyElement )

local borderBottom = display.newRect( 0, 500, 320, 20 )
borderBottom:setFillColor( 200, 0, 0, 255)
physics.addBody( borderBottom, “static”, borderBodyElement )

local borderLeft = display.newRect( 0, 10, 10, 460 )
borderLeft:setFillColor( 0, 0, 0, 0) – make invisible
physics.addBody( borderLeft, “static”, borderBodyElement )

local borderRight = display.newRect( 310, 10, 25, 460 )
borderRight:setFillColor( 0, 0, 0, 0) – make invisible
physics.addBody( borderRight, “static”, borderBodyElement )

function onHit(e)
if(e.phase == “began”) then
if(e.object1 == borderBottom) then
audio.play(sounds[i])
end
end
end

Runtime:addEventListener(“collision”, onHit)

function onHit(e)
if(e.phase == “began”) then
if(e.object1 == borderRight) then
audio.play(sounds[i])
end
end
end
Runtime:addEventListener(“collision”, onHit)

function onHit(e)
if(e.phase == “began”) then
if(e.object1 == borderLeft) then
audio.play(sounds[i])
end
end
end
Runtime:addEventListener(“collision”, onHit)

function onHit(e)
if(e.phase == “began”) then
if(e.object1 == borderTop) then
audio.play(sounds[i])
end
end
end
Runtime:addEventListener(“collision”, onHit) [import]uid: 51793 topic_id: 6398 reply_id: 33485[/import]

[lua] – your problem is in this block
function onHit(e)
if(e.phase == “began”) then
if e.object1 == borderRight or
e.object1 == borderLeft or
e.object1 == borderTop or
e.object1 == borderBottom then

– this is your issue here
audio.play(sounds[i])

– instead do this
someSound() – this should solve your problem

end
end
end
Runtime:addEventListener(“collision”, onHit)

[import]uid: 12455 topic_id: 6398 reply_id: 33637[/import]

I don’t think your ‘i’ has actually been assigned a value when you use it to play audio and is thus ‘nil’.
[import]uid: 7563 topic_id: 6398 reply_id: 33638[/import]

jhocking, Can you help?!

I am making a memory card match game and trying to play a random .caf sound (out of four) Upon getting the matching card or a non matching card.

For instance, you get it right you get a random sound out of four like: “imsorry.caf”, “no.caf”, "yousuck.caf, etc.)

I have tried to implement your advice via this thread but to no avail. I can only achieve one sound played. Where the hell do i place this code? this is my main.lua

help would be much appreciated


–Set Global width and height variables
_W = display.contentWidth;
_H = display.contentHeight;

–Hide status bar
display.setStatusBar(display.HiddenStatusBar);

display.setStatusBar(display.HiddenStatusBar)

local background = display.newImage (“background.png”)


– background music –

backgroundMusic = audio.loadStream(“billyJean.caf”)

backgroundMusicChannel = audio.play( backgroundMusic, { channel=0, loops=1, fadein=20000 } )

– Michaels Head Normal –

local MichaelNormal = display.newImage (“MichaelNormal.png”)
MichaelNormal.x = 130
MichaelNormal.y = 85

–Declare a totalButtons variable to track number of buttons on screen
local totalButtons = 0

–Declare variable to track button select
local secondSelect = 0
local checkForMatch = false

–Declare button, buttonCover, and buttonImages table
local button = {}
local buttonCover = {}
local buttonImages = {1,1, 2,2, 3,3, 4,4, 5,5, 6,6,}
–Notify player if match is found or not
local matchText = display.newText("", 0, 228, native.systemFont, 18)
matchText:setReferencePoint(display.CenterReferencePoint)
matchText:setTextColor(51, 255, 102)
matchText.x = _W/2

–Set starting point for button grid
x = -27
y = -80
–Set up game function
function game(object, event)
if(event.phase == “began”) then
if(checkForMatch == false and secondSelect == 0) then
–Flip over first button
buttonCover[object.number].isVisible = false;
lastButton = object
checkForMatch = true

elseif(checkForMatch == true) then
if(secondSelect == 0) then
–Flip over second button
buttonCover[object.number].isVisible = false;
secondSelect = 1;
–If buttons do not match, flip buttons over

if(lastButton.myName ~= object.myName) then
matchText.text = “Match Not Found!”;
timer.performWithDelay(800, function()
matchText.text = " ";
checkForMatch = false;
secondSelect = 0;
buttonCover[lastButton.number].isVisible = true;
buttonCover[object.number].isVisible = true;
local MichaelNormal = display.newImage (“MichaelSick.png”)
MichaelNormal.x = 130
MichaelNormal.y = 85
media.playEventSound(“imsorry.caf”)
end, 1)

–If buttons DO match, remove buttons
elseif(lastButton.myName == object.myName) then
matchText.text = “Match Found!”;
timer.performWithDelay(1250, function()
matchText.text = " ";
checkForMatch = false;
secondSelect = 0;
lastButton:removeSelf();
object:removeSelf();
buttonCover[lastButton.number]:removeSelf();
buttonCover[object.number]:removeSelf();
local MichaelNormal = display.newImage (“MichaelHealth.png”)
MichaelNormal.x = 130
MichaelNormal.y = 85
media.playEventSound(“good.caf”)
end, 1)
end
end
end
end
end

–Place buttons on screen
for count = 1,4 do
x = x + 75
y = 214

for insideCount = 1,3 do
y = y + 75

–Assign each image a random location on grid
temp = math.random(1,#buttonImages)
button[count] = display.newImage(buttonImages[temp] … “.png”);

–Position the button
button[count].x = x;
button[count].y = y;

–Give each a button a name
button[count].myName = buttonImages[temp]
button[count].number = totalButtons

–Remove button from buttonImages table
table.remove(buttonImages, temp)

–Set a cover to hide the button image
buttonCover[totalButtons] = display.newImage(“button.png”);
buttonCover[totalButtons].x = x; buttonCover[totalButtons].y = y;
totalButtons = totalButtons + 1

–Attach listener event to each button
button[count].touch = game
button[count]:addEventListener( “touch”, button[count], playfalse1 )

end
end
[import]uid: 94909 topic_id: 6398 reply_id: 59259[/import]

The samurai fruit sample code actually has a great example of playing random sounds. (For swipes and when objects are sliced.)

See here; http://developer.anscamobile.com/code/samurai-fruit

Peach :slight_smile: [import]uid: 52491 topic_id: 6398 reply_id: 59278[/import]

Thanks for the reply. Looks straight forward, but I’m trying to put it here…am i just tired and being stupid ?
if(lastButton.myName ~= object.myName) then
matchText.text = “Match Not Found!”;
timer.performWithDelay(800, function()
matchText.text = " ";
checkForMatch = false;
secondSelect = 0;
buttonCover[lastButton.number].isVisible = true;
buttonCover[object.number].isVisible = true;
local MichaelNormal = display.newImage (“MichaelSick.png”)
MichaelNormal.x = 120
MichaelNormal.y = 70

– Return a random value between ‘min’ and ‘max’
function getRandomValue(min, max)
return min + math.abs(((max - min) * math.random()))
end

function playRandomMichaelSound()

audio.play(MichaelSounds[“false” … math.random(1, 3)])
end
[import]uid: 94909 topic_id: 6398 reply_id: 59289[/import]

Is the code specific to each individually written program? It doesn’t seem to function properly when inserted into my code.
[import]uid: 94909 topic_id: 6398 reply_id: 61726[/import]