7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【ReactNative】【Expo】画面遷移のタイミングで音を鳴らす方法

Last updated at Posted at 2020-04-12

アプリを作っている途中で、画面遷移の時に音がなるとより本格的になるなーと思ったものの、調べてもすぐ出てこなかったのでメモしておきます。

音がなる前のコード

...

<TouchableOpacity 
  onPress={() => navigate('Home')}>
  <Text>ホーム</Text>
</TouchableOpacity>

onPressのタイミングで音を鳴らす関数を発火したいのですが、すでに画面遷移のための関数が割り当てられていています。
よって、画面遷移と音を鳴らす役割を担う関数を外で定義しないといけません。

音がなるコード

...

import { Audio } from 'expo-av';

...

async function goto(destination){
  navigate(destination)
  try {
    const soundObject = new Audio.Sound();
    await soundObject.loadAsync(require('./assets/sounds/decision.mp3'));
    await soundObject.playAsync();
  } 
  catch (error) {
    console.log('error...')
  }
}

....

<TouchableOpacity 
  onPress={() => goto('Home')}>
  <Text>ホーム</Text>
</TouchableOpacity>

補足

ReactNativeで音を鳴らすのはexpo-avが一番簡単だと思います。
音源は効果音ラボから拾ってきました。

作成したgoto関数を繰り返し使うために、navigateで設定する値を引数で渡しましたが、【React】イベントハンドラで引数を使いたい【備忘録】の方法1にある記述のように、ベストな方法ではないようです。
とりあえず動いたのでここまでにします。

ファイルを編集する度にポロン♪と鳴るのでモチベーションも上がりますね。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?