0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

HarmonyOS運動開発:あなたの専用の運動メトロノームを作ろう

Posted at

## 鴻蒙核心技术##運動開発##Media Kit(メディアサービス)#

前言

運動中に安定したリズムを保つことは、運動効果を高めるために非常に重要です。ランニング、サイクリング、もしくは高強度インターバルトレーニング(HIIT)を行う場合でも、正確なメトロノームがあれば、あなたは運動リズムをよりよくコントロールすることができ、より良いトレーニング効果を得ることができます。この記事では、鴻蒙(HarmonyOS)開発の実践経験を基に、運動メトロノームを開発する方法を詳しく解析し、運動中でも簡単にリズムを掌握できるようにします。

Image description
一、SoundPool を AVPlayer の代わりに選んだ理由

運動メトロノームを開発する際、私たちは SoundPoolAVPlayer の代わりに選びました。なぜなら、SoundPool は短い効果音を再生する際に優れており、迅速な応答を保証し、効果音のタイムリーな再生を確保することができるからです。これは、リズムを正確にコントロールする必要がある運動メトロノームにとって非常に重要です。一方、AVPlayer は長いオーディオファイル、例えば音楽やビデオを再生するのに適していますが、その応答速度と効果音再生の即時性は SoundPool には及びません。

二、運動メトロノームの核心ロジック

  1. 音響の初期化

メトロノームを起動する前に、効果音ファイルを読み込み、SoundPool を初期化する必要があります。以下が効果音の初期化の核心コードです:

async initSound() {
  this.soundPool = await media.createSoundPool(1, {
    usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // オーディオストリーム使用タイプ:音楽
    rendererFlags: 1
  });

  const context = getContext(this) as common.UIAbilityContext;
  const fd = context.resourceManager.getRawFdSync('medias/metronome2.mp3'); // 短い「ピッ」音を推奨します
  this.soundId = await this.soundPool.load(
    fd.fd,
    fd.offset,
    fd.length
  );
}
  1. メトロノームの再生ロジック

メトロノームの核心ロジックは、設定された BPM(毎分のビート数)に従って効果音を定期的に再生し、再生するたびに視覚的なヒント(例えばフラッシュ)を発生させることです。以下がメトロノーム再生ロジックの核心コードです:

startMetronome() {
  if (this.isPlaying) return;

  this.isPlaying = true;
  const interval = 60000 / this.bpm; // ビート間隔

  const playWithFlash = () => {
    this.flashActive = true;
    setTimeout(() => this.flashActive = false, 100); // 100ミリ秒後に flashActive を false に設定し、視覚状態を元に戻します。

    if (this.soundPool && this.soundId !== -1) {
      this.soundPool.play(this.soundId, {
        loop: 0,
        rate: 1.0,
        leftVolume: 1.0, // 最大音量を保証して運動中に聞こえるようにします
        rightVolume: 1.0,
        priority: 0
      });
    }

    this.timerId = setTimeout(playWithFlash, interval);
  };

  playWithFlash();
}
  1. メトロノームの停止

メトロノームを停止する際には、タイマーをクリアし、SoundPool のリソースを開放する必要があります。以下がメトロノーム停止の核心コードです:

stopMetronome() {
  this.isPlaying = false;
  clearTimeout(this.timerId);
}

三、ユーザーインターフェース設計

ユーザーがメトロノームを簡単にコントロールできるように、簡潔で直感的なユーザーインターフェースを設計する必要があります。以下がユーザーインターフェースの核心コードです:

build() {
  Column() {
    // 大きな視覚的なヒントエリア
    Circle()
      .width(200)
      .height(200)
      .fill(this.flashActive ? Color.Red : Color.White)
      .margin({ bottom: 40 })
      .animation({ duration: 50, curve: Curve.EaseIn })

    // 大きな BPM 表示
    Text(`${this.bpm}`)
      .fontSize(60)
      .fontWeight(FontWeight.Bold)
      .margin({ bottom: 30 })

    // 運動用 BPM 範囲スライダー
    Slider({
      value: this.bpm,
      min: 40,  // 最低の有効な運動リズム
      max: 200, // 高強度インターバルトレーニングの上限
      step: 1
    })
      .width('90%')
      .height(60)
      .onChange((value: number) => {
        this.bpm = value;
        if (this.isPlaying) {
          this.stopMetronome();
          this.startMetronome();
        }
      })

    // 運動用コントロールボタン
    Button(this.isPlaying ? '運動を止める' : '運動を始める')
      .width(200)
      .height(80)
      .fontSize(24)
      .backgroundColor(this.isPlaying ? Color.Red : Color.Green)
      .onClick(() => {
        this.isPlaying ? this.stopMetronome() : this.startMetronome();
      })
  }
  .width('100%')
  .height('100%')
  .justifyContent(FlexAlign.Center)
}

核心点解析

• 視覚的なヒント:Circle コンポーネントと flashActive 状態を使用して、視覚的なビートヒントを実現します。

• BPM 表示:Text コンポーネントを使用して現在の BPM 値を表示し、ユーザーがビート周波数を直感的に確認できるようにします。

• BPM 調整:Slider コンポーネントを使用してユーザーが BPM 値を調整でき、調整後にはメトロノームの周波数が自動的に更新されます。

• コントロールボタン:Button コンポーネントを使用してメトロノームの開始と停止機能を実現します。

四、最適化と改善

  1. 運動のステップ頻度に応じてメトロノームの周波数を設定する

ユーザーの運動リズムに更好地適応するために、ステップ頻度に応じてメトロノームの周波数を動的に調整することができます。以前の私の記事では、ステップ頻度とステップ幅を取得する方法について説明しています。

private async updateBpmFromStepFrequency() {
  // 現在のステップ頻度を取得する
  const currentStepFrequency = await this.getStepFrequency();
  this.bpm = Math.round(currentStepFrequency * 60); // ステップ頻度を BPM に変換する
  if (this.isPlaying) {
    this.stopMetronome();
    this.startMetronome();
  }
}
  1. 効果音の選択機能を追加する

異なるユーザーのニーズを満たすために、効果音の選択機能を追加し、ユーザーが異なるヒント音を選択できるようにすることができます。例えば、複数の効果音ファイルを提供することができます。

private soundOptions: string[] = ['metronome1.mp3', 'metronome2.mp3', 'metronome3.mp3'];
private selectedSoundIndex: number = 0;

private async loadSound() {
  const context = getContext(this) as common.UIAbilityContext;
  const fd = context.resourceManager.getRawFdSync(`medias/${this.soundOptions[this.selectedSoundIndex]}`);
  this.soundId = await this.soundPool.load(
    fd.fd,
    fd.offset,
    fd.length
  );
}
  1. 視覚的なヒント効果を最適化する

ユーザー体験を向上させるために、視覚的なヒント効果をさらに最適化することができます。例えば、アニメーション効果を追加したり、ヒントの色を変更することができます。

Circle()
  .width(200)
  .height(200)
  .fill(this.flashActive ? Color.Red : Color.White)
  .margin({ bottom: 40 })
  .animation({ duration: 100, curve: Curve.EaseInOut }) // アニメーション効果を追加する

五、まとめ

鴻蒙の SoundPool と関連 API を使用することで、私たちは簡単に強力な運動メトロノームを開発することができます。

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?