Bootstrap

unity 音频的使用AudioSource

方法一:直接在软件操作给物体添加AudioSource组件
在这里插入图片描述

方式二:用脚本控制

软件添加AudioSource
在这里插入图片描述
音频文件拖入脚本
在这里插入图片描述
脚本附体物体上执行脚本
在这里插入图片描述
脚本代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class  NewTest: MonoBehaviour
{
    // 获取播放音频片段Audiocilp
    public AudioClip music; // 音频文件
    public AudioClip se; // 音频文件
    // 获取播放器组件
    private AudioSource player;
    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)
            {
                // 暂停
               // player.Pause();
                // 停止
                player.Stop();
            }
            else {
                // 继续
                player.UnPause();
                // 开始播放
               // player.Play();
            
            }
        }

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