• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by ShroomWasTaken · Aug 10, 2017 at 02:54 PM · audioaudiosourceaudioclip

Can't seem to play my AudioClip?

What I'm trying to do is simply to play a footstep sound, however it doesn't seem to be as simple as I thought it would be.

Currently my code looks like this :

                     AudioClip clipss = Resources.Load<AudioClip>("Audio/Clips/WalkableMaterialClips/Stone/Stone_0");
                     AudioSource source_ = GetComponent<AudioSource>();
                     source_.clip = clipss;
                     AudioSource.PlayClipAtPoint(clipss, transform.position);

I know that the path which I specify to Resources.Load is correct since it is not null when I step through the game in visual studio.

The source_ variable is also a valid value (aka, it's not null), so that's fine as well.

I have checked the volume of the AudioClip, and playing it inside the Unity editor as well as outside using windows also works and I can hear the footstep sound clearly.

However, I can not hear it in-game for some reason.

I also tried with this approach :

                     AudioClip clipss = Resources.Load<AudioClip>("Audio/Clips/WalkableMaterialClips/Stone/Stone_0");
                     AudioSource source_ = GetComponent<AudioSource>();
                     source_.clip = clipss;
                     source_.Play();

Which also didn't play the sound, and I have set the AudiClip in the inspector.

I also tried using the PlayOneShot() function which also was silent.

The AudioSource Component looks like this in the inspector :

alt text

And a AudioListener is attached to my MainCamera, so I don't think that's the problem either.


Edit :

If I check the Play On Awake boolean in the AudioSource inspector, it plays once on start like ti should. Still doesn't play when I tell it to though. :/

Edit 2 :

Here's the full class which contains the sound-playing stuff :

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class PlayerControllerComponent : MonoBehaviour
 {
 
     public bool allowMovement; // If this is set to false, the player will not be able to walk or jump in any direction.
     public bool allowLooking; // If this is set to false, the player will not be able to move the view.
 
     public float verticalSensitivity;
     public float horizontalSensitivity;
 
     public float maxLookVertical;
     public float minLookVertical;
 
     public float moveSpeed;
     public float runSpeed;
 
     public float footstepRate;
     private float m_footstepTimer;
 
     public float maxStamina;
     public float staminaRegen; // The amount of stamina that will be regenerated per second.
     private float m_stamina;
 
     public float interactionRange; // The minimum range an object has to be in in order for the player to interact with it.
 
     private Rigidbody m_rigidBody;
     private Camera m_mainCamera;
     private GameObject m_cameraPosObject;
     private AudioSource m_audioSource;
 
     private void Start()
     {
         m_rigidBody = GetComponent<Rigidbody>();
         m_mainCamera = Camera.main;
         m_cameraPosObject = GameObject.Find("CameraPosition");
         Cursor.lockState = CursorLockMode.Locked;
         allowLooking = true;
         allowMovement = true;
         m_footstepTimer = footstepRate;
     }
 
     private void Update()
     {
         if (Input.GetKeyDown(KeyCode.Escape))
         {
             allowLooking = !allowLooking;
             if (Cursor.lockState == CursorLockMode.Locked)
                 Cursor.lockState = CursorLockMode.None;
             else
                 Cursor.lockState = CursorLockMode.Locked;
         }
 
         CheckControllerInput();
     }
 
     /// <summary>
     /// Checks for all character-controller related inputs.
     /// </summary>
     private void CheckControllerInput()
     {
         if (allowMovement)
         {
             bool movementInputDetected = false;
 
             if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
             {
                 m_rigidBody.AddForce(m_mainCamera.transform.forward * moveSpeed * Time.deltaTime, ForceMode.VelocityChange);
                 movementInputDetected = true;
             }
             
             if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
             {
                 m_rigidBody.AddForce(-m_mainCamera.transform.forward * moveSpeed * Time.deltaTime, ForceMode.VelocityChange);
                 movementInputDetected = true;
             }
 
             if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
             {
                 m_rigidBody.AddForce(m_mainCamera.transform.right * moveSpeed * Time.deltaTime, ForceMode.VelocityChange);
                 movementInputDetected = true;
             }
 
             if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
             {
                 m_rigidBody.AddForce(-m_mainCamera.transform.right * moveSpeed * Time.deltaTime, ForceMode.VelocityChange);
                 movementInputDetected = true;
             }
 
             if (!movementInputDetected)
             {
                 m_rigidBody.velocity = new Vector3(0, m_rigidBody.velocity.y, 0);
             }
             else if (movementInputDetected && Vector3.Distance(m_rigidBody.velocity, new Vector3(0, 0, 0)) > 0)
             {
                 if (m_footstepTimer > 0)
                 {
                     m_footstepTimer -= Time.deltaTime;
                 }
                 else
                 {
                     m_footstepTimer = footstepRate;
                 }
             }
         }
 
         if (allowLooking)
         {
             float verticalInput = Input.GetAxis("Mouse Y");
             float horizontalInput = Input.GetAxis("Mouse X");
 
             /*
             m_mainCamera.transform.rotation *= Quaternion.AngleAxis(-verticalInput * verticalSensitivity, Vector3.right);
             m_mainCamera.transform.rotation *= Quaternion.AngleAxis(horizontalInput * horizontalSensitivity, Vector3.up);
             m_mainCamera.transform.rotation = new Quaternion(m_mainCamera.transform.rotation.x, m_mainCamera.transform.rotation.y, 0, m_mainCamera.transform.rotation.w);
             transform.rotation = m_mainCamera.transform.rotation;
             m_mainCamera.transform.position = m_cameraPosObject.transform.position;
             */
 
             m_mainCamera.transform.Rotate(-verticalInput * verticalSensitivity, 0, 0, Space.Self);
             m_mainCamera.transform.Rotate(0, horizontalInput * horizontalSensitivity, 0, Space.World);
             //transform.rotation = m_mainCamera.transform.rotation;
             m_mainCamera.transform.rotation = new Quaternion(Mathf.Clamp(m_mainCamera.transform.rotation.x, minLookVertical, maxLookVertical), m_mainCamera.transform.rotation.y,
                 m_mainCamera.transform.rotation.z, m_mainCamera.transform.rotation.w);
             m_mainCamera.transform.position = m_cameraPosObject.transform.position;
         }
 
         if (Input.GetKeyDown(KeyCode.E))
         {
             RaycastHit rayHit;
             if (Physics.Raycast(m_mainCamera.transform.position, m_mainCamera.transform.forward, out rayHit, interactionRange))
             {
                 if (rayHit.transform.tag == "Interactable")
                 {
                     rayHit.transform.GetComponent<Interactable>().Interact();
                 }
             }
         }
     }
 
     private void OnCollisionStay(Collision collision)
     {
         if (m_footstepTimer == 0)
         {
             WalkingMaterialComponent gMatComp = collision.gameObject.GetComponent<WalkingMaterialComponent>();
             if (gMatComp != null)
             {
                 if (gMatComp.walkingMaterial == WalkingMaterialComponent.WalkingMaterials.Stone)
                 {
                     AudioClip clipss = Resources.Load<AudioClip>("Audio/Clips/WalkableMaterialClips/Stone/Stone_0");
                     AudioSource srcAudio = gameObject.GetComponent<AudioSource>();
                     srcAudio.clip = clipss;
                     srcAudio.Play();
                 }
             }
         }
     }
 
 }
 

And here's the WalkingMaterialComponent class :

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class WalkingMaterialComponent : MonoBehaviour
 {
     [System.Serializable]
     public enum WalkingMaterials { Wood, Metal, Stone, Grass, Soil, Silent }
 
     public WalkingMaterials walkingMaterial;
 }

And the ground which the player walks on has Stone set to be the WalkingMaterial type in the inspector.


No idea what I'm doing wrong here :/

Comment
Add comment · Show 4
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image HDX13 · Aug 11, 2017 at 01:00 AM 0
Share

Same thing happened to me, only in Android after I build it to AP$$anonymous$$. It won't load on the built game but works on the Editor. Also, VS replied properly (AudioClip is not null, AudioSource is loaded) on the Editor but not on my real device.

Show more comments
avatar image RisingDead_xTR · Aug 11, 2017 at 01:27 PM 0
Share

Can you please show the full code? I need to see when and how you are calling this.

Show more comments

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by ShroomWasTaken · Aug 12, 2017 at 11:55 AM

I fixed it, had nothing to do with the actual AudioSource.

I was 100% certain I had checked if the code was running properly yesterday, but it wasn't. Not sure what I got that from.

Anyways all I had to do was change the if (m_footstepTimer == 0) line in the OnCollisionStay() function to use the less than or equal operator instead of equal one since the Time.deltaTime cannot guarantee that the m_footstepTimer will actually ever be equal to 0 when subtracting it to the timer since it might be large enough to just skip over 0 and become a negative value, which was the case here.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Komayo · Aug 12, 2017 at 04:20 PM 1
Share

Glad that you fixed it, debugging is a most in this situations to find this issues. I had many of those errors like you. When using subtract or aditions to get a new value and then compare it in if statements, now i have the habbit to clamp all those calculated values, so if i want a value between 0 and 1, i dont get over 1 and i dont get below 0. Here is the function i normaly use, $$anonymous$$athf.Clamp(float value, float $$anonymous$$, float max);

 // Clamps the value 10 to be between 1 and 3.
 // prints 3 to the console
 Debug.Log($$anonymous$$athf.Clamp(10, 1, 3));
avatar image
0

Answer by Komayo · Aug 11, 2017 at 01:36 AM

Try this please:

 AudioSource srcAudio = gameObject.GetComponent<AudioSource>();

Make sure gameObject with AudioSource attached, is not destroyed when you attempt to play the sound, that is another typical error.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ShroomWasTaken · Aug 11, 2017 at 11:24 AM 0
Share

Tried that, no sound and no errors generated, and the GameObject with the AudioSource and script attached to it is visible in the editor during runtime so that's not the problem :/

avatar image Komayo ShroomWasTaken · Aug 11, 2017 at 11:22 PM 0
Share

Are you able to send me the scene with entire script? I need to debug to find out the issue.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

87 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Audio clip not playing 1 Answer

WWW Audio and PlayOneShot: Playing the same AudioClip Twice Cuts off First Instance 1 Answer

Audio loops too early 2 Answers

No overlapping sounds 0 Answers

Question about audio (AudioSource). My ingame sound doesn't sound like the original audio file? 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges