播放游戏音频的类(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);
}
}
}
注:
-
audioSource.Stop()这个函数一旦执行就停止音频播放,想要重新播放音频就只有执行audioSource.Play()这条命令
-
使用音频文件的前提是,要在相应的组件上装AudioListener组件