Unity sound

The camera has its own sound plug-in by default, so if there are multiple cameras, an error will be reported, just delete the sound plug-in of another camera and keep one

Bind the sound to the object: add the sound plug-in Audio Source, drag the music directly into the

Play when wake up: whether to play when running

3D Sound Settings

①: There is a trumpet-shaped figure on the object, drag and drop to adjust the minimum distance (sound)

②: Slide the scroll wheel and you will find a maximum spherical shape, which controls the maximum distance (sound)

script control

Add AudioTest script

    //写下该对象,脚本文件中会出现下面该选项,将音乐拖拽进去后,该对象不为空
    public AudioClip music;
    public AudioClip se;

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

public class AudioTest : MonoBehaviour
{
    //AudioClip
    public AudioClip music;
    public AudioClip se;

    //播放器组件
    private AudioSource player;


    // Start is called before the first frame update
    void Start()
    {
        player = GetComponent<AudioSource>();
        //设定播放的音频片段
        player.clip = music;
        //循环播放
        player.loop = true;
        //音量
        player.volume = 0.5f;
        //播放
        player.Play();
    }

    // Update is called once per frame
    void Update()
    {
        //按空格切换声音的播放和暂停
        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (player.isPlaying)
            {
                //暂停 对应关系:1 正常暂停
                //player.Pause();

                //停止 对应关系:2 每次暂停都重新开始
                player.Stop();
            }
            else
            {
                //继续 对应关系:1
                //player.UnPause();

                //开始播放 对应关系:2
                player.Play();
            }
        }

        //按鼠标左键播放声音
        if (Input.GetMouseButton(0))
        {
            //只播放一声
            player.PlayOneShot(se);
        }
    }
}

Guess you like

Origin blog.csdn.net/ssl267422/article/details/128808519