Wednesday, January 7, 2009

Playing Sounds in SketchUp



This week I'd like to talk about a much-maligned feature of the SketchUp Ruby API... UI.play_sound. Why would you ever want to play sound via the Ruby API? Glad you asked!

Besides the obvious desire to listen to Marvin Gaye while drawing your skatepark, you could enhance a scene tour with sound effects that match the location where your camera is located. It puts the multi in multimedia. Sounds fun, right? Let's try it.

Step 1: Get a Zoo With some Scenes

For this exercise, we're going to need a model with some Scene tabs. Luckily I have just the zoo. Click here to download a ZIP file with everything you need to follow this example.

Once you get it, unzip everything to your SketchUp/Plugins/ directory. It contains four files:

  • zoo.skp - a model of the world's lamest zoo
  • zoo.rb - the code that we're about to talk about
  • zoo_lion.wav - what the lion says
  • zoo_elephant.wav - what the elephant says
  • zoo_sang.wav - what Sang says

Step 2: Don't Feed the Animals

Once everything is in your /Plugins/ directory, open the zoo.skp file
and click the Scene tabs. Turn up the volume. You should hear a sound
effect that the Ruby API plays at each scene stop.

Step 3: Explore the Code

Here's the entire script. It shows using a Page Observer to capture
each frame of our scene animations. It watches the callback parameter
percent_done to figure out when the animation is complete, and then
it plays the sound.
# Create a class that will "observe" frame changes.
class ZooFrameObserver < Sketchup::ViewObserver

def frameChange(from_page, to_page, percent_done)
if percent_done == 1.0
if to_page == Sketchup.active_model.pages[0]
UI.play_sound("Plugins/zoo_lion.wav")
elsif to_page == Sketchup.active_model.pages[1]
UI.play_sound("Plugins/zoo_elephant.wav")
elsif to_page == Sketchup.active_model.pages[2]
UI.play_sound("Plugins/zoo_sang.wav")
end
end
end

end

# Attach our observer.
Sketchup::Pages.add_frame_change_observer(ZooFrameObserver.new)

I look forward to the day when every ruby script will play sounds with each interaction. I also like the blink tag. Huzzah!

3 comments:

Anonymous said...

乒乒乓乓

Thomas Thomassen said...

Oh no you didn't! o_O
How dare you revive the blink! @_o

*goes to curl up in a corner*

AL Paton said...

Hello Scott,
what a great way to "put the multi in multimedia"!
Q. Can you link UI.play.sound to Dynamic Component functions including ANIMATE and OnClick ?
PS: Thanks for the fine detail you included in your original post and attachments for it helps so much when exploring the code.
Regards, AL.