Bevy 0.16 音频组件( AudioSource)组件中文文档
/// 表示音频数据的来源
#[derive(Clone, Debug)]
pub struct AudioSource {
/// 音频源的原始字节数据
pub bytes: Arc<[u8]>,
}
字段说明
字段名称 | 类型 | 描述 |
---|---|---|
bytes |
Arc<[u8]> |
音频源的原始字节数据。必须使用 Bevy 支持的文件格式(wav、ogg、flac 或 mp3)。 注意:这些格式的支持需要启用 Bevy 的对应可选特性(feature)。 使用 rodio::decoder::Decoder 进行解码。如果未启用对应格式的特性,解码时会触发 UnrecognizedFormat 错误。 |
特性实现 (Trait Implementations)
AsRef<[u8]>
impl AsRef<[u8]> for AudioSource {
/// 将类型转换为对 `[u8]` 的共享引用
fn as_ref(&self) -> &[u8];
}
Clone
impl Clone for AudioSource {
/// 返回值的副本
fn clone(&self) -> AudioSource;
/// 从源执行复制赋值
fn clone_from(&mut self, source: &Self);
}
Debug
impl Debug for AudioSource {
/// 使用格式化器显示结构体信息
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>;
}
Decodable
(可解码)
impl Decodable for AudioSource {
/// 音频采样类型(通常是 u16/i16/f32,需实现 `rodio::Sample`)
type DecoderItem = <Decoder<Cursor<AudioSource>> as Iterator>::Item;
/// 音频采样迭代器类型(需实现 `rodio::Source`)
type Decoder = Decoder<Cursor<AudioSource>>;
/// 构建并返回解码器实例
fn decoder(&self) -> Self::Decoder;
}
TypePath
(类型路径)
impl TypePath for AudioSource {
/// 返回完整类型路径(如 "bevy::audio::AudioSource")
fn type_path() -> &'static str;
/// 返回简短类型路径(带美化格式)
fn short_type_path() -> &'static str;
/// 返回类型名称(如果有)
fn type_ident() -> Option<&'static str>;
/// 返回所属 crate 名称(如果有)
fn crate_name() -> Option<&'static str>;
/// 返回模块路径(如果有)
fn module_path() -> Option<&'static str>;
}
VisitAssetDependencies
(资源依赖访问)
impl VisitAssetDependencies for AudioSource {
/// 访问该资源依赖的其他资源
fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId));
}
Asset
(资源标记)
impl Asset for AudioSource {} // 标记该类型为可加载资源
自动特性实现 (Auto Trait Implementations)
特性 | 说明 |
---|---|
Freeze |
标记类型为不可变 |
RefUnwindSafe |
保证在栈展开时安全 |
Send |
可跨线程安全传递 |
Sync |
可跨线程安全共享引用 |
Unpin |
允许移动后继续使用 |
UnwindSafe |
保证在 panic 时不会导致内存不安全 |
泛型实现 (Blanket Implementations)
常见类型转换
impl<T> From<T> for T; // T 到 T 的平凡转换
impl<T, U> Into<U> for T where U: From<T>; // 通用类型转换
资源容器
impl<A> AssetContainer for A where A: Asset; // 标记资源容器类型
序列化/反序列化
impl<T> ToHex for T where T: AsRef<[u8]>; // 将字节转换为十六进制字符串
其他工具特性
impl<T> Instrument for T; // 添加诊断工具
impl<T> Tap for T; // 链式调用工具
impl<T> ToOwned for T where T: Clone; // 克隆到拥有值的转换
使用示例
// 加载音频文件(需启用对应格式的特性)
let audio_source = AudioSource {
bytes: Arc::new(include_bytes!("sound.ogg").to_vec()),
};
// 使用解码器播放音频
let decoder = audio_source.decoder();
audio_sink.play(decoder);
注意
- 必须启用对应音频格式的特性(如
ogg
、mp3
等),否则解码时会 panic。 - 支持的格式详见 Bevy 音频文档。