Unity3d - 在播放和暂停之间转换时音频粗糙的声音

Unity3d - Audio rough sound when transition between play and pause

我有一个 Unity 脚本可以在玩家移动时播放音频(脚步声)。脚本可以运行,但还有一个问题,在播放和暂停之间转换时,音频似乎太粗糙(可能会损坏我的扬声器呵呵)。

这是我的脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

public class PlayerController : MonoBehaviour {
    Rigidbody playerRigid;
    private Vector3 pindah;
    public AudioSource audioSource;
    public AudioClip audioClip;
    public float lowPitchRange = .95f;
    public float hiPitchRange = 1.05f;

    void Awake () {
        audioSource = GetComponent<AudioSource> ();
        audioSource.clip = audioClip;
        float randomPitch = Random.Range (lowPitchRange, hiPitchRange);
        audioSource.pitch = randomPitch;
    }

    // Use this for initialization
    void Start () {
        //mengambil komponen rigidbody player
        playerRigid = GetComponent<Rigidbody> ();
    }

    // Update is called once per frame
    void Update () {
        //untuk mendapatkan input dari virtual joystick button
        float h = CrossPlatformInputManager.GetAxisRaw ("Horizontal");
        float v = CrossPlatformInputManager.GetAxisRaw ("Vertical");

        if ((h != 0f || v != 0f) && !audioSource.isPlaying) {
            audioSource.Play ();
        } else {
            audioSource.Pause ();
        }
        //memindah posisi player sesuai input yang didapat
        pindah = new Vector3 (h, 0.0f, v);
        playerRigid.velocity = pindah;
    }
}

我猜你需要像这样更改代码:

if (h != 0f || v != 0f) {
     if (!audioSource.isPlaying) audioSource.Play ();
} else {
     audioSource.Pause ();
}

如果问题是暂停时音频源突然弹出,也许你应该考虑用类似这样的东西来淡化音量(我自己没有测试过,我稍后会尝试):

// fade/increase time in seconds
public float rateTime = 1; 

public FadeSound() { 
    //audioSource.Play ();
    StartCoroutine(_FadeSound); 
    }

public IncreaseSound() { 
    StartCoroutine(_IncreaseSound); 
}

IEnumerator _FadeSound() {
    float t = rateTime;

    while (t > 0) {
        yield return null;
        t-= Time.deltaTime;
        source.volume = t/rateTime;
    }
    yield break;
    //yield audioSource.Pause ();
}

IEnumerator _IncreaseSound() {
    float t = 0;

    while (t < 1) {
        yield return null;
        t+= Time.deltaTime;
        source.volume = t/rateTime;
    }
    yield break;
}

if ((h != 0f || v != 0f) && !audioSource.isPlaying) {
    IncreaseSound();
} else {
    FadeSound();
}