Learn R Programming

⚠️There's a newer version (2.7.3) of this package.Take me there.

soundgen readme

R package for sound synthesis and acoustic analysis.
Homepage with help, demos, etc: http://cogsci.se/soundgen.html
Source code on github: https://github.com/tatters/soundgen

Performs parametric synthesis of sounds with harmonic and noise components such as animal vocalizations or human voice. Also includes tools for spectral analysis, pitch tracking, audio segmentation, self-similarity matrices, morphing, etc.

Key functions

  • Sound synthesis from R console: soundgen()
  • Shiny app for sound synthesis (opens in a browser): soungen_app()
  • Acoustic analysis of a wav/mp3 file: analyze()
  • Shiny app for editing intonation contours (opens in a browser): pitch_app()
  • Measuring syllables, pauses, and bursts in a wav/mp3 file: segment()

For more information, please see the vignettes on sound synthesis and acoustic analysis:

vignette("sound_generation", package="soundgen")

vignette("acoustic_analysis", package="soundgen")

Or, to open the vignettes in a browser:
RShowDoc('sound_generation', package = 'soundgen')

RShowDoc('acoustic_analysis', package = 'soundgen')

Example of sound synthesis

Use the soundgen() function to create a breathy moan:

s = soundgen(
  sylLen = 230,               # duration of voiced part, ms
  pitch = c(305, 280),        # pitch, Hz (goes down from 305 to 380 Hz)
  ampl = c(0, -20),           # amplitude, dB (gradual fade-out by 20 dB)
  rolloff = -30,              # strong f0, weak harmonics
  temperature = 0.05,         # some stochasticity in generation
  formants = c(260, 960, 1500, 2200,  # F1-F8 formant frequencies, Hz
               2600, 3600, 4200, 4500),
  noise = data.frame(
    time = c(-50, 120, 700),  # time of noise anchors
    value = c(-15, -5, -50)   # noise amplitude, dB
  ),
  rolloffNoise = 0,           # flat noise spectrum before adding formants
  addSilence = 0, samplingRate = 44100, pitchSamplingRate = 44100,
  play = TRUE, plot = TRUE, osc = TRUE, ylim = c(0, 6)
)

Example of acoustic analysis

Use the analyze() function to detect pitch and obtain other spectral descriptives of the sound we have just synthesized:

a = analyze(s, 44100, plot = TRUE, ylim = c(0, 6))
a$detailed[1:5, c('pitch', 'peakFreq', 'harmHeight', 'HNR', 'ampl', 'loudness')]
#>      pitch peakFreq harmHeight       HNR       ampl loudness
#> 1       NA       NA         NA        NA 0.02993491       NA
#> 2 291.4030 300.1361   582.8060  5.743706 0.19258955 11.19230
#> 3 293.9992 300.1361   881.9977 13.480664 0.41832141 18.21197
#> 4 293.8760 300.1361   881.9977 13.757051 0.53108777 22.46051
#> 5 292.1780 300.1361  1753.0680 12.266983 0.49117243 21.69834
colnames(a$detailed)
#>  [1] "duration"           "duration_noSilence" "time"               "amDep"             
#>  [5] "amDepVoiced"        "amFreq"             "amFreqVoiced"       "ampl"              
#>  [9] "amplVoiced"         "dom"                "domVoiced"          "entropy"           
#> [13] "entropyVoiced"      "epoch"              "f1_freq"            "f1_width"          
#> [17] "f2_freq"            "f2_width"           "f3_freq"            "f3_width"          
#> [21] "flux"               "harmEnergy"         "harmHeight"         "HNR"               
#> [25] "HNRVoiced"          "loudness"           "loudnessVoiced"     "novelty"           
#> [29] "noveltyVoiced"      "peakFreq"           "peakFreqVoiced"     "pitch"             
#> [33] "quartile25"         "quartile25Voiced"   "quartile50"         "quartile50Voiced"  
#> [37] "quartile75"         "quartile75Voiced"   "roughness"          "roughnessVoiced"   
#> [41] "specCentroid"       "specCentroidVoiced" "specSlope"          "specSlopeVoiced"   
#> [45] "subDep"             "subRatio"           "voiced"

Installation

To install the current release from CRAN: install.packages("soundgen")

NB: Make sure all dependencies have been installed correctly! For problems with seewave, see https://rug.mnhn.fr/seewave/

On Macs, you may need to do the following:

  • First install brew according to the instructions here: https://brew.sh/
  • Then run the following from the terminal
    brew install libsndfile
    brew install fftw
  • Finally, install soundgen in R:
    install.packages("soundgen")

Copy Link

Version

Install

install.packages('soundgen')

Monthly Downloads

623

Version

2.6.0

License

GPL (>= 2)

Maintainer

Andrey Anikin

Last Published

May 22nd, 2023

Functions in soundgen (2.6.0)

Mode

Modified mode
addAM

Add amplitude modulation
ERBToHz

Convert Hz to ERB rate
addVectors

