全文
extern crate ggez;
use ggez::conf;
use ggez::event;
use ggez::graphics;
use ggez::{Context, GameResult};
use ggez::audio;
use ggez::timer;
use std::env;
use std::path;
struct MainState {
sound: audio::Source,
}
impl MainState {
fn new(ctx: &mut Context) -> GameResult<MainState> {
let sound = audio::Source::new(ctx, "/sound.ogg").unwrap();
let _ = sound.play();
let s = MainState {
sound,
};
Ok(s)
}
}
impl event::EventHandler for MainState {
fn update(&mut self, ctx: &mut Context) -> GameResult<()> {
if timer::get_ticks(ctx) % 10 == 0 {
let _ = self.sound.play();
}
Ok(())
}
fn draw(&mut self, ctx: &mut Context) -> GameResult<()> {
graphics::clear(ctx);
graphics::present(ctx);
Ok(())
}
}
pub fn main() {
let c = conf::Conf::new();
let ctx = &mut Context::load_from_conf("super_simple", "ggez", c).unwrap();
if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
let mut path = path::PathBuf::from(manifest_dir);
path.push("resources");
ctx.filesystem.mount(&path, true);
}
let state = &mut MainState::new(ctx).unwrap();
event::run(ctx, state).unwrap();
}
簡単な解説
struct MainState {
sound: audio::Source,
}
定義部分。
let sound = audio::Source::new(ctx, "/sound.ogg").unwrap();
let _ = sound.play();
ggezプロジェクトに含まれているsound.ogg
を読み込んで再生。
if timer::get_ticks(ctx) % 10 == 0 {
let _ = self.sound.play();
}
以降、定期的に再生。なお、timer::get_ticks
はイベントループが再生された数を返す。
その他
リピート再生
let mut sound = audio::Source::new(ctx, "/sound.ogg").unwrap();
sound.set_repeat(true);
let _ = sound.play();
一時停止・再開
sound.pause()
sound.resume()
停止
sound.stop()
状態確認
let is_playing = sound.playing()
let is_stopped = sound.stopped()
let is_paused = sound.paused()
playingはpaused == false
かつstopped == false
音量取得・変更
sound.volume()
sound.set_volume(2.)
デフォルトの音量は1.0。
2.0くらいまであげると音割れが発生した。