0
votes

I am making a Music Player app for Android in Unity3d. For show_currentPlayTime() function, I want to get AS.time value to show current playTime. For seek() function, I want to set AS.time value to get to that specific point of AudioClip. But, the problem is that AS.time is giving me 0.

I have tried setting AudioClip in AudioSource. It works that way, but the audio becomes distorted and shows abnormal behavior.

Variable Declaration:

public AudioSource AS;
[Range(0.0f, 1.0f)]

public Slider Volume;
public Slider slider;
bool isPlaying;


public List<AudioClip> AC = new List<AudioClip>();
int currentSong = 0;

Play Function:

public void Play()
{
    AS.Stop();
    AS.PlayOneShot(AC[currentSong]);

    //AS.clip = AC[currentSong]; ---
    //AS.Play(); ---
    //AS.clip = AC[currentSong]; ---
    //AS.PlayOneShot(AS.clip); ---

    clipInfo.text = AC[currentSong].name;
    Debug.Log(AC[currentSong].name);

    CancelInvoke();
    Invoke("Next", AC[currentSong].length);
    isPlaying = true;
}

The program runs with using --- lines, in above code, but with that, the audio becomes distorted.

Music Seek function:

public void MusicSlider()
{        
    AS.time = AC[currentSong].length * slider.value;
    slider.value = AS.time / AC[currentSong].length;
    Debug.Log(AS.time);
}

AS.time gives me value = 0.

1
What do you mean by distorted and abnormal behavior? Do you have exactly one AudioListener? Is it on the same GameObject as the AudioSource? - Ruzihm
Are you saying you tried public void Play() { AS.Stop(); AS.clip = AC[currentSong]; AS.Play(); clipInfo.text = AC[currentSong].name; ... ? - Ruzihm

1 Answers

0
votes

The AudioSource.Stop function stops the currently set Audio clip from playing

so you shouldn't be using PlayOneShot since this doesn't assign the clip value and isn't stopped but played parallel. It is usually more used for playing soundeffects which may occure at the same time.

From AudioSource

You can play a single audio clip using Play, Pause and Stop You can also adjust its volume while playing using the volume property, or seek using time. Multiple sounds can be played on one AudioSource using PlayOneShot.

AudioSource.time from the examples also only seems to work using Play instead of PlayOneShot for the same reason.

In the commented code you are also mixing both Play and PlayOneShot. I guess what you called distorted is actually the clip playing twice at the same time. Your code should rather simply be

public void Play()
{
    AS.Stop();

    AS.clip = AC[currentSong];
    AS.Play();

    clipInfo.text = AC[currentSong].name;
    Debug.Log(AC[currentSong].name);

    // Don't know ofcourse what those methods do...
    CancelInvoke();
    Invoke("Next", AC[currentSong].length);
    isPlaying = true;
}