Unity sound and video playback basics

chat:

There are reasons why game development is more difficult than ordinary software development. First, the functional requirements of the game are diverse and the internal logic is intertwined, while the software is relatively fixed, and it is nothing more than click-to-jump and data storage. Second, the game requires a lot of 3D mathematics and physics knowledge. , at least have the foundation of high school physics, forces, vectors, rays, in addition to these data storage, there is also a lot

However, you need to have a calm mind and an attitude of never getting tired of it, just add it a little bit and play a little bit! Check now and learn now, learn now and use now, forgetting after use is the norm!

Unity sound control depends on needs. Every project needs are different!

Today, you will realize a business requirement of hitting gold coins and making sounds!

Import sounds from scene to warehouse

Just drag the sound to the Unity folder

Then the implementation of playing sound requires two components. One is the hearing sound component. There can only be one in the whole scene. Generally, it is hung on the cameraAudioListener

The other is AudioSource. This component is like a player, which specifies a sound clip to play. There are also corresponding classes to control everything about it.

When you play a lot of sounds, you can create multiple such components, or you can use one component to switch Audioclip through code to play different sounds. But there are also some sounds that need to be played at the same time. Unity takes these into consideration in the class. Playoneshot() is overlay playback.

You need to briefly understand it first

  1. Sound component AudioSource class (can store sound playback components, used to play and control sounds)

  2. AudioClip class sound clip (used to store audio), which can be assigned to AudioSource.clip in the future to implement audio switching

1. Function to play sound

1.AudioSource.Play()

Directly play the content of the clip in the current AudioSource class object

// Assuming an AudioSource component is attached to the same GameObject
public class AudioPlayer : MonoBehaviour
{
    private AudioSource audioSource;

    void Start()
    {
        audioSource = GetComponent<AudioSource>();
    }

    public void PlaySound()
    {
        if (audioSource.clip != null)
        {
            audioSource.Play();
        }
    }
}

AudioSource.clip can be assigned values from the outside, you can declare variables, assign values externally, or you can use the ResourceLoad() method to load local resources!

2 The following code is implemented by specifying multiple audios externally, and then switching the audios during playback

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

public class PlayAudio : MonoBehaviour
{
    private AudioSource audioSource;
    public AudioClip[] OneClip=new AudioClip[3];

    void Start()
    {
        //Get the playback component
        audioSource = GetComponent<AudioSource>();
    }
    //This function will be associated with the button in the future
    public void PlaySound()
    {
        //Give the sound variables stored in the array to the sound playback component as the default audio
        audioSource.clip = OneClip[0];
        if (audioSource.clip != null)
        {
            audioSource.Play();//Playback component
        }
    }
}

2.PlayOneShot:

The PlayOneShot method is a function of the Unity AudioSource class that allows you to play an audio clip without interrupting the currently playing audio. This method is particularly suitable for playing short-lived sound effects, such as explosions, clicks, etc. It accepts two parameters: an AudioClip object and an optional volume multiplier (float type), which will be multiplied by the AudioSource’s volume. For example, if you have a sound effect for the player’s jumping action, you can use PlayOneShot to play the jumping sound effect even if the background music is already playing from the same AudioSource. This way, the jump sound effect will play at the same time as the background music, without stopping or replacing the background music.

using UnityEngine;
public class SoundManager : MonoBehaviour
{
    // Reference to the audio source component
    public AudioSource audioSource;

    //Audio clip to play
    public AudioClip jumpSound;

    void Start()
    {
        // Get the AudioSource component on the current game object
        audioSource = GetComponent<AudioSource>();
    }

    //Method for playing jump sounds
    public void PlayJumpSound()
    {
        // Use PlayOneShot to play jumpSound audio clips
        // The second parameter is optional and is used to adjust the playback volume. If omitted, the default is 1 (that is, the current volume of AudioSource)
        audioSource.PlayOneShot(jumpSound, 1.0f);
    }
}

In this example, audioSource is a reference to the AudioSource component attached to the same game object, and jumpSound is the AudioClip object to be played. The PlayJumpSound method plays the jumpSound sound effect through the PlayOneShot method and sets the volume to the current volume of the AudioSource. This approach does not interrupt any audio currently playing on the AudioSource.

3.PlayClipAtPoint

PlayClipAtPoint is a static method in Unity, used to play an audio clip (AudioClip) at a specific position in 3D space without the need for an audio source (AudioSource) component. It creates a temporary AudioSource at the specified location, plays the audio once, and then destroys the AudioSource. This method is great for playing transient sound effects that don’t require detailed control, such as explosions or the sound of players collecting items.

When using the PlayClipAtPoint method, you need to provide the audio clip and a Vector3 position. You can also optionally provide a volume parameter, but this is not required. This method automatically handles audio playback and cleanup, eliminating the need to pre-place audio sources in the scene.

using UnityEngine;

public class AudioManager : MonoBehaviour
{
    //Audio clip to play
    public AudioClip explosionSound;

    // Play the audio clip at a specific location in 3D space
    public void PlayExplosionSound(Vector3 position)
    {
        // Use PlayClipAtPoint to play the explosionSound audio clip at the specified position
        // The second parameter is the position of the audio. The third parameter is optional and is used to adjust the volume. The default value is 1.0
        AudioSource.PlayClipAtPoint(explosionSound, position, 1.0f);
    }
}

