官术网_书友最值得收藏!

Loading and attaching sounds to objects

In this recipe we will take a look into Panda3D's positional audio capabilities. 3D sound is a wonderful tool to immerse the player and to generate great atmosphere. Positional audio also can help the player to orientate: In a shooter, for example, it is much easier to return fire if one heard that the enemy units are attacking from behind.

Getting ready

Before starting this recipe, be sure to set up a project as described in Setting up the game structure. You will also need to provide a mono sound file called loop.wav in the sounds folder of your project.

How to do it...

Let's load a sound file and attach it to a model:

  1. Open Application.py and add the highlighted code:
    from direct.showbase.ShowBase import ShowBase
    from direct.showbase.Audio3DManager import Audio3DManager
    
    class Application(ShowBase):
        def __init__(self):
            ShowBase.__init__(self)
            self.smiley = loader.loadModel("smiley")
            self.smiley.reparentTo(render)
    
            self.audio = Audio3DManager(self.sfxManagerList[0])
            self.audio.attachListener(self.cam)
    
            self.loop = self.audio.loadSfx("loop.wav")
            self.loop.setLoop(True)
            self.audio.attachSoundToObject(self.loop, self.smiley)
            self.loop.play()
            
            self.cam.setPos(0, -40, 0)
  2. Hold the left mouse button and move the mouse to pan the camera, or hold down the right mouse button and use the mouse to zoom in and out of the scene. Note how the sound position changes.

How it works...

The key to positional audio in Panda3D is the Audio3DManager class. After adding a smiley to the scene, we initialize the Audio3DManager and set the camera to be the listener object. This has the effect that all sounds played using positional audio will be mixed relative to the NodePath we pass to attachListener().

Then, the sound file is loaded, set to be a loop and attached to the smiley, so that the sound plays wherever the object is positioned in the scene. Finally we start to play the sound loop and position the camera.

Note

Positional audio will not work if we are using a stereo sound file. Panda3D will print a warning message in the console output if our sound is stereo, not mono.

There's more...

If you want to take the scene objects' and listener's velocity into account to achieve the Doppler effect, you need to update the listener and object positions by passing their velocity vectors to the setListenerVelocity() and setSoundVelocity() methods of Audio3DManager.

主站蜘蛛池模板: 革吉县| 金寨县| 育儿| 裕民县| 昔阳县| 天津市| 荣昌县| 平乐县| 天峨县| 安达市| 普兰县| 汤原县| 江城| 栾川县| 兴义市| 土默特右旗| 肥东县| 德钦县| 丹阳市| 金川县| 闵行区| 余干县| 贞丰县| 托克逊县| 武陟县| 田林县| 吐鲁番市| 赤峰市| 襄樊市| 当阳市| 朔州市| 开化县| 武冈市| 芜湖县| 丽水市| 邯郸市| 涿州市| 黄骅市| 开鲁县| 新源县| 高陵县|