useState() causes unexpected behaviour with audio object

Simon

I'm trying to create a basic audio player and keeping track of the player state using the state hook.

The following code creates a component with the following behaviour:

  1. First time the button is pressed audio plays
  2. Every time the button is pressed the text toggles correctly
  3. When state is playing, calling player.pause() does nothing
  4. When state is not playing, audio continues and calling player.play() causes a second layer of audio to start on top
    import React, {useState} from 'react'
    
    function InlinePlayer ({audio}) {
      const [playing, setPlaying] = useState(false)
    
      const player = new Audio(audio.asset.url)
    
      function togglePlay () {
        playing ? player.pause() : player.play()
        setPlaying(!playing)
      }
    
      return <>
        <button onClick={() => togglePlay()}>
          {playing ? 'Stop' : 'Play' }
        </button>
      </>
    }
    
    export default InlinePlayer

If I don't use the state hook at all I can stop and start the audio without issues.

One strange thing is that even if I call play() unconditionally and then call the state hook, subsequent calls to pause() also don't work anymore. It's as if calling setPlaying() destroys the connection to the player object. If I comment out the setPlaying line, it works.

  function play () {
    player.play()
    setPlaying(true)
  }

  function pause () {
    player.pause()
    setPlaying(false)
  }

I initially thought the problem was that the state was being set asynchronously so the conditional play was the culprit. What seems to be up here?

Sam R.

player.pause() and player.play() are like side effects. Use useEffect with proper cleanup function so you can toggle the play/pause:

import React, { useState, useEffect } from "react";

function InlinePlayer({ audio }) {
  const [playing, setPlaying] = useState(false);

  const player = new Audio(
    "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
  );

  useEffect(() => {
    playing ? player.play() : player.pause();

    // This is cleanup of the effect
    return () => player.pause();

  }, [playing]);
   // ^ Run the effect every time the `playing` is changed

  function togglePlay() {
    // Using the callback version of `setState` so you always
    // toggle based on the latest state
    setPlaying(s => !s);
  }

  return (
    <>
      <button onClick={() => togglePlay()}>{playing ? "Stop" : "Play"}</button>
    </>
  );
}

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Entity Framework adding object to collection results in unexpected behaviour

分類Dev

Unexpected behaviour in bash redirection

分類Dev

Unexpected behaviour of rootDir and outDir

分類Dev

Unexpected quicksort behaviour in R

分類Dev

Unexpected task cancellation behaviour

分類Dev

Unexpected static counter variable behaviour

分類Dev

C# Unexpected Property Behaviour

分類Dev

Lambda causes unexpected token

分類Dev

Unexpected behaviour when _.allKeys(obj) array(say var arr) is referred to object :obj.arr[0], it returns undefined

分類Dev

Unexpected behaviour in test with fakeAsync(), NgModel and detectChanges()

分類Dev

Variadic template and std::array unexpected behaviour

分類Dev

Trust Zone on Raspberry Pi unexpected behaviour?

分類Dev

Python unexpected (to me) behaviour when deleting lists

分類Dev

React Hooks useState()with Object

分類Dev

Can Value Object have behaviour?

分類Dev

Inconsistent behaviour of object method 'hasOwnProperty'

分類Dev

Testing of spring batch job causes unexpected results

分類Dev

One function causes irregular behaviour of another function afterwards

分類Dev

Unexpected behaviour from applying np.isin() on a pandas dataframe

分類Dev

Combine & SwiftUI with a custom Publisher - unexpected behaviour when using .assign subscriber

分類Dev

Unexpected behaviour of grid items using justify-content property

分類Dev

Unexpected behaviour of hash function when using set in a class

分類Dev

React useState with Typescript for setting a nested typed object

分類Dev

Web audio api unexpected syntax token, Sound won't play

分類Dev

Unexpected indentation behaviour when I set the terminal to raw mode – why is this happening?

分類Dev

Why isn't it undefined behaviour to destroy an object that was overwritten by placement new?

分類Dev

Unexpected convert numeric to string on object create in typescript

分類Dev

convert string to JSON object throws Unexpected token

分類Dev

Unexpected token 'this' while creating method inside object

Related 関連記事

  1. 1

    Entity Framework adding object to collection results in unexpected behaviour

  2. 2

    Unexpected behaviour in bash redirection

  3. 3

    Unexpected behaviour of rootDir and outDir

  4. 4

    Unexpected quicksort behaviour in R

  5. 5

    Unexpected task cancellation behaviour

  6. 6

    Unexpected static counter variable behaviour

  7. 7

    C# Unexpected Property Behaviour

  8. 8

    Lambda causes unexpected token

  9. 9

    Unexpected behaviour when _.allKeys(obj) array(say var arr) is referred to object :obj.arr[0], it returns undefined

  10. 10

    Unexpected behaviour in test with fakeAsync(), NgModel and detectChanges()

  11. 11

    Variadic template and std::array unexpected behaviour

  12. 12

    Trust Zone on Raspberry Pi unexpected behaviour?

  13. 13

    Python unexpected (to me) behaviour when deleting lists

  14. 14

    React Hooks useState()with Object

  15. 15

    Can Value Object have behaviour?

  16. 16

    Inconsistent behaviour of object method 'hasOwnProperty'

  17. 17

    Testing of spring batch job causes unexpected results

  18. 18

    One function causes irregular behaviour of another function afterwards

  19. 19

    Unexpected behaviour from applying np.isin() on a pandas dataframe

  20. 20

    Combine & SwiftUI with a custom Publisher - unexpected behaviour when using .assign subscriber

  21. 21

    Unexpected behaviour of grid items using justify-content property

  22. 22

    Unexpected behaviour of hash function when using set in a class

  23. 23

    React useState with Typescript for setting a nested typed object

  24. 24

    Web audio api unexpected syntax token, Sound won't play

  25. 25

    Unexpected indentation behaviour when I set the terminal to raw mode – why is this happening?

  26. 26

    Why isn't it undefined behaviour to destroy an object that was overwritten by placement new?

  27. 27

    Unexpected convert numeric to string on object create in typescript

  28. 28

    convert string to JSON object throws Unexpected token

  29. 29

    Unexpected token 'this' while creating method inside object

ホットタグ

アーカイブ