音频系统(二)

一、音频系统的简单应用

实现功能:在场景中加入背景音乐,并实现开门声

1)导入游戏场景,创建一个胶囊体作为游戏主角。给胶囊体添加“Rigidbody”组件,将主摄像机(含Audio Listener组件)绑定到胶囊体上并调整好位置;

2)选中一扇门,给门添加“Box Collider”组件并勾选“Is Trigger”;给门添加“Audio Source”组件,添加门音乐;给门添加Tag标签“door”;

3)将背景音乐拖拽到Hierarchy视图,调整好适当的位置。给背景音乐添加Audio Reverb Zone以及高通、低通音频过滤器。在Audio Source下调节好Spatial Blend(控制当角色距离大于“Reverb Zone”的Max Distance时的音量)

4)实现代码:(将代码添加到胶囊体上)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private AudioSource _audioSource;
    void FixedUpdate()
    {
        Move();
    }
    void Move()
    {
        //角色移动
        //运行时需要在"Rigidbody"组件上设置constraints(轴约束),否则角色胶囊无法保持平衡
        transform.Translate(0, 0, Input.GetAxis("Vertical") * Time.deltaTime * 5);
        transform.Rotate(0, Input.GetAxis("Horizontal") * Time.deltaTime * 50, 0);
    }
    void OnTriggerEnter(Collider other)
    {
        //使用OnTrigger方法必须在游戏物体或者角色上开启“Is Trigger”
        //如果触发标签为"door"的游戏对象,则改变它的位置并播放声音
        //如果transform.position前不添加“other”,则默认改变的是当前绑定脚本的游戏对象
        if (other.tag == "door")
        {
            other.transform.position = new Vector3(other.transform.position.x, other.transform.position.y + 3.6f, other.transform.position.z);
            _audioSource = other.GetComponent<AudioSource>();
            _audioSource.Play();
        }
    }
    void OnTriggerExit(Collider other)
    {
        if (other.tag == "door")
        {
            other.transform.position = new Vector3(other.transform.position.x, other.transform.position.y - 3.6f, other.transform.position.z);
            _audioSource = other.GetComponent<AudioSource>();
            _audioSource.Play();
        }
    }
}

二、Audio Mixer 脚本控制

1. 暴露接口

如:选中一个 Groups 组,在 Inspector 面板中的 Volume 右键选择 Expose 'Volume (of Master)' to script

2. 修改接口参数名称,在脚本中进行调用

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;                                    //引入音频的命名空间

public class AudioMixerControl : MonoBehaviour {

    public AudioMixer _AudioMixer;                          //音频混合器
    void Start () {
        //控制音量的大小,0 对应混响器中的音量大小
        _AudioMixer.SetFloat("ExposedParam_MasterVolume", 0);
    }
    
}

 

posted @ 2017-04-03 18:59  LiuChangwei  阅读(370)  评论(0编辑  收藏  举报