Add overlapping vectors
addFormants

Add formants
analyze

Acoustic analysis
addPitchCands

Plot pitch candidates
HzToSemitones

Convert Hz to semitones
HzToNotes

Convert Hz to notes
HzToERB

Convert Hz to ERB rate
audSpectrogram

Auditory spectrogram
compareSounds

Compare two sounds
convertStringToFormants

Prepare a list of formants
clumper

Clump a sequence into large segments
annotation_app

Annotation app
analyzeFrame

Analyze fft frame
checkInputType

Check audio input type
costPerPath

Cost per path
defaults

Shiny app defaults
defaults_analyze

Defaults and ranges for analyze()
beat

Generate beat
bandpass

Bandpass/stop filters
crossFade

Join two waveforms by cross-fading
costJumps

Cost of jumps
convert_sec_to_hms

Print time
.bandpass

Bandpass filter per sound
detectNLP_training_nonv

Nonlinear phenomena: Naive Bayes classifier trained on human nonverbal vocalizations
.detectNLP

Detect NLP per sound
detectNLP_training_synth

Nonlinear phenomena: Naive Bayes classifier trained on synthetic sounds
dPhase

Phase derivatives
detectPitchJumps

Detect pitch jumps
detectNLP

Detect NLP
def_form

Defaults and ranges for formant_app()
averageMatrices

Average matrices
defaults_analyze_pitchCand

Defaults for plotting with analyze()
.addAM

Add AM to a sound
divideIntoSyllables

Syllable structure of a bout
.getPitchZc

Zero-crossing rate per sound
.fade

Fade per sound
.addFormants

Add formants per sound
.flatEnv

Flat envelope per sound
.segment

Internal soundgen function
.shiftFormants

Shift formants per sound
.modulationSpectrum

Modulation spectrum per sound
.getSurprisal

Get surprisal per sound
.shiftPitch

Shift pitch per sound
.getRMS

RMS amplitude per sound
.analyze

Analyze per sound
.filterSoundByMS

Filter a single sound by MS
.audSpectrogram

Auditory spectrogram per sound
.flatSpectrum

Flat spectrum per sound
.phasegram

Phasegram per sound
.osc

Oscillogram per sound
estimateVTL

Estimate vocal tract length
drawContour

Draw contour
.spectrogram

Spectrogram per sound
.getLoudness

Loudness per sound
.getDuration

Get duration per sound
.pitchDescriptives

Pitch descriptives per file
.prosody

Prosody per sound
.resample

Resample per sound
.ssm

SSM per sound
fade

Fade
filterMS

Filter modulation spectrum
evaluatePars

Evaluate parameters for optimization
findGrad

Find gradient
.reverb

Add reverb to a sound
.timeStretch

Time stretch per sound
findBursts

Find bursts
findElbow

Find the elbow of a screeplot or similar
filterSoundByMS

Filter sound by modulation spectrum
findSyllables

Find syllables
gaussianSmooth2D

Gaussian smoothing in 2D
findZeroCrossing

Find zero crossing
findVoicedSegments

Find voiced segments
generateEpoch

Generate an epoch
flatEnv

Flat envelope / compressor
generateNoise

Generate noise
getCPP

Get Cepstral Peak Prominence
findInflections

Find inflections
getFeatureFlux

Get flux from features
generatePath

Generate path
getBandwidth

Get bandwidth
getFormantDispersion

Get formant dispersion
fart

Fart
filled.contour.mod

Modified filled.contour
getPeakFreq

Get peak frequency
getNovelty

SSM novelty
formant_app

Interactive formant tracker
getPitchAutocor

Autocorrelation pitch tracker
getEntropy

Entropy
getEnv

Get amplitude envelope
getLoudnessPerFrame

Get loudness per frame
formatPitchManual

Format pitchManual
getPrior

Get prior for pitch candidates
getPitchZc

Zero-crossing rate
getMelSpec

Mel-transformed spectrogram
getPitchHps

Harmonic product spectrum
getPitchCep

Cepstral pitch tracker
flatSpectrum

Flat spectrum
forcePerPath

Force per path
getSigmoid

Get sigmoid filter
getSurprisal_matrix

Get surprisal per matrix
getAM

Get amplitude modulation
getIntegerRandomWalk

Discrete random walk
getLoudness

Get loudness
getRMS

RMS amplitude
guessPhase_GL

Guess phase GL
getSmoothContour

Smooth contour from anchors
guessPhase_spsi

Guess phase SPSI
generateGC

Generate glottal cycles
getAM_env

Get Amplitude Modulation
generateHarmonics

Generate harmonics
getDom

Get lowest dominant frequency band
getPitchSpec

BaNa pitch tracker
getSurprisal_vector

Get surprisal per vector
getDuration

Get duration
getRolloff

Control rolloff of harmonics
identifyAndPlay

Identify and play
hz2mel

Hz to mel
interpolate

Interpolate
interpolMatrix

