SoundPlayOneshot.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //======= Copyright (c) Valve Corporation, All rights reserved. ===============
  2. //
  3. // Purpose: Play one-shot sounds as opposed to continuos/looping ones
  4. //
  5. //=============================================================================
  6. using UnityEngine;
  7. using System.Collections;
  8. namespace Valve.VR.InteractionSystem
  9. {
  10. //-------------------------------------------------------------------------
  11. public class SoundPlayOneshot : MonoBehaviour
  12. {
  13. public AudioClip[] waveFiles;
  14. private AudioSource thisAudioSource;
  15. public float volMin;
  16. public float volMax;
  17. public float pitchMin;
  18. public float pitchMax;
  19. public bool playOnAwake;
  20. //-------------------------------------------------
  21. void Awake()
  22. {
  23. thisAudioSource = GetComponent<AudioSource>();
  24. if ( playOnAwake )
  25. {
  26. Play();
  27. }
  28. }
  29. //-------------------------------------------------
  30. public void Play()
  31. {
  32. if ( thisAudioSource != null && thisAudioSource.isActiveAndEnabled && !Util.IsNullOrEmpty( waveFiles ) )
  33. {
  34. //randomly apply a volume between the volume min max
  35. thisAudioSource.volume = Random.Range( volMin, volMax );
  36. //randomly apply a pitch between the pitch min max
  37. thisAudioSource.pitch = Random.Range( pitchMin, pitchMax );
  38. // play the sound
  39. thisAudioSource.PlayOneShot( waveFiles[Random.Range( 0, waveFiles.Length )] );
  40. }
  41. }
  42. //-------------------------------------------------
  43. public void Pause()
  44. {
  45. if ( thisAudioSource != null )
  46. {
  47. thisAudioSource.Pause();
  48. }
  49. }
  50. //-------------------------------------------------
  51. public void UnPause()
  52. {
  53. if ( thisAudioSource != null )
  54. {
  55. thisAudioSource.UnPause();
  56. }
  57. }
  58. }
  59. }