-
-
Notifications
You must be signed in to change notification settings - Fork 34
Feat/wave shaper #806
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
maciejmakowski2003
wants to merge
35
commits into
main
Choose a base branch
from
feat/wave-shaper
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Feat/wave shaper #806
Changes from 23 commits
Commits
Show all changes
35 commits
Select commit
Hold shift + click to select a range
e045715
feat: draft
736a2de
fix: nitpicks
8814752
feat: working for none oversample
47f4543
ci: lint
7abeec3
feat: implemented up and down sampling
5a0e0f8
feat: added web support
dfd8482
docs: draft
127a972
chore: tests draft for wave shaper and resampler
6b8f30d
refactor: few nitpicks
60e138b
feat: improvements
dbb0985
fix: nitpick
16c79b5
ci: format
42d7348
Merge branch 'main' into feat/wave-shaper
2f19187
ci: format
7b76db6
ci: format
baf7a5a
chore: update Web Audio API coverage table
fff55a6
fix: fixed tests
97d047f
ci: format
2eca4c7
refactor: simd optimizations
5ff8d43
test: added tests
5988060
feat: added example for wave shaper node
7284cdc
docs: finished docs
1af8d2f
fix: nitpicks
c349d9c
fix: fixed assignment of null to WaveShaperNode curve property
89d74bb
refactor: added requested changes
0ed84c4
refactor: requested changes applied and improvements made
3892145
fix: nitpick
04a46df
fix: nitpick
3b3a61a
test: part of resampler tests
d45ac50
test: implemented resamplers process testa
94ea611
ci: lint
b24deb3
Merge branch 'main' into feat/wave-shaper
0ae8af3
chore: requested changes
d49bdce
Merge branch 'main' into feat/wave-shaper
4cd5588
chore: requested changes
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| import React, { useCallback, useEffect, useState, FC } from 'react'; | ||
| import { ActivityIndicator } from 'react-native'; | ||
| import { | ||
| AudioContext, | ||
| AudioNode, | ||
| AudioBuffer, | ||
| AudioBufferSourceNode, | ||
| } from 'react-native-audio-api'; | ||
| import { Container, Button } from '../../components'; | ||
| import { presetEffects } from '../../utils/effects'; | ||
|
|
||
| // const URL = | ||
| // 'http://localhost:3000/react-native-audio-api/audio/music/guitar-sample.flac'; | ||
|
|
||
| const URL = | ||
| 'https://software-mansion.github.io/react-native-audio-api/audio/voice/example-voice-01.mp3'; | ||
|
|
||
| const Distorted: FC = () => { | ||
| const [isPlaying, setIsPlaying] = useState(false); | ||
| const [isLoading, setIsLoading] = useState(false); | ||
| const [buffer, setBuffer] = useState<AudioBuffer | null>(null); | ||
|
|
||
| const aCtxRef = React.useRef<AudioContext | null>(null); | ||
| const effectsMap = React.useRef<Map<string, AudioNode> | null>(null); | ||
| const sourceNodeRef = React.useRef<AudioBufferSourceNode | null>(null); | ||
|
|
||
| const fetchAudioBuffer = useCallback(async () => { | ||
| setIsLoading(true); | ||
|
|
||
| if (!aCtxRef.current) { | ||
| aCtxRef.current = new AudioContext(); | ||
| } | ||
| const audioContext = aCtxRef.current; | ||
|
|
||
| effectsMap.current = presetEffects.distorted(audioContext); | ||
|
|
||
| const audioBuffer = await fetch(URL, { | ||
| headers: { | ||
| 'User-Agent': | ||
| 'Mozilla/5.0 (Android; Mobile; rv:122.0) Gecko/122.0 Firefox/122.0', | ||
| }, | ||
| }) | ||
| .then((response) => response.arrayBuffer()) | ||
| .then((arrayBuffer) => audioContext.decodeAudioData(arrayBuffer)) | ||
| .catch((error) => { | ||
| console.error('Error decoding audio data source:', error); | ||
| return null; | ||
| }); | ||
|
|
||
| setBuffer(audioBuffer); | ||
|
|
||
| setIsLoading(false); | ||
| }, []); | ||
|
|
||
| const togglePlayPause = useCallback(async () => { | ||
| if (!aCtxRef.current) { | ||
| return; | ||
| } | ||
|
|
||
| if (buffer === null) { | ||
| fetchAudioBuffer(); | ||
| return; | ||
| } | ||
|
|
||
| if (isPlaying) { | ||
| sourceNodeRef.current?.stop(); | ||
| } else { | ||
| await aCtxRef.current.resume(); | ||
| sourceNodeRef.current = aCtxRef.current.createBufferSource(); | ||
| sourceNodeRef.current.buffer = buffer; | ||
|
|
||
| let previousNode: AudioNode = sourceNodeRef.current; | ||
| effectsMap.current?.forEach((node) => { | ||
| previousNode.connect(node); | ||
| previousNode = node; | ||
| }); | ||
|
|
||
| previousNode.connect(aCtxRef.current.destination); | ||
|
|
||
| sourceNodeRef.current.start(); | ||
| } | ||
|
|
||
| setIsPlaying((prev) => !prev); | ||
| }, [isPlaying, buffer, fetchAudioBuffer]); | ||
|
|
||
| useEffect(() => { | ||
| fetchAudioBuffer(); | ||
|
|
||
| return () => { | ||
| aCtxRef.current?.close(); | ||
| aCtxRef.current = null; | ||
| }; | ||
| }, [fetchAudioBuffer]); | ||
|
|
||
| return ( | ||
| <Container centered> | ||
| {isLoading && <ActivityIndicator color="#FFFFFF" />} | ||
| <Button | ||
| title={isPlaying ? 'Stop' : 'Play'} | ||
| onPress={togglePlayPause} | ||
| disabled={isLoading} | ||
| /> | ||
| </Container> | ||
| ); | ||
| }; | ||
|
|
||
| export default Distorted; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export { default } from './Distorted'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,157 @@ | ||
| import { | ||
| AudioContext, | ||
| GainNode, | ||
| BiquadFilterNode, | ||
| ConvolverNode, | ||
| WaveShaperNode, | ||
| AudioNode, | ||
| } from 'react-native-audio-api'; | ||
|
|
||
| export function createGainEffect( | ||
| audioContext: AudioContext, | ||
| gain: number = 1.0 | ||
| ): GainNode { | ||
| const gainNode = audioContext.createGain(); | ||
| gainNode.gain.setValueAtTime(gain, audioContext.currentTime); | ||
| return gainNode; | ||
| } | ||
|
|
||
| export function createLowPassFilter( | ||
| audioContext: AudioContext, | ||
| frequency: number = 1000 | ||
| ): BiquadFilterNode { | ||
| const filter = audioContext.createBiquadFilter(); | ||
| filter.type = 'lowpass'; | ||
| filter.frequency.setValueAtTime(frequency, audioContext.currentTime); | ||
| filter.Q.setValueAtTime(1, audioContext.currentTime); | ||
| return filter; | ||
| } | ||
|
|
||
| export function createHighPassFilter( | ||
| audioContext: AudioContext, | ||
| frequency: number = 300 | ||
| ): BiquadFilterNode { | ||
| const filter = audioContext.createBiquadFilter(); | ||
| filter.type = 'highpass'; | ||
| filter.frequency.setValueAtTime(frequency, audioContext.currentTime); | ||
| filter.Q.setValueAtTime(1, audioContext.currentTime); | ||
| return filter; | ||
| } | ||
|
|
||
| export function createSimpleReverb( | ||
| audioContext: AudioContext, | ||
| roomSize: number = 0.5, | ||
| decayTime: number = 2 | ||
| ): ConvolverNode { | ||
| const convolver = audioContext.createConvolver(); | ||
|
|
||
| const sampleRate = audioContext.sampleRate; | ||
| const length = sampleRate * decayTime; | ||
| const impulse = audioContext.createBuffer(2, length, sampleRate); | ||
|
|
||
| for (let channel = 0; channel < 2; channel++) { | ||
| const channelData = impulse.getChannelData(channel); | ||
| for (let i = 0; i < length; i++) { | ||
| const decay = Math.pow(1 - i / length, 2); | ||
| channelData[i] = (Math.random() * 2 - 1) * decay * roomSize; | ||
| } | ||
| } | ||
|
|
||
| convolver.buffer = impulse; | ||
| return convolver; | ||
| } | ||
|
|
||
| export function createOverdrive( | ||
| audioContext: AudioContext, | ||
| amount: number = 0.5 | ||
| ): WaveShaperNode { | ||
| const waveShaper = audioContext.createWaveShaper(); | ||
|
|
||
| const samples = 44100; | ||
| const curve = new Float32Array(samples); | ||
|
|
||
| const clampedAmount = Math.max(0, Math.min(1, amount)); | ||
| const drive = 2 + clampedAmount * 30; | ||
|
|
||
| for (let i = 0; i < samples; i++) { | ||
| const x = (i * 2) / samples - 1; | ||
| const driven = x * drive; | ||
|
|
||
| let distorted; | ||
| if (driven > 0) { | ||
| distorted = Math.tanh(driven * 1.5) * 0.8; | ||
| } else { | ||
| distorted = Math.tanh(driven * 1.2) * 0.9; | ||
| } | ||
|
|
||
| const harmonics = Math.sin(driven * 3) * 0.1 * clampedAmount; | ||
|
|
||
| curve[i] = Math.max(-1, Math.min(1, distorted + harmonics)) * 3; | ||
| } | ||
|
|
||
| waveShaper.curve = curve; | ||
| waveShaper.oversample = '4x'; | ||
|
|
||
| return waveShaper; | ||
| } | ||
|
|
||
| export function createBandPassFilter( | ||
| audioContext: AudioContext, | ||
| lowFreq: number = 800, | ||
| highFreq: number = 3000 | ||
| ): BiquadFilterNode { | ||
| const filter = audioContext.createBiquadFilter(); | ||
| filter.type = 'bandpass'; | ||
|
|
||
| const centerFreq = Math.sqrt(lowFreq * highFreq); | ||
| filter.frequency.setValueAtTime(centerFreq, audioContext.currentTime); | ||
|
|
||
| const Q = centerFreq / (highFreq - lowFreq); | ||
| filter.Q.setValueAtTime(Q, audioContext.currentTime); | ||
|
|
||
| return filter; | ||
| } | ||
|
|
||
| export function createEffectsMap( | ||
| effects: { name: string; node: AudioNode }[] | ||
| ): Map<string, AudioNode> { | ||
| const effectsMap = new Map<string, AudioNode>(); | ||
|
|
||
| effects.forEach(({ name, node }) => { | ||
| effectsMap.set(name, node); | ||
| }); | ||
|
|
||
| return effectsMap; | ||
| } | ||
|
|
||
| export const presetEffects = { | ||
| ambient: (audioContext: AudioContext) => | ||
| createEffectsMap([ | ||
| { name: 'reverb', node: createSimpleReverb(audioContext, 0.3, 1.5) }, | ||
| { name: 'lowpass', node: createLowPassFilter(audioContext, 8000) }, | ||
| ]), | ||
|
|
||
| warm: (audioContext: AudioContext) => | ||
| createEffectsMap([ | ||
| { name: 'lowpass', node: createLowPassFilter(audioContext, 3000) }, | ||
| { name: 'gain', node: createGainEffect(audioContext, 1.2) }, | ||
| ]), | ||
|
|
||
| distorted: (audioContext: AudioContext) => | ||
| createEffectsMap([ | ||
| { name: 'overdrive', node: createOverdrive(audioContext, 0.85) }, | ||
| { name: 'midpass', node: createBandPassFilter(audioContext, 800, 3000) }, | ||
| { name: 'lowpass', node: createLowPassFilter(audioContext, 6000) }, | ||
| { name: 'gain', node: createGainEffect(audioContext, 0.4) }, | ||
| ]), | ||
|
|
||
| test: (audioContext: AudioContext) => | ||
| createEffectsMap([ | ||
| { name: 'gain', node: createGainEffect(audioContext, 0.3) }, | ||
| ]), | ||
|
|
||
| overdrive_only: (audioContext: AudioContext) => | ||
| createEffectsMap([ | ||
| { name: 'overdrive', node: createOverdrive(audioContext, 0.9) }, | ||
| ]), | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| --- | ||
| sidebar_position: 6 | ||
| --- | ||
|
|
||
| import AudioNodePropsTable from "@site/src/components/AudioNodePropsTable" | ||
| import { ReadOnly } from '@site/src/components/Badges'; | ||
|
|
||
| # WaveShaperNode | ||
|
|
||
| The `WaveShaperNode` interface represents non-linear signal distortion effects. | ||
| Non-linear distortion is commonly used for both subtle non-linear warming, or more obvious distortion effects. | ||
|
|
||
| #### [`AudioNode`](/docs/core/audio-node#properties) properties | ||
|
|
||
| <AudioNodePropsTable numberOfInputs={1} numberOfOutputs={1} channelCount={2} channelCountMode={"max"} channelInterpretation={"speakers"} /> | ||
|
|
||
| ## Constructor | ||
|
|
||
| [`BaseAudioContext.createWaveShaper()`](/docs/core/base-audio-context#createwaveshaper) | ||
|
|
||
| ## Properties | ||
|
|
||
| It inherits all properties from [`AudioNode`](/docs/core/audio-node#properties). | ||
|
|
||
| | Name | Type | Description | | ||
| | :--: | :--: | :---------- | | ||
| | `curve` | `Float32Array \| null` | The shaping curve used for waveshaping effect. | | ||
| | `oversample` | [`OverSampleType`](/docs/effects/wave-shaper-node#oversampletype) | Specifies what type of oversampling should be used when applying shaping curve. | | ||
|
|
||
| ## Methods | ||
|
|
||
| `WaveShaperNode` does not define any additional methods. | ||
| It inherits all methods from [`AudioNode`](/docs/core/audio-node#methods). | ||
|
|
||
| ## Remarks | ||
|
|
||
| #### `curve` | ||
| - Default value is null | ||
| - Contains at least two values. | ||
| - Subsequent modifications of curve have no effects. To change the curve, assign a new Float32Array object to this property. | ||
|
|
||
| #### `oversample` | ||
| - Default value `none` | ||
| - Value of `2x` or `4x` can increases quality of the effect, but in some cases it is better not to use oversampling for very accurate shaping curve. | ||
|
|
||
| ### `OverSampleType` | ||
|
|
||
| <details> | ||
|
|
||
| **Acceptable values:** | ||
| - `none` | ||
|
|
||
| Do not oversample. | ||
|
|
||
| - `2x` | ||
|
|
||
| Oversample two times. | ||
|
|
||
| - `4x` | ||
|
|
||
| Oversample four times. | ||
|
|
||
| </details> | ||
maciejmakowski2003 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file not shown.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.