Interpolate matrix
hillenbrand

Formants in American vowels
listDepth

List depth
killDC

Kill DC
htmlPlots

HTML for clickable plots
getRandomWalk

Random walk
invertSpectrogram

Invert spectrogram
intplNA

Interpolate NAs
getSpectralFlux

Get spectral flux
matchPars

Match soundgen pars (experimental)
getSurprisal

Get surprisal
harmEnergy

Energy in harmonics
medianSmoother

Median smoothing
morphFormants

Morph formants
modulationSpectrum

Modulation spectrum
getRough

Get roughness
harmHeight

Height of harmonics
morphList

Morph lists
getDiscreteContour

Discrete smooth contour from anchors
getFrameBank

Frame bank
getCheckerboardKernel

Checkerboard kernel
naiveBayes_train

Train a naive Bayes classifier
modulationSpectrumFragment

Modulation spectrum per fragment
getVocalFry_per_epoch

Constant subharmonics regime
iso226

iso226
nonLinearPrediction_mod

Nonlinear prediction modified
getVocalFry

Subharmonics
istft_mod

Modified istft
getGlottalCycles

Divide f0 contour into glottal cycles
matchColumns

Match number of columns
getSmoothSpectrum

Get smooth spectrum
normalizeFolder

Normalize folder
notesDict

Conversion table from Hz to musical notation
matchLengths

Resize vector to required length
pathfinder

Pathfinder
getSpectralEnvelope

Spectral envelope
log01

log01
lockToFormants

Lock to formants
harmHeight_dif

Height of harmonics: difference method
harmHeight_peaks

Height of harmonics: peaks method
nonlinPred

Nonlinear prediction
logMatrix

Log-warp matrix
nonlinStats

Nonlinear statistics
isCentral.localMax

Simple peak detection
phasePropagate

Propagate phase
naiveBayes

Naive Bayes
pathfinding_fast

Path through pitch candidates: fast
msToSpec

Modulation spectrum to spectrogram
parabPeakInterpol

Parabolic peak interpolation
phasegram

Phasegram
pitchSmoothPraat

Pitch smoothing as in Praat
pDistr

Proportion of total
isNeighbour_mod

Is neighbor modified
logistic

Logistic
plotSpec

Plot spectrogram
logWarpMS

Log-warp a modulation spectrum
pitchDescriptives

Pitch descriptives
prosody

Prosody
reportTime

Report time
pseudoLog

Pseudolog
naiveBayes_dynamicPrior

Naive Bayes dynamic prior
logit

Logit
resample

Resample a vector
pitch_app

Interactive pitch tracker
reverb

Reverb & echo
scaleSPL

Scale SPL
schwa

Schwa-related formant conversion
notesToHz

Convert notes to Hz
naiveBayes_likelihood

Naive Bayes likelihood
phon2sone

Convert phon to sone
objectToString

Object to string
pitchContour

Manually corrected pitch contours in 260 sounds
presets

Presets
rnorm_truncated

Random draw from a truncated normal distribution
segment

Segment a sound
segmentManual

Manual counts of syllables in 260 sounds
playme

Play audio
plotMS

Plot modulation spectrum
princarg

Principal argument
processAudio

Process audio
semitonesToHz

Convert semitones to Hz
pitchManual

Manual pitch estimation in 260 sounds
pseudoLog_undo

Undo pseudolog
soundgen

Generate a sound
selfsim

Compute self-similarity
sampleModif

sampleModif
readAudio

Read audio
reformatFormants

Reformat formants
rbind_fill

rbind_fill
reportCI

Report CI
morph

Morph sounds
spreadSpec

Spread spectrum
reformatAnchors

Reformat anchors
ssm

Self-similarity matrix
scaleNoiseAnchors

Scale noise anchors
shiftFormants

Shift formants
shiftPitch

Shift pitch
splitIntoChunks

Split vector into chunks
splitContour

Split contour
to_dB

Convert to dB
transplantEnv

Transplant envelope
transplantFormants

Transplant formants
silenceSegments

Silence sound segments
timeStretch

Time stretch
soundgen_app

Interactive sound synthesizer
wigglePars

Wiggle parameters
summarizeAnalyze

Summarize the output of analyze()
snake

Snake
validatePars

Validate parameters
subhToHarm

Subharmonics-to-harmonics ratio
morphDF

Morph dataframes
optimizePars

Optimize parameters for acoustic analysis
warpMatrix

Warp matrix
upsampleGC

Upsample glottal cycles
updateAnalyze

Update analyze
writeAudio

Write audio
wiggleAnchors

Randomly modify anchors
wiggleGC

Wiggle glottal cycles
osc

Oscillogram
specToMS

Spectrogram to modulation spectrum
pathfinding_slow

Path through pitch candidates: slow
permittedValues

Defaults and ranges for soundgen()
spectrogram

Spectrogram
timeSeriesSummary

Time series summary
switchColorTheme

Switch color theme
zeroOne

Normalize 0 to 1