[英]Can't set up beep sound in React.js
我想在我的 React.js 应用程序中设置哔声。 我关注了这篇文章,但是尽管我单击了按钮,但它却没有发出声音。
import UIfx from "uifx";
class App extends Component {
render() {
const mp3file = `${process.env.PUBLIC_URL}/assets/sound/alert.mp3`;
const sound = new UIfx({ asset: mp3file });
sound.setVolume(0.8);
console.log("sound", sound);
return() {
<button onClick={sound.play}>Signup</button>
}
}
}
声音表演是这样的:
UIfx {file: {…}, volume: 0.8, throttleMs: 0, play: ƒ, setVolume: ƒ, …}
play: ƒ (volume)
setVolume: ƒ (volume)
file: {asset: "/assets/sound/alert.mp3"}
volume: 0.8
throttleMs: 0
validateVolume: ƒ validateVolume(volume)
__proto__: Object
我在下面有一个错误:
未捕获的错误:“音量”必须是介于 0.0 和 1.0 之间的数字
哦,这是一个微妙的!
请注意,记录的sound
对象表明play
函数采用名为volume
: play: ƒ (volume)
。 请记住, onClick
将事件作为参数传递。 所以既然直接传了 play 函数,其实就等价于onClick={e => sound.play(e)}
!
请尝试以下操作:
return() {
<button onClick={() => sound.play()}>Signup</button>
}
您的代码有两个问题。
第一个是 UIFx 构造函数不接受您的对象,您应该改为执行new UIFx(mp3file)
。
第二个是onClick={sound.play}
- this
将被设置为元素引用并会导致问题,你应该做的是onClick={() => sound.play()}
。
我也在寻找一种简单的方法来发出哔哔声,并很高兴分享我的发现。 我发现新的 AudioContext很轻。 Mozilla音频上下文。 参考: 我们的代码世界。 对我来说,这有效:
const addToCart = () => {
function beep(duration, frequency, volume) {
return new Promise((resolve, reject) => {
// Set default duration if not provided
duration = duration || 200;
frequency = frequency || 440;
volume = volume || 100;
try {
let oscillatorNode = myAudioContext.createOscillator();
let gainNode = myAudioContext.createGain();
oscillatorNode.connect(gainNode);
// Set the oscillator frequency in hertz
oscillatorNode.frequency.value = frequency;
// Set the type of oscillator
oscillatorNode.type = "square";
gainNode.connect(myAudioContext.destination);
// Set the gain to the volume
gainNode.gain.value = volume * 0.01;
// Start audio with the desired duration
oscillatorNode.start(myAudioContext.currentTime);
oscillatorNode.stop(myAudioContext.currentTime + duration * 0.001);
// Resolve the promise when the sound is finished
oscillatorNode.onended = () => {
resolve();
};
} catch (error) {
reject(error);
});
}
}
当您拨打 function 之类的哔哔声时,您将听到“本机哔哔声” - 如果我错了,请纠正我。
beep(
// Set the duration to 0.2 second (200 milliseconds)
200,
// Set the frequency of the note to A4 (440 Hz)
440,
// Set the volume of the beep to 100%
100
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.