版本: Unity 6 (6000.0)
语言英语
  • C#

AudioSource.PlayScheduled

建议更改

成功!

感谢您帮助我们提高 Unity 文档的质量。虽然我们无法接受所有提交内容,但我们会阅读用户提出的每个建议,并在适当的情况下进行更新。

关闭

提交失败

由于某些原因,您的建议更改无法提交。请<a>稍后再试</a>。感谢您抽出时间帮助我们提高 Unity 文档的质量。

关闭

取消

切换到手册

声明

public void PlayScheduled(double time);

参数

time 在 AudioSettings.dspTime 所指的绝对时间线上,声音开始播放的时间(以秒为单位)。

描述

在 AudioSettings.dspTime 所指的绝对时间线上,在特定时间播放 clip

这是在音乐播放器中拼接 AudioClip 的首选方法,因为它独立于帧速率,并为音频系统提供足够的时间来准备声音的播放,以便从媒体中获取它(流),而无需导致突然的 CPU 尖峰(打开和缓冲需要很多时间)。

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 中的示例展示了如何在两个音频片段之间不产生爆音或咔嗒声的情况下播放两个音频片段。这种方法是使用两个带有音频片段的 AudioSource,并使用其 AudioSource 对每个音频片段进行排队。

其他资源:SetScheduledStartTime.