0

我有一个 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;
    }
}
4

2 回答 2

2

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

// 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();
}
于 2017-11-15T11:18:00.137 回答
1

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

if (h != 0f || v != 0f) {
     if (!audioSource.isPlaying) audioSource.Play ();
} else {
     audioSource.Pause ();
}
于 2017-11-15T09:59:10.553 回答