Package 'sonicscrewdriver'

Title: Bioacoustic Analysis and Publication Tools
Description: Provides tools for manipulating sound files for bioacoustic analysis, and preparing analyses these for publication. The package validates that values are physically possible wherever feasible.
Authors: Ed Baker [aut, cre] (ORCID: <https://orcid.org/0000-0002-5887-9543>), Quentin Geissman [ctb]
Maintainer: Ed Baker <[email protected]>
License: GPL-3
Version: 0.0.8.9000
Built: 2026-10-23 19:10:26 UTC
Source: https://github.com/edwbaker/sonicscrewdriver

Help Index


PseudoWave scalar subtraction

Description

PseudoWave scalar subtraction

Usage

## S4 method for signature 'PseudoWave,numeric'
e1 - e2

Arguments

e1

Input 1

e2

Input 2

Value

A PseudoWave object with e2 subtracted from its offset.


Check if two annotations overlap or are continuous

Description

Check if two annotations overlap or are continuous

Usage

.annotation_check_overlap(annotation1, annotation2, domain = "time")

Arguments

annotation1

An Annotation object.

annotation2

An Annotation object.

domain

Domain of the annotations, either "time", "frequency", or "both".

Value

TRUE if the annotations overlap, FALSE otherwise.


Combine annotations helper function

Description

Checks a list of annotations for those that are overlapping in the time or frequency domain, and returns a list where overlapping annotations are merged.

Usage

.merge_annotations(annotations, domain = "time")

Arguments

annotations

A list of Annotation objects.

domain

Domain of the annotations, either "time" or "frequency".

Details

The exported function merge_annotations() handles sanity checks and calls this function.

Value

A list of Annotation objects.


Helper function to convert a Wave-like object to scikit-maad spectrogram

Description

Helper function to convert a Wave-like object to scikit-maad spectrogram

Usage

.spectrogram_maad_power(object)

Arguments

object

A Wave or WaveMC object (or Tagged equivalent), or a spectrogram_maad object

Value

A spectrogram_maad object


Helper function to convert a Wave-like object to scikit-maad spectrum

Description

Helper function to convert a Wave-like object to scikit-maad spectrum

Usage

.spectrum_maad(object)

Arguments

object

A Wave or WaveMC object (or Tagged equivalent), or a spectrum

Value

A spectrum list


Allow subsetting a Wave object with a TimeRegion

Description

Allow subsetting a Wave object with a TimeRegion

Usage

## S4 method for signature 'Wave,TimeRegion'
x[i]

Arguments

x

Wave Object

i

TimeRegion object

Value

A Wave object containing only the samples within the time region.


Numeric multiplication by PseudoWave

Description

Numeric multiplication by PseudoWave

Usage

## S4 method for signature 'numeric,PseudoWave'
e1 * e2

Arguments

e1

Input 1

e2

Input 2

Value

A PseudoWave object with its scale multiplied by e1.


PseudoWave scalar manipulation

Description

PseudoWave scalar manipulation

Usage

## S4 method for signature 'PseudoWave,numeric'
e1 * e2

Arguments

e1

Input 1

e2

Input 2

Value

A PseudoWave object with its scale multiplied by e2.


PseudoWave scalar division

Description

PseudoWave scalar division

Usage

## S4 method for signature 'PseudoWave,numeric'
e1 / e2

Arguments

e1

Input 1

e2

Input 2

Value

A PseudoWave object with its scale divided by e2.


Numeric addition by PseudoWave

Description

Numeric addition by PseudoWave

Usage

## S4 method for signature 'numeric,PseudoWave'
e1 + e2

Arguments

e1

Input 1

e2

Input 2

Value

A PseudoWave object with e1 added to its offset.


PseudoWave scalar addition

Description

PseudoWave scalar addition

Usage

## S4 method for signature 'PseudoWave,numeric'
e1 + e2

Arguments

e1

Input 1

e2

Input 2

Value

A PseudoWave object with e2 added to its offset.


Convert text times of day in audioblast traits to numeric values

Description

This function takes a traits dataset retrieved from audioblast and converts values such as "day" into a numeric time of day based on the date and location.

Usage

ab_diel_traits(traits, date, lat, lon, overwrite = FALSE)

Arguments

traits

Traits dataset retrieved using audioblast().

date

The date used for conversion for time.

lat

Latitude of location.

lon

Longitude of location.

overwrite

If TRUE then the function will overwrite any existing min/max.

Value

The traits data frame, with value_min and value_max converted to numeric times of day.


Add a process to a Tagged Wave or WaveMC object

Description

This function takes a TaggedWave or TaggedWaveMC object and adds a process to the processing slot. This is used to keep a record of the processes that have been applied to the object.

Usage

addProcess(object, process, output = NULL, duration = NULL)

## S4 method for signature 'TaggedWave'
addProcess(object, process, output = NULL, duration = NULL)

## S4 method for signature 'TaggedWaveMC'
addProcess(object, process, output = NULL, duration = NULL)

Arguments

object

An object.

process

A description of the process.

output

The output of the process.

duration

The duration of the process in seconds.

Value

The object with the process added.


Add two spectra from seewave

Description

This function takes two spectra from seewave (or equivalent) and adds their values. The spectra must have the same bins.

Usage

addSpectra(s1, s2, coerceNegative = TRUE)

Arguments

s1

First spectrum

s2

Second spectrum

coerceNegative

Sets any values below zero to zero in output.

Value

A spectrum of s1+s2

Examples

## Not run: 
addSpectra(spec1, spec2)
addSpectra(spec1, spec2, coerceNegative=TRUE)

## End(Not run)

Apply a function to all channels of a Wave or WaveMC object

Description

Some functions (e.g. ffilter from seewave) only operate on a single channel at a time. This function applies the function to each channel and returns a list of analyses.

Usage

allChannels(
  w,
  FUN,
  cl = NULL,
  channel.param = "channel",
  output.FUN = NULL,
  ...
)

Arguments

w

A Wave or WaveMC object

FUN

Function to apply to the wave.

cl

Optionally a cluster for parallel calculation.

channel.param

Name of the channel parameter to FUN. Can be NULL.

output.FUN

Optional. Function that processes the output of FUN. The "channels_se" function provides standard functionality for the soundecology package.

...

Optional. Additional parameters to pass to FUN.

Value

A list with one entry per channel, whatever the class and channel count of the input. Each entry is itself a list.


Create a new Annotation object

Description

Create a new Annotation object

Usage

annotation(
  file = "",
  metadata = list(),
  start = 0,
  end = Inf,
  low = 0,
  high = Inf,
  source = "",
  type = "",
  value = ""
)

Arguments

file

File being annotated.

metadata

A list of metadata.

start

Start time of annotation (seconds).

end

End time of annotation (seconds).

low

Low frequency of annotation (Hz).

high

High frequency of annotation (Hz).

source

Source of annotation.

type

Type of annotation.

value

Value of annotation.

Value

An Annotation object.


A S4 class for annotations

Description

The Annotation class is used to store annotations on Wave-like objects.

Slots

file

File being annotated.

metadata

A list for storing metadata.

start

Start time of annotation.

end

End time of annotation.

low

Low frequency of annotation.

high

High frequency of annotation.

source

Source of annotation.

type

Type of annotation.

value

Value of annotation.


Convert a list of Annotation objects to a data.frame

Description

Converts a list of Annotation objects to a data.frame, with one column for each metadata name in the list.

Usage

AnnotationList2DataFrame(x)

Arguments

x

A list of Annotation objects.

Value

A data.frame.


Calculated size of raw audio files

Description

Calculates the raw size of audio date at set sample rate, bit depth and duration.

Usage

audio_filesize(
  samp.rate = 44100,
  bit.depth = 16,
  channels = 1,
  duration = 1,
  duration.unit = "seconds",
  output.unit = "bits",
  units = "decimal"
)

Arguments

samp.rate

Sample rate

bit.depth

Bit depth

channels

The number of audio channels

duration

Duration of recording

duration.unit

Any unit accepted by convert2seconds(), which is one of seconds, minutes, hours, days, years, HHMM or POSIX.

output.unit

"human", "bits" or "bytes"

units

Units used when output.unit is "human", either "decimal" or "binary". See humanBytes().

Details

The size is given in bits by default. Setting output.unit to "bytes" gives bytes, and to "human" passes the result through humanBytes(), whose choice of decimal or binary units is taken from units.

Value

The size of the audio file in the specified unit

Examples

# One minute of mono 16-bit audio sampled at 44.1kHz
audio_filesize(samp.rate=44100, bit.depth=16, channels=1, duration=1, duration.unit="minutes")

# One year of stereo 24-bit audio sampled at 96kHz
audio_filesize(samp.rate=96000, bit.depth=24, channels=2, duration=1, duration.unit="years")

Get data or analyses from audioBlast

Description

Search for data or analyses on audioBlast.

Usage

audioblast(
  type,
  name,
  endpoint = NULL,
  check = TRUE,
  max_pages = NULL,
  page = 1,
  quiet = FALSE,
  on.issue = stop,
  output = "data.frame",
  ...
)

Arguments

type

One of data, analysis, standalone.

name

Name of data or analysis source.

endpoint

Optionally specify endpoint of an audioBlast module.

check

Logical. Performs sanity check on input before sending to audioBLAST.

max_pages

Maximum number of data pages to return, by default this is set to NULL and returns all pages.

page

First page of results to request, defaults to 1.

quiet

If true will not print progress. Silence is a virtue.

on.issue

Function to call on error or warning. By default stop to raise a standard R error. Setting to warning will instead a warning.

output

By default a data.frame. "Annotations" will return a list of Annotation objects.

...

Fields and values to filter on. Any field defined by audioBLAST.

Value

A data frame

Examples

## Not run: 
audioblast("data", "recordings", taxon="Gryllotalpa vineae")

## End(Not run)

Download audio files from audioBlast

Description

Downloads audio files associated with a search using the audioBlast() function.

Usage

audioblastDownload(
  d,
  metadata = TRUE,
  skip.existing = TRUE,
  dir = ".",
  quiet = FALSE,
  on.issue = .audioblastIssue
)

Arguments

d

Data returned from a search using audioBlast().

metadata

If true saves the data in d as a csv file.

skip.existing

If true will not overwrite existing files.

dir

Directory to save files to.

quiet

If true will not print progress.

on.issue

Function to call on error or warning. By default stop to raise a standard R error. Setting to warning will instead a warning.

Value

No return value, called for its side effect of downloading files.


Read AudioMoth configuration file

Description

Reads and parses an AudioMoth configuration file.

Usage

audiomothConfig(filename)

Arguments

filename

Path to the configuration file to read

Value

A data frame of the configuration settings, with columns Key and Value

Examples

## Not run: 
audiomothConfig("./CONFIG.TXT")

## End(Not run)

Read AudioMoth metadata from a wave file

Description

Reads and parses metadata stored in wave files produced by AudioMoth devices.

Usage

audiomothWave(filename)

Arguments

filename

Path to the wave file to read

Value

A list of extracted parameters

Examples

## Not run: 
audiomothWave("./FILENAME.WAV")

## End(Not run)

Automatic Band Pass Filter

Description

Creates an automatic bandpass filter based on the strongest frequency. The allowed bandwidth can be an integer multiple of the bandwidth at either -3dB or -10dB.

Usage

autoBandPass(wave, bw = "-3dB", n.bw = 1, lowcut = 1000)

Arguments

wave

A Wave object

bw

Either -3dB or -10dB. This is calculated by frequencyStats

n.bw

The number of bandwidths either side of the centre of the centre to keep

lowcut

High-pass filtering is applied at this frequency before calculating the centre frequency and bandwidth

Value

A band-pass filtered Wave object

Examples

## Not run: 
autoBandPass(sheep)
autoBandPass(sheep, bw="-3dB", n.bw=1, lowcut=1000)
autoBandPass(sheep, bw="-10dB", n.bw=2, lowcut=0)

## End(Not run)

Simple bandpass filter

Description

Creates a band pass WaveFilter between values specified to a Wave object.

Usage

bandpass(from, to, ...)

Arguments

from

Bottom of bandpass frequency (Hz).

to

Top of bandpass frequency (Hz).

...

Further arguments to pass to ffilter.

Details

This is a simple wrapper function to the seewave ffilter function allowing its use with filterw and pipes.

Value

A WaveFilter object.

Examples

## Not run: 
nwave <- noise("white", duration=44100, samp.rate=44100)

fwave <- filterWave(nwave, bandpass(from=1000, to=2000))
nwave |> filterWave(bandpass(from=1000, to=2000)) -> fwave

## End(Not run)

Estimate the direction a sound arrived from

Description

Given the time differences of arrival of a sound between the microphones of an array, and the positions of those microphones, estimates the direction the sound arrived from.

Usage

bearing(delays, positions, speed = NULL, unit = "degrees")

Arguments

delays

Time differences of arrival in seconds, one per microphone, as returned by tdoa(). Either the data frame tdoa() returns, or a numeric vector in channel order. Channels with a delay of NA are ignored.

positions

Positions of the microphones in metres, as a matrix or data frame with one row per microphone (in the same order as delays) and either two or three columns.

speed

The speed of sound in metres per second. The default is the value soundSpeed() gives for air, a value for the conditions of a recording can be obtained with e.g. soundSpeed(method="cramer", temp=14, RH=80).

unit

Unit for the returned angles, either "degrees" (the default) or "radians".

Details

The sound is assumed to be far enough away that the wavefront reaching the array is flat, in which case the delay at each microphone depends on the direction the sound came from but not on how far away it was. "Far enough" is relative to the size of the array: a few array widths is usually sufficient. No distance to the source is estimated, and none can be from a single array under this assumption.

The direction is returned as an azimuth measured anticlockwise from the positive x axis of the coordinates the microphone positions were given in. If those coordinates have x pointing east and y pointing north, the compass bearing of the source is (90 - azimuth) %% 360 degrees.

Arrays that cannot give a single answer

Two microphones, or any number of microphones in a straight line, determine only the angle between the direction of the sound and the axis of the array: every direction on a cone around that axis gives the same delays. For an array lying in a line in two dimensions this leaves two possible bearings, mirrored about the array axis, and both are returned. Microphones lying in a plane, with positions given in three dimensions, likewise leave two possible directions mirrored about that plane. For microphones in a line with positions given in three dimensions no bearing can be recovered, and only the angle from the array axis is returned.

Checking the result

A set of delays that is consistent with a plane wave has a magnitude of 1 and a residual of 0. A magnitude far from 1, or a residual that is an appreciable fraction of the size of the array, means the delays are not consistent with any single direction and the bearing should not be trusted. Common causes are a correlation peak found on the wrong cycle of a tonal sound, a source too close to the array for the plane wave assumption, and two sounds overlapping in the window correlated.

Neither check is available from every array. The residual is only meaningful where there are more microphones than one more than the number of dimensions the positions are given in, as fewer leave the delays exactly enough to fit a direction to. The magnitude is only meaningful for an array that determines the direction fully, as one that does not fits only the part of the direction it can see. For a pair of microphones neither is available, and delays that are not physically possible are all that can be detected.

The speed of sound

Where the array determines the direction fully the bearing does not depend on the speed of sound, which only scales the delays: getting it wrong moves the magnitude away from 1 but leaves the direction alone. Where the array leaves an ambiguity the bearing does depend on it, so a pair of microphones is worth giving a speed calculated for the conditions of the recording.

Value

A list holding:

  • azimuth The direction the sound arrived from, or two directions where the array leaves an ambiguity (see Details), or NA where no direction can be recovered.

  • elevation The angle above the horizontal, for positions given in three dimensions. NA otherwise.

  • direction A matrix holding the unit vector of each direction in the coordinates the positions were given in.

  • cone For microphones in a line with positions given in three dimensions, the angle between the direction of the sound and the axis of the array, measured from the first microphone towards the last. NA otherwise.

  • residual The root mean square difference, in metres, between the path length differences the estimate implies and those the delays give.

  • magnitude The length of the direction vector the fit produced, before it was scaled to a unit vector, which is 1 for delays that are exactly consistent with a plane wave (see Details). Where the array leaves an ambiguity this is the length of the part of the direction the array can see, which is at most 1.

  • speed The speed of sound used.

  • unit The unit the angles are given in.

  • ambiguous Whether the array leaves more than one possible direction.

See Also

tdoa(), which produces the delays this function takes.

Examples

# Three microphones in a right angled triangle, 1m apart
mics <- rbind(c(0, 0), c(1, 0), c(0, 1))

# A sound arriving from the east reaches the eastern microphone first
bearing(c(0, -1/343, 0), mics)

# A stereo pair leaves two possible bearings
bearing(c(0, -0.5/343), rbind(c(0, 0), c(1, 0)))

Beat spectrum complexity

Description

This function computes a beatSpectrum and calculates some basic measurements of its complexity. The complexity value is calculated as the maximum identified repeating period (in seconds) divided by the number of peaks.

Usage

beatComplexity(wave, plot = FALSE)

Arguments

wave

A Wave object

plot

If TRUE a spectrogram overlaid with the peaks is plotted.

Value

A list of the complexity, a vector of the peak periods, and the number of peaks.

Examples

## Not run: 
  beatComplexity(sheep)
  beatComplexity(sheep, plot=TRUE)

## End(Not run)

Computes a beat spectrum

Description

Beat spectra represent the periodicity in signal amplitude. It is computed by performing a continuous wavelet transform on the envelope of a preprocessed signal, and processing the average power per frequency band.

Usage

beatSpectrum(wave, min_period = 0.005, max_period = 30, dj = 1/32, ...)

Arguments

wave

an R object or path to a wave file

min_period

the minimal rhythmicity period expected, in seconds

max_period

the maximal rhythmicity period expected, in seconds

dj

the frequency resolution of the cwt (in voices per octave)

...

extra arguments passed to analyze.wavelet()

Value

a spectrum as a data frame. It contains two columns: power and period. The number of rows depend on the resolution and frequency range.

Author(s)

Quentin Geissmann

Examples

## Not run: 
beatSpectrum(sheep)
beatSpectrum(sheep, min_period=0.005, max_period=30, dj=1/32)

## End(Not run)

Analyse sound files using BirdNET-Analyzer

Description

This function takes a list of sound files and analyses them using the BirdNET-Analyzer (Kahl et al. 2021). The function either returns a data frame with the results of the analysis or a list of Annotation objects.

Usage

birdNetAnalyse(
  files,
  lat = NULL,
  lon = NULL,
  date = NULL,
  output = "Annotation"
)

Arguments

files

A character vector of file paths.

lat

A latitude or vector of latitudes.

lon

A longitude or vector of longitudes.

date

A Date or list of Date objects .

output

One of "data.frame" or "Annotation".

Value

A list of Annotation objects, or a data frame if output is "data.frame".

References

Kahl S, Wood CM, Eibl M, Klinck H (2021). “BirdNET: A deep learning solution for avian diversity monitoring.” Ecological Informatics, 61.

Examples

## Not run: 
  birdnetAnalyse(files=c("path/to/file1.wav", "path/to/file2.wav"), output="data.frame")

## End(Not run)

Channels for sound ecology

Description

Used to process the output of acoustic index functions from the soundecology package when using allChannels.

Usage

channels_se(...)

Arguments

...

Export from a bioacoustic index function from the soundecology package

Value

A list containing the value calculated for the left channel.


Circularise a dataset

Description

When plotting rings or horizons that are meant to cover the entirety of the time period in a dielPlot() or yearlyPlot() this function append the beginning values to the end to ensure an entire loop is created.

Usage

circularise(values)

Arguments

values

A vector if values

Value

The input vector with its first value appended, so that it closes on itself.


Concatenate two or more Wave-like objects.

Description

The concat() method is a more flexible version of the bind() method from tuneR package, that allows specifying more advanced types of concatenation. Setting method to "noClick" will remove any click between Wave objects caused by sudden jumps in amplitude by applying tuneR::prepComb() appropriately with default value of zero (this is only effective for the left channel or stereo or multi-channel recordings).

Usage

concat(object, ..., method = "bind")

## S4 method for signature 'Wave'
concat(object, ..., method = "bind")

## S4 method for signature 'WaveMC'
concat(object, ..., method = "bind")

## S4 method for signature 'TaggedWave'
concat(object, ..., method = "bind")

## S4 method for signature 'TaggedWaveMC'
concat(object, ..., method = "bind")

Arguments

object

A Wave like object.

...

Wave like objects to concatenate to object.

method

One of "bind", "noClick". Default is "bind".

Value

A concatenated Wave like object, with type of object.


Convert file sizes to bytes

Description

Converts file size measurements into bytes. Both decimal units, which are powers of 1000, and binary units, which are powers of 1024, are accepted.

Usage

convert2bytes(S, input = "bits")

Arguments

S

The value to convert

input

The unit to convert, one of those given by fileSizeUnits(), or "bits" or "bytes".

Value

The numeric value in bytes

Examples

convert2bytes(8, input="bits")
convert2bytes(1, input="kB")
convert2bytes(1, input="KiB")

Convert temperature to Celsius

Description

Converts temperature measurements into Celsius

Usage

convert2Celsius(temp, input = "K")

Arguments

temp

The value of the temperature to convert

input

The unit of the temperature to convert, allowed values are "K", "F".

Value

Numeric value in degrees Celsius

Examples

convert2Celsius(15, input="K")
convert2Celsius(15, input="F")

Convert angle to degrees

Description

Converts angle measurements into degrees

Usage

convert2degrees(A, input = "radians")

Arguments

A

The angle value to convert

input

The unit of angle to convert, allowed values are "radians".

Value

The numeric value in degrees


Convert pressure to dyne per square centimetre

Description

Converts pressure measurements into dyne per square centimetre

Usage

convert2dyne_cm2(P, input = "kPa")

Arguments

P

The value of the pressure to convert

input

The unit of the pressure to convert, allowed values are "Pa", "kPa".

Value

The numeric value in dyne per square centimetre.

Examples

convert2dyne_cm2(1, input="Pa")
convert2dyne_cm2(1, input="kPa")

Convert temperature to Fahrenheit

Description

Converts temperature measurements into Fahrenheit

Usage

convert2Fahrenheit(temp, input)

Arguments

temp

The value of the temperature to convert

input

The unit of the temperature to convert, allowed values are "K", "C".

Value

No return value, this conversion is not implemented and the function raises an error.

Examples

## Not run: 
convert2Fahrenheit(15, input = "C")

## End(Not run)

Convert temperature to Kelvin

Description

Converts temperature measurements into Kelvin

Usage

convert2Kelvin(temp, input = "C")

Arguments

temp

The value of the temperature to convert

input

The unit of the temperature to convert, allowed values are "C", "F".

Value

Numeric value in Kelvin

Examples

convert2Kelvin(15, input="C")
convert2Kelvin(15, input="F")

Convert pressure to Pascals

Description

Converts pressure measurements into Pascals

Usage

convert2Pascals(P, input = "kPa")

Arguments

P

The value of the pressure to convert

input

The unit of the pressure to convert, allowed values are "kPa", "dyne_cm2".

Value

The numeric value in Pascals

Examples

convert2Pascals(1000, input="kPa")
convert2Pascals(10, input="dyne_cm2")

Convert angle to radians

Description

Converts angle measurements into radians

Usage

convert2radians(A, input = "degrees")

Arguments

A

The angle value to convert

input

The unit of angle to convert, allowed values are "degrees".

Value

The numeric value in radians


Convert time to seconds

Description

Converts time measurements into seconds

Usage

convert2seconds(T, input = "minutes", origin = "day")

Arguments

T

The time value to convert

input

The unit of time to convert, allowed values are "minutes", "hours", "days", "years", "HHMM".

origin

For POSIX whether to return relative to start of day ("day") or Unix epoch ("unix")

Value

The numeric value in seconds


Correlate channels in a WaveMC object

Description

Uses the corenv function from seewave to calculate the envelope correlation for timed events between the channels of a WaveMC object

Usage

corWaveMC(wave, times, window, cluster = NULL, ...)

Arguments

wave

A WaveMC object

times

One or more times of events to correlate

window

Width of the window to correlate in seconds (centred on times)

cluster

A cluster for parallel execution

...

Additional arguments passed to seewave::corenv(), e.g. method or the envelope smoothing arguments.

Details

The delays are the offsets corenv() reports, with the sign changed so that a positive delay means the sound arrived at that channel later than it arrived at the first channel, which is the convention tdoa() and bearing() use. corenv() resolves an offset only to a whole sample, and reports any delay of zero or less as one sample greater than it is. tdoa() with method="envelope" measures the same thing without either limitation, and its output can be passed to bearing().

corenv() correlates ranks rather than values unless it is told otherwise, which for a recording with quiet stretches between events can put the largest correlation at no offset at all whatever the offset really is. Pass method="pearson" if the delays look implausible.

Value

A list with one entry per event, each holding the corenv list for every channel in correlations, and the delay of every channel relative to the first in delays (see Details).

See Also

tdoa(), which measures the time differences of arrival between channels, and bearing(), which turns them into a direction.


Cut wave by samples

Description

Extract a section of a Wave or WaveMC object based on sample positions. This function will automatically detect if a Wave object is stereo, and returns the same class of object it was given.

Usage

cutws(wave, from = 1, to = Inf, plot = FALSE)

Arguments

wave

A Wave or WaveMC object

from

First sample to return

to

Last sample to return

plot

If TRUE shows the cut region within the original waveform

Value

A Wave or WaveMC object

Examples

## Not run: 
cutws(sheep, 1, 20)
cutws(sheep, 1, 20, plot=TRUE)

## End(Not run)

Convert data into a Wave object

Description

Make a sequence of data into a normalised Wave object.

Usage

data2Wave(
  left,
  samp.rate = 44100,
  bit = 16,
  unit = NULL,
  remove.offset = TRUE,
  normalise = TRUE
)

Arguments

left

Data for mono audio channel

samp.rate

Sampling rate for Wave object

bit

Bit depth of Wave object

unit

See tuneR::normalize. If NULL this is handled automatically.

remove.offset

If TRUE any DC offset is removed

normalise

If TRUE the output Wave is normalised to the range implied by unit, which for the default of NULL is the range of the bit depth rather than -1:1.

Value

A mono Wave object.

Examples

pattern <- seq(from=-1, to=1, length.out=100)
data <- rep.int(pattern, 100)
w <- data2Wave(data)

Phase of day

Description

Given a start time and (optionally) a duration returns the phase of day at a given location. This is primarily used to calculate phase of day information for soundscape recording projects.

Usage

dayPhase(
  time = Sys.time(),
  duration = 40000,
  lat = 50.1,
  lon = 1.83,
  tz = "UTC"
)

Arguments

time

A time object representing the start time of a recording

duration

Duration of recording in seconds

lat

Latitude of recording device

lon

Longitude of recording device

tz

Time-zone of recording device when recording was made

Value

Data frame of day phases with absolute timestamps and relative times within file

Examples

dayPhase(time=as.POSIXct("2024-06-15 20:00:00", tz="UTC"), duration=40000)

Phases of days

Description

Phases of days

Usage

daysPhases(
  date = Sys.Date(),
  period = "year",
  plot = FALSE,
  lat = 50.1,
  lon = 1.83,
  tz = "UTC"
)

Arguments

date

A time object representing the start time of a recording

period

"month" or "year"

plot

If true plots the data, default FALSE

lat

Latitude of recording device

lon

Longitude of recording device

tz

Time-zone of recording device when recording was made

Value

A data frame with a row for each day, giving the times of each phase of the day and the state of the moon.

Examples

daysPhases(date=as.Date("2024-06-15"), period="month")

Create Default Cluster for Windowing

Description

Creates a default cluster using one less than the total cores available on the system. By default this uses forking, which is not be available on Windows. Hence, the fork parameter has no effect on Windows.

Usage

defaultCluster(fork = TRUE)

Arguments

fork

If TRUE uses forking to create the cluster (Unix like systems only)

Value

A cluster object for parallel processing

Examples

## Not run: 
cl <- defaultCluster()
stopCluster(cl)
cl <- defaultCluster(FALSE)
stopCluster(cl)

## End(Not run)

Calculate the fraction of a day given by a value

Description

Given an object that can be coerced to POSIXlt or is in a supported string format, return the fraction of a day represented by the object.

Usage

dielFraction(t, input = "POSIX", unit = "radians")

Arguments

t

Object to be converted to a fraction

input

One of POSIX (default) or HHMM

unit

If set to radians outputs a position around a circle. If set to fraction outputs the raw fraction.

Value

The position of the time within the day, in radians or as a fraction of a day.


Diel Histogram

Description

Draws a histogram on a dielPlot() using pre-defined bins related to time of day.

Usage

dielHistogram(
  times,
  by = "hour",
  col = "grey",
  maxval = NA,
  presence.only = FALSE,
  limits = c(1, 2),
  rot = tzRot(0)
)

Arguments

times

A vector of times that can be processed by dielFraction().

by

Controls the size of histogram bins, one of "hour", "15minute", "30minute".

col

Colour of the plot.

maxval

By default scales histogram within limits, specifying a maximum value here allows comparison between plots.

presence.only

Only show presence/absence not values.

limits

Limits of the plotting (see dielPlot()).

rot

Rotation of the plot, which must match the dielPlot() being drawn on.

Value

A data frame of start and end points of bins.


Generate labels for a diel plot

Description

Generates labels for a dielPlot() in 12- or 24-hour format. Labels are generated at three hourly intervals.

Usage

dielLabels(format = "clock24")

Arguments

format

One of clock24 (default) or clock12

Value

A character vector of eight labels, at three hourly intervals.

Examples

dielLabels()
dielLabels("clock12")

Create a diel plot

Description

A diel plot shows the times of night, twilight and the maximum altitude of the sun for a given date.

Usage

dielPlot(
  date,
  lat,
  lon,
  limits = c(0, 2),
  plot = NULL,
  rot = tzRot(0),
  method = "plotrix",
  legend = FALSE
)

Arguments

date

Date to plot.

lat

Numeric latitude.

lon

Numeric longitude.

limits

Plotting limits of the daylight regions, default to c(1,2)

plot

Character vector of components to plot

rot

Either "Solar Noon" or an offset calculated by tz

method

Plotting library to use

legend

Whether to show a legend

Value

Called for its side effect of drawing a plot. The return value is that of the underlying plotting function and should not be relied on.


Generate positions of labels for a diel plot

Description

Generates positions for three-hourly labels of a dielPlot() in radians.

Usage

dielPositions(format = "3hourly")

Arguments

format

One of "3hourly" (default), "hours", or "minutes"

Value

A numeric vector of label positions, in radians.

Examples

dielPositions()
dielPositions("hours")
dielPositions("minutes")

Plot rings on a diel plot

Description

Plot rings on a diel plot.

Usage

dielRings(
  names,
  starts,
  ends,
  cols = "grey",
  format = "HHMM",
  limits = c(1, 2),
  legend = TRUE,
  rot = tzRot(0)
)

Arguments

names

Labels for the rings

starts

Start times for rings in HHMM string format

ends

End times for rings in HHMM string format

cols

Colours of the rings

format

Defaults to HHMM

limits

Region of a dielPlot() to plot rings. Defaults to c(1,2)

legend

Boolean. Whether to plot a legend.

rot

Rotation of the plot, which must match the dielPlot() being drawn on.

Value

Called for its side effect of drawing on the current plot. The return value is that of the underlying plotting function and should not be relied on.


Dolbear's law

Description

Dolbear (1897) was the first to publish a formula for how the rate of chirping of crickets varies with temperature, using the tree cricket Oecanthus fultoni.

Usage

dolbear(n = NULL, t = NULL, species = "Oecanthus fultoni")

Arguments

n

Chirps per minute

t

Temperature in Celsius

species

Species to use (by default Oecanthus fultoni), NULL to calculate for all species.

Details

Subsequent research by Dolbear and others have published additional formulae for other species: Oecanthus fultoni (Fulton 1925), Oecanthus rileyi (Walker 1962), Oecanthus alexanderi (Walker and Collins 2010), and Oecanthus allardi (Allard 1957).

Value

Data frame with t and n calculated for matching species.

References

Allard HA (1957). “The stridulations of some crickets in the Dominican Republic.” Journal Washington Academy of Sciences, 47, 150–152.

Dolbear AE (1897). “The Cricket as a Thermometer.” The American Naturalist, 31(371), 970–971. ISSN 00030147, 15375323. http://www.jstor.org/stable/2453256.

Fulton BB (1925). “Physiological variation in the snowy tree cricket, Oecanthus fultoni, De Geer.” Annals of the Entomological Society of America, 18, 363–383.

Walker TJ (1962). “The taxonomy and calling songs of United States tree crickets (Orthoptera: Gryllidae: Oecanthinae). I. The genus Neoxabea and the niveus and varicornis groups of the genus Oecanthus.” Annals Entomological Society of America, 55, 303–322. http://entnemdept.ifas.ufl.edu/walker/Buzz/s576lw62.pdf.

Walker TJ, Collins N (2010). “New World thermometer crickets: the Oecanthus rileyi species group and a new species from North America.” Journal of Orthoptera Research, 19(2). ISSN 10826467, 19372426. http://www.jstor.org/stable/25822725.

Examples

dolbear(n=6)
dolbear(t=25)

Calculate the duty cycle of a wave

Description

Proportion of a wave with signal above the limit

Usage

dutyCycle(wave, limit = 0.1, output = "unit", normalise = TRUE)

Arguments

wave

A Wave object. Stereo Wave and WaveMC objects are passed to allChannels(), which returns a list with one duty cycle per channel.

limit

Threshold above which to consider the signal

output

If "unit" the duty cycle will be in the range 0-1. For a percentage use "percent".

normalise

If TRUE the Wave is normalised using tuneR

Value

A numerical value for the duty cycle between 0 and 1 (or 0 and 100% if percentage output). For multi-channel input, a list of such values.

Examples

wave <- tuneR::sine(2000)
dc <- dutyCycle(wave)
pc <- dutyCycle(wave, output="percent")

Create an empty diel plot

Description

Create a diel plot with labels but without sun altitude or times of day plotted.

Usage

emptyDiel(method = "plotrix", rot = pi)

Arguments

method

Plotting package to use

rot

Rotation of the origin (defaults to pi)

Value

Called for its side effect of drawing a plot. The return value is that of the underlying plotting function and should not be relied on.


Create an empty yearly plot

Description

Create a yearly plot with labels but without sun or night duration plotted.

Usage

emptyYearly(year = 2022, method = "plotrix", rot = pi)

Arguments

year

Year to plot (allows for leap years)

method

Plotting package to use

rot

Rotation of the origin (defaults to pi)

Value

Called for its side effect of drawing a plot. The return value is that of the underlying plotting function and should not be relied on.


Various measurements of frequency values for a Wave object

Description

Calculates the peak, centre, bandwidth and quality factor. The quality factor (Q) is calculated at both -3dB and -10dB as discussed by Bennett-Clark (1999) https://doi.org/10.1080/09524622.1999.9753408.

Usage

entropyStats(wave)

Arguments

wave

A Wave object. Stereo Wave and WaveMC objects are passed to allChannels(), which returns one set of statistics per channel.

Value

A list of spectral entropy types. For multi-channel input, one such list per channel.

Examples

## Not run: 
entropyStats(sheep)

## End(Not run)

False-colour index spectrogram

Description

Calculates a false-colour index spectrogram, in which three acoustic indices are calculated for each frequency bin of each time window and mapped to the red, green and blue channels of an image. Long recordings can be summarised in a single image, with different sounds appearing as different colours.

Usage

fcis(
  x,
  window.length = NULL,
  indices = c("power", "ACI", "entropy"),
  wl = 256,
  cluster = NULL
)

Arguments

x

A Wave object, or a vector of filenames which are treated as consecutive parts of one recording.

window.length

Length of each column of the image in samples. If NULL, each file gives a single column.

indices

The three indices to map to the red, green and blue channels.

wl

Window length used for the spectrograms.

cluster

A cluster from the 'parallel' package for multi-core computation. This is only worthwhile when x is a filename and the windows are long, as each worker then reads its own part of the file. Passing a Wave object sends a copy of it to every worker, which takes longer than the calculation itself.

Details

Indices are scaled across the whole of the input, so that colours are comparable between the windows of one spectrogram but not between separate spectrograms. The available indices are described in fcisIndexNames.

Value

An object of class "fcis", being a list of the colours as a character matrix of one entry per frequency bin and window, the matrix of values for each index, the frequencies of the bins in kHz, the duration of a window in seconds, and the names of the indices used.

Examples

## Not run: 
f <- fcis(wave, window.length=44100)
plot(f)

f <- fcis(wave, window.length=44100, indices=c("background", "ACI", "cover"))

## End(Not run)

Per-frequency-bin acoustic indices

Description

The indices available as channels of a false-colour index spectrogram. Each is calculated separately for every frequency bin of a spectrogram, giving one value per bin rather than one value for the whole signal.

Usage

fcisIndexNames()

Details

power

Mean of the squared amplitude.

ACI

Acoustic complexity index, the summed absolute difference between consecutive time frames, divided by the total amplitude in the bin.

entropy

Temporal entropy of the amplitude, scaled to between 0 and 1. A bin whose amplitude is constant over time has an entropy of 1.

background

An estimate of the background level, taken as the tenth percentile of the amplitude over time.

cover

The proportion of time frames whose amplitude is more than three times the background level of the bin.

Value

A character vector of index names.

Examples

fcisIndexNames()

Units used for file sizes

Description

The units understood by convert2bytes() and produced by humanBytes(). Decimal units are powers of 1000 and binary units are powers of 1024.

Usage

fileSizeUnits(units = "decimal")

Arguments

units

One of "decimal" or "binary"

Value

A character vector of unit names, from smallest to largest.

Examples

fileSizeUnits()
fileSizeUnits("binary")

Apply a WaveFilter object to a Wave object

Description

A WaveFilter object is an object containing information necessary for the filterw function to apply the filter to a Wave object. This is designed to allow a pipe operator (either magrittr or base R) to be used to apply filters to a Wave in a pipeline.

Usage

filterWave(w, filt, cl = NULL)

Arguments

w

A Wave object.

filt

Wave object with the selected filter applied.

cl

Optional. If a cluster is specified, the filter will be applied in parallel.

Details

Supported filters include those from the seewave package.

Value

A filtered Wave or WaveMC object, or a list of such objects if given a list.


Get the frequency from wavelength and speed of sound

Description

Calculates the frequency of a sound wave given the wavelength and speed of sound in that medium.

Usage

frequencySound(wl, s = soundSpeed(medium = "air"))

Arguments

wl

Wavelength

s

Speed of sound (defaults to the speed of sound in air)

Value

Frequency of the sound in Hertz

Examples

f <- frequencySound(wl=100, s=343)

Various measurements of frequency values for a Wave object

Description

Calculates the peak, centre, bandwidth and quality factor. The quality factor (Q) is calculated at both -3dB and -10dB as discussed by Bennett-Clark (1999) <doi: 10.1080/09524622.1999.9753408>.

Usage

frequencyStats(wave, wave_spec = NULL, warn = TRUE, lowcut = 1, plot = FALSE)

Arguments

wave

A Wave object. Stereo Wave and WaveMC objects are passed to allChannels(), which returns one set of statistics per channel.

wave_spec

A precomputed spectrum (optional, if not present will be generated)

warn

If TRUE provides warnings when values are not consistent

lowcut

Frequency (in kHz) values below which are ignored.

plot

IF TRUE displays values

Value

A list of frequency statistics, with an entry for each of the -3dB and -10dB thresholds.


Add noise to a Wave like object

Description

Adding noise to a Wave like object allows for testing of the robustness of automated identification algorithms to noise.

Usage

generateNoise(
  wave,
  noise = c("white"),
  noise.add = FALSE,
  noise.ratio = 0.5,
  noise.ref = "file",
  output = "list"
)

Arguments

wave

Object to add noise to (Wave, WaveMC, or Tagged versions), or a list of such objects.

noise

Vector of noise to add (unif, gaussian, white, pink, power, red)

noise.add

If TRUE all noise sources are added to wave. If FALSE separate outputs are created for each noise source.

noise.ratio

Ratio of maximum noise amplitude to the maximum amplitude in wave.

noise.ref

Reference maximum for noise.ratio. If "max" then the maximum amplitude, if "file" then the maximum amplitude of wave.

output

TODO: Is this implemented?

Value

A list of Wave objects with the required noise added.


Generate time masked Wave-like objects

Description

Given a Wave-like object (or a list of Wave-like objects), generate new Wave-like objects with time masking.

Usage

generateTimeMask(wave, method = "squarewave", dutyCycle = 0.95, n.periods = 10)

Arguments

wave

A Wave-like object (or a list of Wave-like objects).

method

The method to use for time masking (one of "squarewave", "random).

dutyCycle

The duty cycle of the output. A value of 0.95 means that 5% of the time is masked.

n.periods

The number of waves to generate in the squarewave method.

Value

The Wave or WaveMC object with the time mask applied.


Generated time-shifted versions of a Wave-like object

Description

Given a Wave-like object (or list of Wave-like objects), this function generates time-shifted versions of the object. The time-shifted versions are generated by adding a constant amount of time to the start or end of the object. This is achieved by either inserting silence and truncating the object to the original length, or by rotating the audio within the object.

Usage

generateTimeShift(wave, type = "silent", amount = c(1, 2), where = "start")

Arguments

wave

A Wave or WaveMC object, or a list of such objects.

type

The type of time-shift to apply. Either "silent" or "rotate".

amount

Vector of amount of time to shift by (seconds).

where

Where to insert silence if type is "silent". One of "start", "end", or "both". If "both" two versions are generated for each amount.

Value

A Wave-like object or list of Wave-like objects.


Import scikit-maad

Description

Imports the scikit-maad object into R. This allows reuse of the same object between function calls.

Usage

getMaad()

Value

The scikit-maad Python module, with its sound and features submodules attached.


Google Speech API Transcribe

Description

Wrapper around various Google packages to simplify speech transcription.

Usage

gs_transcribe(filename, bucket = NULL, ...)

Arguments

filename

Path to file for analysis

bucket

Storage bucket on Google Cloud for larger files

...

Additional arguments to pass to gl_speech()

Value

A gs_transcribe object containing details of the transcription

Examples

## Not run: 
gs_transcribe("demo.wav")

## End(Not run)

Converts bytes in human readable form

Description

Given an input of bytes calculates the result in a sensible output unit (e.g. MB, GB, PB). Decimal units are powers of 1000, and binary units powers of 1024.

Usage

humanBytes(S, units = "decimal", digits = 3)

Arguments

S

Number of bytes. A vector may be given.

units

One of "decimal", giving units such as kB, or "binary", giving units such as KiB.

digits

Number of decimal places to round to, or NULL for no rounding.

Value

String in human readable format, one for each value of S.

Examples

humanBytes(1500)
humanBytes(1500, units="binary")
humanBytes(c(1, 1024, 1e6))

Converts time to human readable form

Description

Given a time calculates the result in a sensible output unit (e.g. minutes, hours).

Usage

humanTime(S, unit = "seconds", digits = 3)

Arguments

S

Time to convert in unit. A vector may be given.

unit

The unit of time to convert

digits

Number of decimal places to round to, or NULL for no rounding.

Value

String in human readable format, one for each value of S.

Examples

humanTime(90)
humanTime(c(1, 90, 7200))
humanTime(1, unit="hours")

Calculate the jitter in a Wave object

Description

Jitter is a measure of the variability of the length of successive periods in the waveform. Absolute jitter is the mean absolute difference between the lengths of consecutive periods, in samples; relative jitter divides this by the mean period length. A waveform of constant period has a jitter of zero.

Usage

jitter(wave, method = "absolute")

Arguments

wave

A Wave object

method

One of "absolute" or "relative"

Details

Periods are located from zero crossings, so they are measured to the nearest sample. A tone whose period is not a whole number of samples will report a small amount of jitter for this reason.

Value

The jitter, in samples for method "absolute" and as a proportion of the mean period for method "relative"

Examples

## Not run: 
jitter(sheep, method="absolute")
jitter(sheep, method="relative")

## End(Not run)

Pad labels with interval

Description

Takes labels from Google Speech API transcript and pads the time by a specified number of seconds.

Usage

labelPadding(t, pad = 0.5, max_t = NULL)

Arguments

t

Transcript from Google Speech API

pad

Amount of time (in seconds) to add to start and end

max_t

Optional. The duration of the file, so padding does not exceed length of file.

Value

A modified Google Speech API transcript object

Examples

## Not run: 
labelPadding(t, pad=2, max_t=duration(wave))

## End(Not run)

Combines labels which overlap into single continuous regions

Description

Takes labels from Google Speech API transcript and combines overlapping labels.

Usage

labelReduction(t)

Arguments

t

Transcript from Google Speech API

Value

A list containing start and end times of speech containing regions

Examples

## Not run: 
labelReduction(t)

## End(Not run)

Compute the acoustic complexity index using scikit-maad

Description

ACI depends on the duration of the spectrogram as the derivation of the signal is normalized by the sum of the signal. Thus, if the background noise is high due to high acoustic activity the normalization by the sum of the signal reduced ACI. So ACI is low when there is no acoustic activity or high acoustic activity with continuous background noise. ACI is high only when acoustic activity is medium, with sounds well above the background noise.

Usage

maad_acoustic_complexity_index(object, maad = NULL)

Arguments

object

A Wave object or a spectrogram_maad object generated by maad_spectrogram. If a Wave-like object is provided, the spectrogram will be calculated using the default parameters.

maad

An optional maad object. If not provided, one will be created using getMaad().

Details

For addition documentation see https://scikit-maad.github.io/generated/maad.features.temporal_acoustic_complexity_index.html (Pieretti et al. 2011).

Value

List comprising:

ACI_xx

Acoustic Complexity Index.

ACI_per_bin

Acoustic Complexity Index.

ACI_sum

Sum of ACI value per frequency bin (Common definition)

References

Pieretti N, Farina A, Morri D, Gage SH (2011). “A new methodology to infer the singing activity of an avian community: the Acoustic Complexity Index (ACI).” Ecological Indicators, 11, 868–873. doi:10.1016/j.ecolind.2010.11.005.


Compute the frequency entropy using scikit-maad

Description

The spectral entropy of a signal measures the energy dispersion along frequencies. Low values indicates a concentration of energy around a narrow frequency band. If the DC value is not removed before processing the large peak at f=0Hz will lower the entropy of the signal.

Usage

maad_frequency_entropy(object, compatibility = "QUT", maad = NULL)

Arguments

object

A Wave object or a spectrogram_maad object generated by maad_spectrogram. If a Wave-like object is provided, the spectrogram will be calculated using the default parameters.

compatibility

One of "QUT" (Towsey et al. 2018) or "seewave" (Sueur et al. 2008). Default is "QUT".

maad

An optional maad object. If not provided, one will be created using getMaad().

Details

For addition documentation see https://scikit-maad.github.io/generated/maad.features.frequency_entropy.html

Value

List comprising:

Hf

Frequency entropy.

Ht_per_bin

Temporal entropy per frequency bin.

References

Sueur J, Aubin T, Simonis C (2008). “Seewave, a free modular tool for sound analysis and synthesis.” Bioacoustics, 18(2), 213–226.

Towsey M, Truskinger A, Cottman-Fields M, Roe P (2018). “Ecoacoustics Audio Analysis Software.” https://github.com/QutEcoacoustics/audio-analysis.


Compute the number of peaks using scikit-maad

Description

Count the number of frequency peaks on a mean spectrum. This function was adapted from the function fpeaks of the R package Seewave (Sueur et al. 2008).

Usage

maad_number_of_peaks(
  object,
  mode = "dB",
  min_peak_val = NULL,
  min_freq_dist = 200,
  slopes = c(1, 1),
  prominence = 0,
  maad = NULL
)

Arguments

object

A Wave object or a spectrogram_maad object generated by maad_spectrogram. If a Wave-like object is provided, the spectrogram will be calculated using the default parameters.

mode

One of "dB", "linear".

min_peak_val

Only peaks above this threshold will be considered.

min_freq_dist

Frequency threshold parameter (in Hz). If the frequency difference of two successive peaks is less than this threshold, then the peak of highest amplitude will be kept only.

slopes

Refers to the amplitude slopes of the peak. The first value is the left slope and the second value is the right slope. Only peaks with higher slopes than threshold values will be kept.

prominence

The first element is the minimal prominence and the second element is the maximal prominence. If a single number is provided it is interpreted as the minimal value, and no maximal value will be used.

maad

An optional maad object. If not provided, one will be created using getMaad().

Details

For addition documentation see https://scikit-maad.github.io/generated/maad.features.number_of_peaks.html

Value

Numeric number of peaks


Compute the spectral activity using scikit-maad

Description

Acoustic activity corresponds to the portion of the spectrogram above a threshold frequency per frequency along time axis (Towsey 2017).

Usage

maad_spectral_activity(object, dB_threshold = 6, maad = NULL)

Arguments

object

A Wave object or a spectrogram_maad object.

dB_threshold

dB threshold of activity (default = 6).

maad

An optional maad object. If not provided, one will be created using getMaad().

Value

The function computes for each frequency bin:

ACTfract

Proportion (fraction) of points above the threshold.

ACTcount

Total number of points above the threshold.

ACTmean

Mean value (in dB) of the portion of the signal above the threshold.

References

Towsey M (2017). “The calculation of acoustic indices derived from long-duration recordings of the natural environment.” Queensland University of Technology. https://eprints.qut.edu.au/110634/1/QUTePrints110634_TechReport_Towsey2017August_AcousticIndices%20v3.pdf.


Compute the frequency entropy using scikit-maad

Description

Compute different entropies based on the average spectrum, its variance, and its maxima.

Usage

maad_spectral_entropy(object, flim = NULL, maad = NULL)

Arguments

object

A Wave object or a spectrogram_maad object generated by maad_spectrogram. If a Wave-like object is provided, the spectrogram will be calculated using the default parameters.

flim

A numeric vector of length 2 specifying the frequency limits for the entropy calculation.

maad

An optional maad object. If not provided, one will be created using getMaad().

Details

For addition documentation see https://scikit-maad.github.io/generated/maad.features.spectral_entropy.html

Value

List comprising:

EAS

Entropy of Average Spectrum.

ECU

Entropy of spectral variance (along the time axis for each frequency).

ECV

Entropy of Coefficient of Variation (along the time axis for each frequency).

EPS

Entropy of spectral maxima (peaks).

EPS_KURT

Kurtosis of spectral maxima.

EPS_SKEW

Skewness of spectral maxima.


Compute a spectrogram of a sound wave using scikit-maad

Description

This is a wrapper function for the maad.sound.spectrogram function from the scikit-maad package for Python. It computes the spectrogram of a sound wave. Further usage details are provided at https://maad.readthedocs.io/en/latest/maad.sound.html#maad.sound.spectrogram.

Usage

maad_spectrogram(wave, mode = "power", ..., maad = NULL)

Arguments

wave

A Wave object

mode

The type of spectrogram to compute. Options are "power", "amplitude" "complex". Default is "power".

...

Additional arguments to pass to maad.sound.spectrogram.

maad

An optional maad object. If not provided, one will be created using getMaad().

Value

Generically a spectrogram_maad object.


Compute a spectrum of a sound wave using scikit-maad

Description

This is a wrapper function for the maad.sound.spectrum function. It computes the spectrum of a sound wave. Further usage details are provided at https://maad.readthedocs.io/en/latest/maad.sound.html#maad.sound.spectrum.

Usage

maad_spectrum(wave, ..., maad = NULL)

Arguments

wave

A Wave object

...

Additional arguments to pass to maad.sound.spectrum.

maad

An optional maad object. If not provided, one will be created using getMaad().

Value

A list comprising:

pxx

Power spectral density estimate.

f_idx

Index of sample frequencies.


Compute the acoustic activity index using scikit-maad

Description

For addition documentation see https://scikit-maad.github.io/generated/maad.features.temporal_activity.html (Towsey 2013).

Usage

maad_temporal_activity(
  wave,
  dB_threshold = 3,
  mode = "fast",
  Nt = 512,
  maad = NULL
)

Arguments

wave

A Wave object.

dB_threshold

dB threshold of activity (default = 3).

mode

Mode of the envelope calculation. Can be "fast" or "Hilbert".

Nt

Size of each frame. The largest, the highest is the approximation.

maad

An optional maad object. If not provided, one will be created using getMaad().

Value

List of calculated values, comprising:

ACTfrac

fraction)of points above the threshold for each frequency bin.

ACTcount

total number of points above the threshold for each frequency bin.

ACTmean

mean value (in dB) of the portion of the signal above the threshold.

References

Towsey M (2013). “Noise Removal from Waveforms and Spectrograms Derived from Natural Recordings of the Environment.” Queensland University of Technology. https://eprints.qut.edu.au/216373/.


Compute the temporal entropy using scikit-maad

Description

For addition documentation see https://scikit-maad.github.io/generated/maad.features.temporal_entropy.html.

Usage

maad_temporal_entropy(
  wave,
  compatibility = "QUT",
  mode = "fast",
  Nt = 512,
  maad = NULL
)

Arguments

wave

A Wave object.

compatibility

One of "QUT" (Towsey et al. 2018), "seewave" (Sueur et al. 2008).

mode

Mode of the envelope calculation. Can be "fast" or "hilbert".

Nt

Size of each frame. The largest, the highest is the approximation.

maad

An optional maad object. If not provided, one will be created using getMaad().

Value

Numeric entropy of the envelope.

References

Sueur J, Aubin T, Simonis C (2008). “Seewave, a free modular tool for sound analysis and synthesis.” Bioacoustics, 18(2), 213–226.

Towsey M, Truskinger A, Cottman-Fields M, Roe P (2018). “Ecoacoustics Audio Analysis Software.” https://github.com/QutEcoacoustics/audio-analysis.


Compute the acoustic event index using scikit-maad

Description

An acoustic event corresponds to the period of the signal above a threshold. An acoustic event could be short (at list one point if rejectDuration is None) or very long (the duration of the entire audio). Two acoustic events are separated by a period with low audio signal (i.e. below the threshold).

Usage

maad_temporal_events(
  wave,
  dB_threshold = 3,
  rejectDuration = 0.1,
  mode = "fast",
  Nt = 512,
  maad = NULL
)

Arguments

wave

A Wave object.

dB_threshold

dB threshold of activity (default = 3).

rejectDuration

Duration of the silence to reject an acoustic event (default = 0.1).

mode

Mode of the envelope calculation. Can be "fast" or "Hilbert".

Nt

Size of each frame. The larger, the highest is the approximation.

maad

An optional maad object. If not provided, one will be created using getMaad().

Details

For addition documentation see https://scikit-maad.github.io/generated/maad.features.temporal_events.html (Towsey 2013) (Towsey et al. 2018).

Value

List of calculated values, comprising:

EVTfrac

fraction of points above the threshold for each frequency bin.

EVTcount

total number of points above the threshold for each frequency bin.

EVTmean

mean value (in dB) of the portion of the signal above the threshold.

EVN

logical vector or matrix with 1 corresponding to event position.

References

Towsey M (2013). “Noise Removal from Waveforms and Spectrograms Derived from Natural Recordings of the Environment.” Queensland University of Technology. https://eprints.qut.edu.au/216373/.

Towsey M, Truskinger A, Cottman-Fields M, Roe P (2018). “Ecoacoustics Audio Analysis Software.” https://github.com/QutEcoacoustics/audio-analysis.


Compute the temporal envelope median using scikit-maad

Description

For addition documentation see https://scikit-maad.github.io/generated/maad.features.temporal_median.html.

Usage

maad_temporal_median(wave, mode = "fast", Nt = 512, maad = NULL)

Arguments

wave

A Wave object.

mode

Mode of the envelope calculation. Can be "fast" or "hilbert".

Nt

Size of each frame. The largest, the highest is the approximation.

maad

An optional maad object. If not provided, one will be created using getMaad().

Value

Numeric median of the envelope.


Map three vectors to RGB

Description

Maps three vectors of equal length to RGB for use in false-colour index spectrograms

Usage

map2RGB(red, green, blue)

Arguments

red

The red channel vector

green

The green channel vector

blue

The blue channel vector

Value

A vector of RGB values


Combine annotations

Description

Checks a list of annotations for those that are overlapping in the time or frequency domain, and returns a list where overlapping annotations are merged. Annotation objects must have the same file, type and value to be merged.

Usage

merge_annotations(annotations, domain = "time", same.source = TRUE)

Arguments

annotations

A list of Annotation objects.

domain

Domain of the annotations, either "time" or "frequency".

same.source

If TRUE, annotations must have the same source to be merged.

Value

A list of Annotation objects.


Calculate the natural frequency

Description

Calculates the natural frequency given the inductance, capacitance and resistance. In the acoustic case the inductance is inertia or mass, the capacitance is elasticity (bulk modulus) and resistance is composed of air resistance and related quantities. All units are SI.

Usage

naturalFrequency(L, C = NULL, R)

Arguments

L

Inductance

C

Capacitance, by default IUPAC standard pressure.

R

Resistance

Details

For isothermal compression, the bulk modulus is equal to the pressure. The default value of C therefore is the IUPAC standard pressure.

Value

The natural frequency, in Hertz.

Examples

naturalFrequency(L=20,R=0.5)
naturalFrequency(L=20,C=1/4,R=0.5)

Normalise a Wave object

Description

Similar to normalize() from the tuneR package but automatically identifies the unit parameter.

Usage

normalise(wave, unit = NULL, ...)

Arguments

wave

Wave or WaveMC object

unit

If not null behaves as in normalize() from tuneR, if null the unit is automatically identified.

...

Additional arguments passed to normalize() from tuneR

Value

Normalised Wave or WaveMC object


Natural Time Domain

Description

Runs a function on the wave and outputs values in the Natural Time Domain (see Varotsos, Sarlis & Skordas(2011) https://doi.org/10.1007/978-3-642-16449-1).

Usage

ntd(wave, events, FUN, normalise = FALSE, argument = "wave", ...)

Arguments

wave

A Wave object containing pulses

events

Onset of detected events, e.g. from pulseDetection()

FUN

The function to run

normalise

If TRUE the output is a probability density

argument

If "wave" supplies a weave object to the function, if "vector" supplies the left channel as a numeric vector.

...

Additional arguments to FUN

Value

A list of outputs form the applied function


Parse a filename

Description

Attempts to extract meaningful information from a filename, typically the date and time a recording started.

Usage

parseFilename(file, format = NULL, timezone = "UTC")

Arguments

file

A filename (or list of filenames).

format

Optionally force a given format (see Details). If NULL (default) an attempt is made to automatically detect the format for each file. If "match" and a list of filenames is given then an attempt will be made to find a format that matches all files. This may give incorrect results if the filename is ambiguous (see Details).

timezone

The timezone the clock of the recorder was set to, defaults to "UTC" (see Details).

Details

Determining the format

It is sometimes impossible to accurately determine the format of a filename, e.g. when an eight-digit 'AudioMoth HEX' only contains numbers it could be confused with a YYYYMMDD format. If a list of filenames is given and the "match" format is specified then an effort will be made to determine the most likely format that applies to all filenames.

Timezones

Most supported formats write a wall clock (e.g. 20200609_191730) into the filename, with no indication of the timezone the clock of the recorder was set to. The timezone argument states which timezone that wall clock belongs to, and defaults to UTC, which is what AudioMoth devices use unless they are configured otherwise. The datetime returned is therefore the same instant whatever timezone the machine running the analysis is set to.

The 'AudioMoth HEX' and 'timestamp' formats are exceptions: these encode an instant rather than a wall clock, so for them timezone only sets the timezone the datetime is displayed in.

Supported formats

  • AudioMoth - The newer format for AudioMoth devices consists of a standard YYYYMMDD_HHMMSS.wav format. An eight character hexadecimal filename given this format is treated as 'AudioMoth HEX'.

  • AudioMoth HEX - Older format for AudioMoth devices consisting of eight hexadecimal characters giving the number of seconds since 1970-01-01 00:00:00 UTC. Conversion is handled by a call to the audiomoth() function from the seewave package (Sueur et al. 2008).

  • timestamp - A standard date-time format. Uses the R standard origin of 1970-01-01 00:00:00 UTC.

  • Wildlife Acoustics SM2 - Can also be used for Wildlife Acoustics SM4 devices. The filename is split by a call to seewave::songmeter().

  • Wildlife Acoustics SM3 - The filename is split by a call to seewave::songmeter().

  • YYYYMMDD_HHMMSS - A standard date-time format.

  • YYYYMMDD - A standard date format, the time is taken to be midnight.

Value

A list of file, type of match, datetime. If a list of filenames is given then a list of such lists is returned.

It is possible to determine additional properties from some files, these will be added to the list.

References

Sueur J, Aubin T, Simonis C (2008). “Seewave, a free modular tool for sound analysis and synthesis.” Bioacoustics, 18(2), 213–226.

Examples

parseFilename("5E90A4D4.wav")

Pulse detection using Dietrich (2004)

Description

Detects pulses in a Wave using the method described in Dietrich et al (2004) https://doi.org/10.1016/j.patcog.2004.04.004.

Usage

pd_dietrich2004(
  wave,
  U = 120,
  gamma = 0.05,
  alpha = 1.4,
  scaling = 32,
  V = 480,
  psi = 1
)

Arguments

wave

A Wave object

U

Window length

gamma

Gamma

alpha

Alpha

scaling

Scaling

V

V Window length

psi

Psi

Value

A list of input values plus the onset and offset times of pulses


Simplified pulse detection using Dietrich (2004)

Description

Detects pulses in a Wave.

Usage

pd_simple(
  wave,
  U = 120,
  gamma = 0.05,
  alpha = 1.4,
  scaling = 32,
  V = 480,
  psi = 1
)

Arguments

wave

A Wave object

U

Window length

gamma

Gamma

alpha

Alpha

scaling

Scaling

V

V Window length

psi

Psi

Value

A list of input values plus the onset and offset times of pulses.


Plot a false-colour index spectrogram

Description

Plot a false-colour index spectrogram

Usage

## S3 method for class 'fcis'
plot(
  x,
  xlab = NULL,
  ylab = "Frequency (kHz)",
  main = "False-colour index spectrogram",
  ...
)

Arguments

x

An object of class "fcis"

xlab

Label for the x axis

ylab

Label for the y axis

main

Title for the plot

...

Additional parameters passed to plot()

Value

No return value, called for its side effect of drawing a plot.

Examples

## Not run: 
plot(fcis(wave, window.length=44100))

## End(Not run)

Create a PseudoWave object

Description

This function is used to create a PseudoWave object that can be used to generate a Wave object when operated on.

Usage

pseudoWave(
  type = NA_character_,
  subtype = NA_character_,
  scale = 1,
  offset = 0,
  seed = 1,
  params = list()
)

Arguments

type

Type of PseudoWave (e.g. "noise", "sine")

subtype

Subtype of PseudoWave (e.g. "white" if type is "noise")

scale

The Wave channels are multiplied by this value

offset

This value is added to the Wave channels

seed

Random seed, so that the same PseudoWave gives the same samples every time. Pass NA for a fresh random sequence on each use. Setting a seed does not disturb the random numbers drawn elsewhere in the session.

params

List of additional parameters to pass to generating function

Value

A PseudoWave object.

Examples

pw <- pseudoWave("noise", "white")

pw <- pseudoWave("sine", params=list("f0"=440))

## Not run: 
pw <- pseudoWave("file", "myfile.wav")

## End(Not run)

An S4 class to represent a PseudoWave object that is converted to a Wave object when operated on.

Description

An S4 class to represent a PseudoWave object that is converted to a Wave object when operated on.

Slots

type

Type of PseudoWave (e.g. "noise")

subtype

Subtype of PseudoWave (e.g. "white" if type is "noise")

scale

The Wave channels are multiplied by this value

offset

This value is added to the Wave channels

seed

Random seed, so that the same PseudoWave gives the same samples every time. NA draws a fresh sequence on each use.

params

List of additional parameters to pass to generating function


Generate a single pulse

Description

Generate a single pulse, either a Dirac pulse (Dirac delta) or a square pulse.

Usage

pulse(
  type = "dirac",
  leading = 22050,
  pulse.length = 1,
  duration = samp.rate,
  samp.rate = 44100,
  bit = 1,
  pcm = FALSE,
  stereo = FALSE,
  output = "Wave",
  invert = FALSE
)

Arguments

type

Either "dirac" or "square".

leading

The number of samples before the pulse.

pulse.length

The number of samples in the pulse (for "square").

duration

The total number of samples generated.

samp.rate

The sample rate.

bit

The bit depth.

pcm

Whether Wave generated is PCM (see tuneR).

stereo

Whether Wave generated is stereo.

output

The output format ("Wave").

invert

Whether to invert the pulse.

Value

Specified by output.


Pulse detection

Description

Detects pulses in a Wave. Stereo and multi-channel waves are analysed one channel at a time, giving one result per channel.

Usage

pulseDetection(wave, method = "simple", ...)

Arguments

wave

A Wave object containing pulses

method

Which method to use for pulse detection

...

Other arguments to pass to pulse detection function

Value

The output of the pulse detection method used.


Pulse intervals

Description

Used to locate area of no pulses from the results of pulseDetection().

Usage

pulseIntervals(pulses, nsd = 2)

Arguments

pulses

The result of a pulseDetection.

nsd

The number of standard deviations each sid of the mean pulse interval to discard

Value

A list of onset and offset times for pulses


Install sonicscrewdriver Python environment

Description

This function installs scikit-maad in the sonicscrewdriver environment using reticulate.

Usage

pythonInstall(unattended = FALSE)

Arguments

unattended

If TRUE then the function will not prompt the user to install the environment in a non-interactive session.

Value

No return value, called for its side effect of creating the Python environment.

Examples

## Not run: 
pythonInstall()
pythonInstall(unattended=TRUE)

## End(Not run)

The radar equation

Description

Calculates the power returned from an echolocation pulse

Usage

radarPower(P_t, r, area, G_t = 1, G_r = 1, wl = 1)

Arguments

P_t

Power transmitted (from sender)

r

Range of the target

area

Effective cross-sectional area of the target

G_t

Transmitter gain

G_r

Receiver gain

wl

Wavelength (use only with G_r and G_t)

Value

The received power

Examples

radarPower(12, 20, 0.05)
radarPower(12, 20, 0.05, G_t=1.2, G_r=1.5, wl=0.045)

Radar range

Description

Calculates the distance of an object based on the round trip time of an echolocation pulse

Usage

radarRange(t, c = soundSpeed(medium = "air"))

Arguments

t

Time in seconds

c

Speed of sound in transmission medium m/s (by default air)

Value

Distance to object

Examples

radarRange(2)
radarRange(2, c=343)
radarRange(2, c=soundSpeed(medium = "sea water"))

Plot a radial polygon

Description

Used to plot sectors, annuli and horizons on a dielPlot() or yearlyPlot(). The polygon has an inner and outer horizon - which can be set to a fixed radius or a vector.

Usage

radialPolygon(
  angle1,
  angle2,
  radius1,
  radius2,
  col = "grey",
  border = NA,
  rot = -pi,
  angleinc = 0.01,
  reverse = TRUE,
  ...
)

Arguments

angle1

Angles for the inner line

angle2

Angles for the outer line

radius1

Radii for the inner line

radius2

Radii for the outer line

col

Colour of the polygon

border

Border colour (see polygon() for details)

rot

Rotation of the plot, defaults to pi to match dielPlot() and yearlyPlot()

angleinc

The angular increment in radians for calculating circular lines

reverse

If FALSE plots in an anti-clockwise direction

...

Other parameters passed to polygon()

Value

No return value, called for its side effect of drawing a polygon on the current plot.


Rainfall detection

Description

Detects rainfall in a Wave. An uncalibrated version of Bedoya et al (2017) https://doi.org/10.1016/j.ecolind.2016.12.018 is available in this package. The hardRain package can also be accessed via this wrapper.

Usage

rainfallDetection(wave, method = "bedoya2017", ...)

Arguments

wave

A Wave object to detect rainfall in. Stereo Wave and WaveMC objects are passed to allChannels(), which returns one value per channel.

method

Which rainfall detection method to use ("bedoya2017")

...

Other arguments to pass to rain detection function

Value

Numeric value from the rainfall detection algorithm chosen. For multi-channel input, a list of such values.

Examples

## Not run: 
rainfallDetection(sheep, method="bedoya2017")

## End(Not run)

Read an Audacity label file

Description

Reads an Audacity label file and returns either a list of Annotation objects or a data frame.

Usage

readAudacityLabels(file, output = "annotations")

Arguments

file

Path to the Audacity label file.

output

One of "annotations" or "data.frame".

Value

A list of Annotation objects, or a data frame if output is "data.frame".


Read an audio file

Description

This file is used to read an audio file and return a Wave object, it is an abstraction function for various specific audio reading functions. If no existing method can be identified an attempt is made to use the av package to read the audio.

Usage

readAudio(file, mime = "auto", from = 0, to = Inf, units = "seconds")

Arguments

file

File to read

mime

MIME type of file to read, or "auto". Supported types are "audio/x-wav" and "audio/mpeg" (MP3)

from

Start point in file to return

to

End point in file to return

units

One of "samples", "seconds", "minutes", "hours". Default is "seconds".

Details

Files read through the av package (which is everything that is not WAVE or MP3, e.g. FLAC) are returned at the bit depth the file was stored at, so that the same audio compares equal however it was read. The av package does not report a bit depth of 24, and returns 24bit audio as 32bit, so the samples of a 24bit file are 256 times those tuneR::readWave() would give for the same audio stored as WAVE. Audio stored as floating point is returned as 32bit.

Value

A Wave object


Read output files from BirdNet Analyser

Description

Reads a single file, or directory of files, output by BirdNet Analyser.

Usage

readBirdNet(file, filename_parsing = "none")

Arguments

file

Filename or directory

filename_parsing

Allows for filename parsing, accepted values are one of none, audiomoth, timestamp.

Value

A data frame.


Read a file from Seeed Studio Respeaker 6 mic array

Description

The Seeed Studio Respeaker-6 when used as described in the documentation saves an eight channel audio file with channels 7 and 8 not containing input audio. This function reads such a file and saves it as a six channel file.

Usage

readRespeaker6(filename, from = 1, to = Inf, units = "samples", header = FALSE)

Arguments

filename

file to read.

from

Where to start reading the wave in units.

to

Where to stop reading the wave in units.

units

Units in which from and to is given, the default is "samples", but can be set to time intervals such as "seconds".

header

If TRUE, just header information of the Wave file are returned, otherwise (the default) the whole Wave object.

Value

A WaveMC object.


Reference intensity

Description

Provides the standard reference intensity level.

Usage

referenceIntensity(unit = "watt_cm2")

Arguments

unit

Unit to return, "watt_cm2"

Value

The reference sound intensity, in the unit specified.

Examples

ri <- referenceIntensity()

Reference pressure

Description

Provides the standard reference pressure level.

Usage

referencePressure(unit = "Pa")

Arguments

unit

Unit to return, "Pa" or "dyne_cm2"

Value

The reference sound pressure, in the unit specified.

Examples

rp <- referencePressure()
rp <- referencePressure(unit="dyne_cm2")

Specify a region with a file to analyse

Description

Specifies a time-bounded region to analyse.

Usage

region(unit, from = 0, to = Inf)

Arguments

unit

Unit of time (one of samples, seconds, minutes, hours)

from

Start time

to

End time

Value

A TimeRegion object.


Calculate the resonant frequency

Description

Calculates the resonant frequency given the inductance and capacitance. In the acoustic case the inductance is inertia or mass, the capacitance is elasticity (bulk modulus) and resistance is composed of air resistance and related quantities. All units are SI.

Usage

resonantFrequency(L, C = NULL)

Arguments

L

Inductance

C

Capacitance, if NULL (the default) the IUPAC standard pressure is used.

Details

For isothermal compression, the bulk modulus is equal to the pressure. The default value of C therefore is the IUPAC standard pressure.

Value

The resonant frequency, in Hertz.

Examples

f <- resonantFrequency(L=1)

Sample duration

Description

Calculates the time represented by n samples in a Wave.

Usage

sDuration(n = 1, wave = NULL, samp.rate = NULL)

Arguments

n

The number of the samples

wave

A Wave object containing pulses

samp.rate

Integer sampling rate

Value

A numeric value in seconds

Examples

sDuration(n=20, samp.rate=44100)
## Not run: 
sDuration(n=20, wave=sheep)#'

## End(Not run)

Sheep frequencyStats

Description

The frequencyStats of the sheep data file from the seewave package.

Usage

sheepFrequencyStats

Format

An object of class list of length 3.


Calculate the shimmer in a Wave object

Description

Shimmer is a measure of the variability of amplitude between successive periods in the waveform. It is returned in decibels, as the mean absolute difference in level between the peak amplitudes of consecutive periods. A waveform of constant amplitude has a shimmer of zero.

Usage

shimmer(wave)

Arguments

wave

A Wave object

Value

The shimmer in decibels

Examples

## Not run: 
shimmer(sheep)

## End(Not run)

Sort annotations

Description

Sorts a list of annotations by either start time, frequency, or both.

Usage

sort_annotations(annotations, domain = "time", decreasing = FALSE)

Arguments

annotations

A list of Annotation objects.

domain

Domain of the annotations, either "time", "frequency", or "both".

decreasing

If TRUE, sort in decreasing order.

Value

A list of Annotation objects.


Calculate the speed of sound in a medium

Description

Given sufficient parameters (i.e. wavelength and frequency, bulk modulus and density) this function calculates the speed of sound.

Usage

soundSpeed(
  medium = NULL,
  method = NULL,
  wl = NULL,
  f = NULL,
  bulkModulus = NULL,
  density = NULL,
  ...
)

Arguments

medium

Propagation medium (e.g. "air"), or "all" to return a list of all available media.

method

Use a specific method to calculate the speed of sound (see Details).

wl

Wavelength

f

Frequency

bulkModulus

Bulk modulus

density

Density

...

Additional parameters passed to the method.

Details

The speed of sound can be calculated using the following methods:

  • cramer Uses the method described in Cramer (1993). Additional parameters are:

    • temp Temperature

    • temp.unit Temperature unit

    • pressure Pressure

    • pressure.unit Pressure unit

    • RH Relative humidity

    • MoleFracCO2 Mole fraction of CO2

  • seewave Delegates the calculation of the speed of sound in air to the package seewave (Sueur et al. 2008). This calculation is . performed as speed=331.4+0.6×temp\text{speed} = 331.4 + 0.6 \times \text{temp}. Additional parameters are:

    • temp Temperature

Value

The speed of sound in the medium, in metres per second.

References

Cramer O (1993). “The variation of the specific heat ratio and the speed of sound in air with temperature, pressure, humidity, and CO2 concentration.” The Journal of the Acoustical Society of America, 93(5), 2510–2516. ISSN 0001-4966. doi:10.1121/1.405827.

Sueur J, Aubin T, Simonis C (2008). “Seewave, a free modular tool for sound analysis and synthesis.” Bioacoustics, 18(2), 213–226.

Examples

soundSpeed(medium="air")
soundSpeed(medium="sea water")

soundSpeed(method="cramer", temp=14, pressure=3, RH=10)
soundSpeed(method="cramer", temp=14, temp.unit="C", pressure=3, pressure.unit="kPa", RH=10)

t <- 1:30
s <- lapply(t, function(x){soundSpeed(method="cramer", temp=x)})

Calculate and plot statistics on a frequency spectrum

Description

Given a list of outputs from meanspec generates a plot with the mean shown by a line, and either the minimum/maximum values or one standard deviation shown by a ribbon.

Usage

specStats(spectra, stats = "minMax", line.col = "black", ribbon.col = "grey70")

Arguments

spectra

A list of spectra

stats

Either minMax or sd

line.col

Colour for the line

ribbon.col

Colour for the ribbon

Value

A ggplot2 object


An S4 class to represent a spectrogram from scikit-maad.

Description

An S4 class to represent a spectrogram from scikit-maad.

Slots

Sxx

The spectrogram matrix

tn

The time vector

fn

The frequency vector

extents

The extents of the spectrogram. A list of tmin, tmax, fmin, fmax.


Short term energy

Description

Computes the short term energy of a Wave.

Usage

ste(wave, method = "dietrich2004", U = 120, ...)

Arguments

wave

A Wave object

method

Which method used to calculate the short term energy, by default "dietrich2004" to use (Dietrich et al. 2004).

U

Window length in samples, matching the pulse detection functions.

...

Other arguments to pass to ste method.

Value

A vector of short term energy values

References

Dietrich C, Palm G, Riede K, Schwenker F (2004). “Classification of bioacoustic time series based on the combination of global and local decisions.” Pattern Recognition, 37(12), 2293–2305.

Examples

## Not run: 
ste(sheep, method="dietrich2004")

## End(Not run)

STP: Standard Temperature and Pressure

Description

Dataset compiled from various sources for differing values of STP.

Usage

STP

Format

An object of class list of length 2.


Subtract two spectra from seewave

Description

This function takes two spectra from seewave (or equivalent) and subtracts their values. The spectra must have the same bins.

Usage

subtractSpectra(s1, s2, coerceNegative = TRUE)

Arguments

s1

First spectrum

s2

Second spectrum

coerceNegative

Sets any values below zero to zero in output.

Value

A spectrum of s1 - s2

Examples

## Not run: 
subtractSpectra(spec1, spec2)
subtractSpectra(spec1, spec2, coerceNegative=TRUE)

## End(Not run)

Generate a sine sweep

Description

Generates a frequency swept sine wave (either linear or logarithmic) and returns it as a Wave object or vector.

Usage

sweptsine(
  f0 = 100,
  f1 = 2500,
  mode = "linear",
  sweep.time = 1,
  time.unit = "seconds",
  samp.rate = 44100,
  output = "wave",
  ...
)

Arguments

f0

Start frequency

f1

End frequency

mode

One of "linear", "log"

sweep.time

Duration of swept wave

time.unit

One of "seconds", "samples"

samp.rate

Sample rate of swept wave

output

"wave" for a Wave object, or "vector"

...

Additional arguments to pass to data2Wave

Value

A swept wave object of the type specified in output.

Examples

#Generate a swept sine wave between 0Hz and 10kHz.
w <- sweptsine(0, 10e3)

#Generate a swept sine wave between 0Hz and 10kHz and normalise it.
w <- normalise(sweptsine(0, 10e3))

#Generate a stereo swept sine wave between 100Hz and 1KHz.
w <- tuneR::stereo(sweptsine(100, 1e3))

#Generate an exponentially swept sine wave between 100Hz and 1KHz.
w <- sweptsine(100, 1e3, mode="log")

A S4 class for tagged waves

Description

The TaggedWave class extended the Wave class from the tuneR package so that it can include extended metadata and the results of analyses.

Slots

metadata

A list for storing metadata.

analyses

A list for storing analyses.


A S4 class for tagged multi-channel waves

Description

The TaggedWaveMC class extended the WaveMC class from the tuneR package so that it can include extended metadata and the results of analyses.

Slots

metadata

A list for storing metadata.

analyses

A list for storing analyses.


Tag a Wave or WaveMC object

Description

This function takes a Wave/WaveMC object (or a list of such objects) and returns a corresponding tagged version (TaggedWave or TaggedWaveMC).

Usage

tagWave(w, origin = "user")

Arguments

w

A Wave or WaveMC object (or list of such objects).

origin

The origin of the object (default "user").

Value

A TaggedWave or TaggedWaveMC object (or list of such objects).


Time differences of arrival between channels

Description

Estimates the time difference of arrival (TDOA) of a sound between the channels of a multichannel recording, by generalised cross-correlation of each channel against a reference channel.

Usage

tdoa(
  wave,
  ref = 1,
  from = NULL,
  to = NULL,
  units = "seconds",
  method = "phat",
  max.delay = NULL,
  interpolate = TRUE
)

Arguments

wave

A Wave or WaveMC object with two or more channels.

ref

The channel that delays are measured against.

from

Optionally, the start of the region to correlate.

to

Optionally, the end of the region to correlate.

units

Units in which from and to are given, one of "samples", "seconds" (the default), "minutes", or "hours".

method

Correlation method, one of "phat" (the default), "cc", or "envelope" (see Details).

max.delay

Optionally, the largest delay to consider, in seconds. Delays larger than the time sound takes to cross the microphone array are not physically possible, and excluding them stops a spurious correlation peak being returned.

interpolate

If TRUE (the default) the delay is interpolated to a fraction of a sample (see Details).

Details

A positive delay means the sound arrived at that channel later than it arrived at the reference channel, so the reference channel is the closer of the two to the source. The delay of the reference channel against itself is zero.

Cross-correlation is performed over the whole recording unless from and to are given, and a single delay is returned for each channel. Recordings holding more than one event should be cut to each event in turn (see Examples), as a correlation over several events with different directions of arrival has no single peak to find. Cutting is also much the faster way to work, as the whole of whatever is given is transformed at once.

The following methods are available:

  • phat (the default) - the phase transform, in which each frequency contributes to the correlation according to its phase alone (Knapp and Carter 1976). Discarding the magnitudes sharpens the correlation peak and makes the estimate more robust to reverberation, at the cost of weighting quiet frequencies (which are mostly noise) as heavily as loud ones.

  • cc - unweighted cross-correlation, normalised so that the returned correlation is between -1 and 1. Better suited to recordings with a poor signal to noise ratio, and to narrowband sounds.

  • envelope - cross-correlation of the Hilbert amplitude envelopes of the channels rather than of the waveforms themselves, as seewave::corenv() does. The only method of the three that works on a sound whose waveform does not stay coherent between microphones, which is the usual situation for the broadband pulses of insects and for microphones far enough apart that the path to each differs. Delays are resolved only to the width of a feature of the envelope, so it is the least precise of the three where the others work at all.

The delay found is a whole number of samples, which at the sample rates used for field recording is a coarse measure of direction. interpolate fits a parabola to the correlation peak and its two neighbours to estimate the delay to a fraction of a sample.

Value

A data frame with one row per channel, holding the channel number, the channel name (NA if the channels are not named), the delay in seconds, the delay in samples, and the height of the correlation peak.

References

Knapp C, Carter GC (1976). “The generalized correlation method for estimation of time delay.” IEEE Transactions on Acoustics, Speech, and Signal Processing, 24(4), 320–327.

See Also

bearing(), which turns the delays into a direction.

Examples

# A noise reaching the second channel of a recording 20 samples after
# it reaches the first.
n <- tuneR::noise(kind="white", duration=5000, samp.rate=48000)
w <- tuneR::WaveMC(
  cbind(n@left[101:4900], n@left[81:4880]),
  samp.rate = 48000,
  bit = 32,
  pcm = FALSE
)
tdoa(w)

# Only the middle of the recording, and only delays that an array 1m across
# could produce.
tdoa(w, from=0.02, to=0.08, max.delay=1/soundSpeed())

## Not run: 
# Delays for each of several events in a recording, each 100ms long
w <- readAudio("array.wav")
events <- c(3.2, 8.7, 12.1)
lapply(events, function(t) tdoa(w, from=t, to=t+0.1))

## End(Not run)

An S4 class to represent a TimeRegion within a Wave object.

Description

An S4 class to represent a TimeRegion within a Wave object.

Slots

from

Start position

to

End position

unit

Time unit (one of seconds, minutes, hours)


Samples per time period

Description

Calculates the number of samples for a given duration of a wave

Usage

tSamples(time = 1, wave = NULL, samp.rate = NULL)

Arguments

time

The duration in seconds

wave

A Wave object containing pulses. Its sample rate is used, so it cannot be given alongside samp.rate.

samp.rate

Integer sampling rate

Value

Number of samples

Examples

tSamples(10, samp.rate=44100)
## Not run: 
tSamples(10, wave=sheep)

## End(Not run)

Typical volumes

Description

Typical volumes of everyday things.

Usage

typicalVolume(thing = NA_character_)

Arguments

thing

Volume of thing, if missing then returns all volumes

Value

Typical volume of thing in dBA, or if no thing parameter a data frame of all volumes

Examples

typicalVolume()
typicalVolume("rocket launch")

Converts a timezone offset into a rotation

Description

Given a timezone offset in hours returns a rotation in radians to apply to values for a diel plot.

Usage

tzRot(tz, init = pi)

Arguments

tz

Timezone numeric

init

Initial rotation. Defaults to pi.

Value

The rotation of the plot, in radians.


Untag a TaggedWave or TaggedWaveMC object

Description

This function takes a TaggedWave/TaggedWaveMC object (or a list of such objects) and returns a corresponding Wave/WaveMC object (or list of such objects).

Usage

untagWave(w)

Arguments

w

A TaggedWave or TaggedWaveMC object (or list of such objects).

Value

A Wave or WaveMC object.

Examples

## Not run: 
w <- noise("white")
tw <- tagWave(w)
w2 <- untagWave(tw)

## End(Not run)

Upsample a wave

Description

Used to upsample a Wave object. The upsampled sample rate must be an natural multiple of the current sample rate.

Usage

upsample(wave, upsample.rate, method = "basic")

Arguments

wave

Wave object to upsample.

upsample.rate

The sample rate to upsample to.

method

"basic" for linear, or a function to interpolate NAs in a vector

Value

A resampled Wave object

Examples

wave <- tuneR::sine(4000, samp.rate=44100)
wave2 <- upsample(wave, 88200)

Check an object is a Wave object

Description

Helper function to test that the input is a Wave object. Will create an error if not.

Usage

validateIsWave(wave)

Arguments

wave

Object to test

Value

The Wave object unchanged. An error is raised if it is not a Wave object.


WaveFilter object for audio filters

Description

A WaveFilter object is an object containing information necessary for the filterWave() function to apply the filter to a Wave or TaggedWave object. This is designed to allow a pipe operator (either magrittr or base R) to be used to apply filters to a Wave in a pipeline. If used with a TaggedWave object the function adds information to the processing slot documenting its action.

Slots

description

Description of the filter.

func

Name of function.

params

List of additional parameters to pass to the function.


Get the wavelength from frequency and speed of sound

Description

Calculates the wavelength of a sound wave given the frequency and speed of sound in that medium.

Usage

wavelength(frequency, speed = soundSpeed(medium = "air"), unit = "m")

Arguments

frequency

Frequency of the sound in Hertz

speed

Speed of sound (defaults to the speed of sound in air)

unit

Unit to return the wavelength in, either "m" or "cm"

Value

Wavelength of the sound in the unit specified

Examples

wl <- wavelength(1000)
wl <- wavelength(1000, speed=soundSpeed(medium="steel"))
wl <- wavelength(1000, unit="cm")

Windowing Function for Wave Objects

Description

Separates a Wave object into windows of a defined length and runs a function on the window section. Windows may overlap, and the function can make use of 'parallel' package for multi-core processing. It will also show a progress bar if the 'pbapply' package is installed.

Usage

windowing(
  wave,
  window.length = 1000,
  FUN,
  window.overlap = 0,
  bind.wave = FALSE,
  complete.windows = TRUE,
  cluster = NULL,
  ...
)

Arguments

wave

A Wave object or filename. Using filenames may save loading an entire large file into memory.

window.length

The length of the analysis window (in samples).

FUN

FUN to be applied to windows.

window.overlap

The overlap between successive windows (in samples), a negative value will result in a gap between windows.

bind.wave

If TRUE and FUN returns wave objects, then these are combined into a single object

complete.windows

If TRUE (default) the final window will not be processed unless it has a length equal to window.length.

cluster

A cluster form the 'parallel' package for multi-core computation.

...

Additional parameters to FUN

Value

A list of the results of FUN for each window, or a single Wave object if bind.wave is TRUE.

Examples

## Not run: 
windowing(wave, window.length=1000, FUN=duration, window.overlap=0, bind.wave=TRUE)

## End(Not run)

Save a time region defined by an Annotation object as a Wave file

Description

Save a time region defined by an Annotation object as a Wave file

Usage

writeAnnotationWave(annotation, wave = NULL)

Arguments

annotation

An Annotation object.

wave

(Optional) A Wave object, if not given will load the wave file from Annotation filename.

Value

No return value, called for its side effect of writing a Wave file.


Write an Audacity label file

Description

Writes a list of Annotation objects to an Audacity label file.

Internally this uses the write.audacity() function from the seewave package (Sueur et al. 2008).

Usage

writeAudacityLabels(annotations, file)

Arguments

annotations

A list of Annotation objects.

file

Path to the Audacity label file.

Value

No return value, called for its side effect of writing a label file.

References

Sueur J, Aubin T, Simonis C (2008). “Seewave, a free modular tool for sound analysis and synthesis.” Bioacoustics, 18(2), 213–226.


Write an audio file

Description

This function writes a Wave or WaveMC object to a file, it is an abstraction function for various specific audio writing functions and is the counterpart of readAudio(). WAVE files are written directly, other formats are written by converting a temporary WAVE file using the av package. If the av package is not available FLAC files can also be written using the flac program via the seewave package (Sueur et al. 2008).

Usage

writeAudio(wave, file, mime = "auto", ...)

Arguments

wave

A Wave or WaveMC object to write. The channels of a WaveMC object must be named, as the name is what records the position of each channel in the file (see tuneR::MCnames). Tagged waves (see tagWave()) are written as the audio they contain, the tags are not saved.

file

File to write.

mime

MIME type of the file to write, or "auto" (the default) to determine it from the file extension (see Details).

...

Additional arguments passed to the function performing the write: tuneR::writeWave() for WAVE files, and av::av_audio_convert() (e.g. bit_rate) for other formats.

Details

The MIME type of the file to write is determined from the file extension, unless it is given in the mime argument. Any format supported by the encoders available to the av package can be written, commonly used types include:

  • audio/x-wav (.wav) - written by tuneR::writeWave().

  • audio/flac (.flac)

  • audio/mpeg (.mp3)

  • audio/mp4 (.m4a)

Which other formats can be written depends on the encoders available to the av package, and some encoders accept only certain sample rates (e.g. Opus requires 48kHz or one of its divisors).

Audio written to a lossy format (e.g. MP3) will not be identical to the audio held in the object, and audio written to a format that does not support the bit depth or channel count of the object will be converted by the encoder.

Value

The path of the file written, invisibly.

References

Sueur J, Aubin T, Simonis C (2008). “Seewave, a free modular tool for sound analysis and synthesis.” Bioacoustics, 18(2), 213–226.

Examples

w <- tuneR::sine(440, duration=1000)
f <- tempfile(fileext=".wav")
writeAudio(w, f)
file.remove(f)

## Not run: 
# Requires the av package
writeAudio(w, "tone.mp3")
writeAudio(w, "tone.flac")

## End(Not run)

Calculate the fraction of a year given by a value

Description

Given an object that can be coerced to POSIXlt, return the fraction of a year represented by the object.

Usage

yearlyFraction(t, year = 2022, input = "POSIX", unit = "radians")

Arguments

t

Object to be converted to a fraction

year

Year to calculate fractions of (allows for leap years)

input

One of POSIXlt (default)

unit

If set to radians outputs a position around a circle. If set to fraction outputs the raw fraction.

Value

The position of the date within the year, in radians or as a fraction of a year.


Generate labels for a yearly plot

Description

Generates monthly labels for a yearlyPlot().

Usage

yearlyLabels()

Value

A character vector of twelve month abbreviations.


Create a yearly plot

Description

ToDO......

Usage

yearlyPlot(
  year = 2022,
  lat,
  lon,
  limits = c(0, 2),
  plot = NULL,
  method = "plotrix",
  legend = FALSE
)

Arguments

year

Year to plot (allows for leap years).

lat

Numeric latitude.

lon

Numeric longitude.

limits

Plotting limits of the daylight regions, default to c(1,2)

plot

Character vector of components to plot

method

Plotting library to use

legend

Whether to show a legend

Value

Called for its side effect of drawing a plot. The return value is that of the underlying plotting function and should not be relied on.


Generate positions of labels for a yearly plot

Description

Generates positions for monthly labels of a yearlyPlot() in radians. The positions can either be for the start of the month, or middle of the month.

Usage

yearlyPositions(year = 2022, format = "months")

Arguments

year

Year to calculate

format

One of months, mid-months, days

Details

The function allows for leap years if the year parameter is provided.

Value

A numeric vector of label positions, in radians.


Identify zero crossings in a Wave object

Description

Returns a vector of the position (in samples) of zero crossings in a Wave object

Usage

zerocross(wave)

Arguments

wave

A Wave object

Value

A vector of zero crossing locations

Examples

## Not run: 
zerocross(sheep)

## End(Not run)

Zero spectrum

Description

This function takes a spectrum from seewave and creates a new zero-valued spectrum with the same structure.

Usage

zeroSpectrum(s1)

Arguments

s1

Spectrum to emulate the structure of.

Value

A zero-valued spectrum.

Examples

## Not run: 
zeroSpectrum(spec)

## End(Not run)