UnityAPI学习之 播放游戏音频的类(AudioSource)

播放游戏音频的类(AudioSource)

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NO17AudioSource : MonoBehaviour
{
    private AudioSource audioSource;//音频组件
    public AudioClip clip;//音频文件
    public AudioClip clip2;
    bool mutestate;
    bool pausestate;
    // Start is called before the first frame update
    void Start()
    {
        audioSource = GetComponent<AudioSource>();
        audioSource.clip = clip;
        audioSource.Play();
        //设置音乐的播放开始的时间轴位置
        audioSource.time = 3;
    }

    // Update is called once per frame
    void Update()
    {
        //实现按下W键静音,再次按下恢复音量
        if (Input.GetKeyDown(KeyCode.W))
        {
            mutestate = !mutestate;
            audioSource.mute = mutestate;
        }
        if (Input.GetKeyDown(KeyCode.P))
        {
            pausestate = !pausestate;
            //暂停播放
            if (pausestate)
            {
                audioSource.Pause();
            }
            else
            {
                //继续播放
                audioSource.UnPause();
            }
        }
        //停止播放
        if (Input.GetKeyDown(KeyCode.S))
        {
            audioSource.Stop();
        }
        //播放一次
        if (Input.GetKeyDown(KeyCode.K))
        {
            audioSource.PlayOneShot(clip2);
        }
        //静态方法
        //在指定位置创建音频
        if (Input.GetKeyDown(KeyCode.Q))
        {
            AudioSource.PlayClipAtPoint(clip2,transform.position);
        }
    }
}

注:

  1. audioSource.Stop()这个函数一旦执行就停止音频播放,想要重新播放音频就只有执行audioSource.Play()这条命令

  2. 使用音频文件的前提是,要在相应的组件上装AudioListener组件

相关推荐
一隅论数智3 天前
给AI一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
XiHongShi20163 天前
STM32F407 RTC定时器例程,建议保存
stm32·单片机·学习
神仙别闹3 天前
基于C#+MySQL实现(WinForm)个人聊天室软件
c#
爱吃苹果的日记本3 天前
离散数学第六课
学习·离散数学
AI职业加油站3 天前
AI智能体应用工程师证书:政策红利下的职业新风口
大数据·运维·人工智能·学习·职场发展
旖旎夜光3 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
奇思妙想聪明勤奋的小羊3 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
霍霍的袁3 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio