This is the 15th day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Audio formats supported by Unity

  • AIFF: Best for short sound effects that can be compressed on demand in the editor
  • WAV: Best for short sound effects can be compressed in the editor as required
  • MP3: Best for longer music tracks
  • OGG: Compressed audio format (not compatible with iPhone devices and some Android devices), best for longer music

Related group price introduction

To play sounds in Unity, you need to have three components:

  • AudioListener: Used to play sound from an AudioAource component and then output it through the sound card. This component is usually automatically added to the main camera when the scene is created.
  • AudioClip: audio files in various formats that need to be played.
  • AudioSource: A component used for sound playback. It can control playback, pause, volume adjustment, etc.

Some major properties on the Audiosource component editor

  • Mute: Mute switch
  • Play On Awake: This object starts playing at Awake in its lifetime
  • Loop: indicates whether to play in a Loop
  • Volume: adjusts the Volume
  • Pitch: Used to adjust Pitch
  • Stereo Pan: Stereo channel adjustment. Less than 0 to the left and greater than 0 to the right

Code playback audio

Implementation steps:

  1. Create a “GameObject” and mount itAudio Sourcecomponent
  2. Import the audio into the Unity project and assign it toAudio SourceThe component’sAudioClipattribute
  3. Create the script AudioTest, mount it to “GameObject”, write the script and run the program

Example: Run the program, click the left mouse button to start playing the sound, click the right mouse button to pause the playback:

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

public class AudioTest : MonoBehaviour
{
    // Audio component
    private AudioSource audioSource;
    void Start()
    {
        // Get the component
        audioSource = GetComponent<AudioSource>();
        // Turn the volume to maximum
        audioSource.volume = 1;
        // Set to loop
        audioSource.loop = true;
        // Turn off autoplay
        audioSource.playOnAwake = false;
        // Stop the sound
        audioSource.Stop();
    }

    // Update is called once per frame
    void Update()
    {
        // Click the left mouse button
        if (Input.GetMouseButtonDown(0))
        {
            // Play the sound effects
            audioSource.Play();
        }
        // Right click
        else if (Input.GetMouseButtonDown(1))
        {
            // Stop the soundaudioSource.Stop(); }}}Copy the code
Copy the code