- Home /
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 :
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 :/
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.
Iam not entirely a expert on sound matter, but this behaviour you are getting,
Seems a wrong format to play on android. $$anonymous$$obile systems are sometimes very strict and specific to some extensions/plugins types. Same on videos also.
Check also a few options of the file, compressions, bitrates, etc... a sound expert may give you a help in that
In the worst case, your android system runs out of resources to load the file, or not loading it quick enought to be readable by unity engine
$$anonymous$$aybe this helps somehow.
Can you please show the full code? I need to see when and how you are calling this.
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.
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));
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.
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 :/
Are you able to send me the scene with entire script? I need to debug to find out the issue.