In this code, we have an AudioClip variable called explosionSound. When the PlayExplosionSound method is called, it will use the PlayClipAtPoint method to play the explosionSound sound effect at the specified position. This method automatically creates a temporary AudioSource to play the sound effect, and destroys the AudioSource after the sound effect is played. This approach is ideal for handling sound effects that are not associated with a specific game object.

My gold coin case

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

public class Collision222 : MonoBehaviour
{
    // Clone gold coins
    //Hang on the protagonist and detect the gold coin cloning area and obstacle cloning area respectively
    //Let the protagonist trigger the gold coin trigger. If triggered, start cloning the gold coin.
    public GameObject CoinMuban;
    GameObject TempTriggerCoin;
    public Transform oneCoinParent;


    public AudioClip coinSound; // Gold coin sound effect, drag and drop assignment from outside
    public AudioClip MonsterAudio; // Health loss sound effect, drag and drop from outside to assign value

    private void OnTriggerEnter(Collider other)//When I trigger someone else, I store the other person’s collider in other.
    {
        TempTriggerCoin = other.transform.gameObject;
        if (other.transform.gameObject.name== "TriggerCoin01")
        {

            CloneCoin();//Start cloning gold coins
        }

        if (other.transform.gameObject.name == "TriggerStru")
        {
            CloneStruction();//Start cloning obstacles
        }


        if (other.transform.gameObject.tag == "Coin")
        {
            //Start adding points
            Debug.Log("Start adding points");
            Destroy(other.transform.gameObject);
            AudioSource.PlayClipAtPoint(coinSound, other.transform.position);//Temporarily played, destroyed after completion
        }

        if (other.transform.gameObject.tag == "Monster")
        {
            //Start adding points
            Debug.Log("Start losing blood");
         
        }
    }

    void CloneCoin()
    {
        for (int i = 0; i < 10; i + + )
        {
            Vector3 clonePos = new Vector3(156, 0.5f, TempTriggerCoin.transform.position.z + 50 + i*3);
            Debug.Log("Start cloning gold coins");
            GameObject.Instantiate(CoinMuban, clonePos, Quaternion.Euler(0, 0, 0), oneCoinParent);
        }
    }
    void CloneStruction()
    {
        Debug.Log("Start cloning obstacles");
    }
}

2. Multiple sound playback

1. Create multiple AudioSource components, each component plays its own clip fragment

2. Multiple sound clips, but only one AudioSource component

You can use the public methods in the AudioSource class to modify the sound clip of the current component.

AudioSource audioSource;

Core code:

audioSource.clip = clip1;

audioSource.clip = clip2;

using UnityEngine;

public class PlayMultipleAudioClips : MonoBehaviour
{
    public AudioSource audioSource; // your AudioSource component
    public AudioClip clip1; // first sound clip
    public AudioClip clip2; // second sound clip

    void Start()
    {
        // Play the first sound clip
        PlaySound(clip1, 0); // 0 means start playing from the beginning

        // Play the second sound clip after 3 seconds
        Invoke("PlaySecondSound", clip1.length + 3.0f); // Play the second sound clip 3 seconds after the first sound clip ends
    }

    void PlaySound(AudioClip clip, float startTime)
    {
        audioSource.clip = clip;
        audioSource.time = startTime;
        audioSource.Play();
    }

    void PlaySecondSound()
    {
        PlaySound(clip2, 0); // Play the second sound clip from the beginning
    }
}

3. Play video

Video playback is very similar to sound playback! Video playback does not require a listening component, it is directly completed by a VideoPlayer.

But the video needs a host to help render the video (this host can be a 3D object or UGUI-RawImage)

Video playback on 3D objects: For example, we should first create a game object, ensure that this object has the Rendener component and renders normally. Then add the VideoPlayer component to this game object. This component can be given to anyone!

Create videos on UGUI

First create the RawImage UI object, then add the video component

After dragging the video clip up, create a New Render Texture that can render the video

The texture of this rendering type needs to render the video, as the renderer of the Video Player component, and as the texture of the Rawimage component. Drag them to the Target Texture of the Video Player component, and then drag them to the Texture of the Raw Image component!

This completes playing video on the UI!

The rest is almost the same as the sound!

Drag a video into Assets and assign it directly to the component Video Clip! Now the game is running and ready to play!

Code Control:

The code can switch between different videos for playback.

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


public class PlayVideo : MonoBehaviour
{
    // Start is called before the first frame update
    public VideoClip[] SomeVideo = new VideoClip[10];

    VideoPlayer OneVideoComp;
    void Start()
    {
        OneVideoComp = this.GetComponent<VideoPlayer>();
        OneVideoComp.frame = 10;
    }

    private void Update()
    {
        Debug.Log(OneVideoComp.frameCount/25);
    }
//The following function associates external UGUI buttons
    public void ButtonClikA()
    {
        OneVideoComp.clip = SomeVideo[0];
        OneVideoComp.Play();
    }
    public void ButtonClikB()
    {
        OneVideoComp.clip = SomeVideo[1];
        OneVideoComp.Play();
  
    }
}