LoginSignup
1
0

More than 5 years have passed since last update.

ggezでサウンドを鳴らす

Posted at

全文

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くらいまであげると音割れが発生した。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0