Unity 6.3
0 онлайн 54 гостей 3 в системе
Вход

AudioSource.PlayScheduled

Declaration

public void PlayScheduled(double time);

Параметры

Параметр Описание
время Абсолютное время начала в секундах на AudioSettings.dspTime временной шкале. Запланируйте время немного в будущем (~100-200 мс), чтобы аудиосистема могла подготовить воспроизведение.

Описание

Воспроизведение clip в определенное время на абсолютной временной линии, из которой AudioSettings.dspTime читает.

Это предпочтительный способ сращивания AudioClips в музыкальных проигрывателях, потому что он независим от частоты кадров и дает аудиосистеме достаточно времени для подготовки воспроизведения звука, чтобы получить его из носителей, где открытие и буферизация занимают много времени (потоки), не вызывая внезапных пиков CPU.

Если time меньше текущего AudioSettings.dspTime, воспроизведение начинается как можно скорее (обычно немедленно), а не в тот момент в прошлом. Любое аудио, которое было бы воспроизведено, когда time находился в прошлом, не воспроизводится.

Если time отрицательно, оно рассматривается как 0 (начало без абсолютной задержки по расписанию).

Если AudioSource.resource является AudioRandomContainer, время по расписанию в прошлом может быть запрошено в клипе, чтобы сохранить время. Если задержка превышает длину клипа, воспроизведение может не произойти.

using UnityEngine;
using System.Collections;

// Basic demonstration of a music system that uses PlayScheduled to preload and sample-accurately // stitch two AudioClips in an alternating fashion. The code assumes that the music pieces are // each 16 bars (4 beats / bar) at a tempo of 140 beats per minute. // To make it stitch arbitrary clips just replace the line // nextEventTime += (60.0 / bpm) * numBeatsPerSegment // by // nextEventTime += clips[flip].length;

[RequireComponent(typeof(AudioSource))] public class ExampleClass : MonoBehaviour { public float bpm = 140.0f; public int numBeatsPerSegment = 16; public AudioClip[] clips = new AudioClip[2];

private double nextEventTime; private int flip = 0; private AudioSource[] audioSources = new AudioSource[2]; private bool running = false;

void Start() { for (int i = 0; i < 2; i++) { GameObject child = new GameObject("Player"); child.transform.parent = gameObject.transform; audioSources[i] = child.AddComponent<AudioSource>(); }

nextEventTime = AudioSettings.dspTime + 2.0f; running = true; }

void Update() { if (!running) { return; }

double time = AudioSettings.dspTime;

if (time + 1.0f > nextEventTime) { // We are now approx. 1 second before the time at which the sound should play, // so we will schedule it now in order for the system to have enough time // to prepare the playback at the specified time. This may involve opening // buffering a streamed file and should therefore take any worst-case delay into account. audioSources[flip].clip = clips[flip]; audioSources[flip].PlayScheduled(nextEventTime);

Debug.Log("Scheduled source " + flip + " to start at time " + nextEventTime);

// Place the next event 16 beats from here at a rate of 140 beats per minute nextEventTime += 60.0f / bpm * numBeatsPerSegment;

// Flip between two audio sources so that the loading process of one does not interfere with the one that's playing out flip = 1 - flip; } } }

Пример в AudioSource.SetScheduledEndTime показывает, как можно воспроизвести два аудиоклипа без звуковых всплесков или щелчков между клипом. Подход заключается в том, чтобы иметь два AudioSources с прикрепленными клипами и поставить каждый клип в очередь с помощью его AudioSource.

Дополнительные ресурсы: AudioSource.SetScheduledStartTime.