Expand description
§soundio-rs
The soundio-rs crate is a wrapper for libsoundio.
The API closely follows the libsoundio so it is fairly low level but much safer. Most of the libsoundio API is exposed.
Some examples are included that are roughly equivalent to the examples in libsoundio.
§Basic Usage
First you must create a new instance of the library using Context::new()
as follows.
let ctx = soundio::Context::new();
This will never fail except for out-of-memory situations in which case it panics (this is standard Rust behaviour).
Next you can connect to a backend. You can specify the backend explicitly, but the simplest thing is to leave it unspecified, in which case they are all tried in order. You can also set the name of the app if you like.
ctx.set_app_name("Player");
ctx.connect()?;
Assuming that worked ok, you can now find a device (or devices) to play or record from. However before you can open any devices you must flush events like this.
ctx.flush_events();
The simplest way to open a device is to just open the default input or output device as follows.
let dev = ctx.default_input_device().expect("No input device");
However please don’t only use that option. Your users will hate you when they have to work out
how ALSA’s undocumented and convoluted .asoundrc
config systems works just to have your app use
a different sound card.
To let the user select the output device you can make use of Context::input_devices()
and Context::output_devices()
.
Onces the device has been opened, you can query it for supported formats and sample rates.
if !dev.supports_layout(soundio::ChannelLayout::get_builtin(soundio::ChannelLayoutId::Stereo)) {
return Err("Device doesn't support stereo".to_string());
}
if !dev.supports_format(soundio::Format::S16LE) {
return Err("Device doesn't support S16LE".to_string());
}
if !dev.supports_sample_rate(44100) {
return Err("Device doesn't 44.1 kHz".to_string());
}
If all is well we can open an input or output stream. You can only open an input stream on an input
device, and an output stream on an output device. If a physical device supports input and output it
is split into two Device
instances, with different Device::aim()
s but the same Device::id()
.
To open the stream you need to define some callbacks for reading/writing to it. The only required one is the read/write callback. You also need to specify the latency in seconds, which determines how often your callback is called.
let mut input_stream = dev.open_instream(
44100,
soundio::Format::S16LE,
soundio::ChannelLayout::get_builtin(soundio::ChannelLayoutId::Stereo),
2.0,
read_callback,
None::<fn()>,
None::<fn(soundio::Error)>,
)?;
read_callback
is a callback that takes an InStreamReader
or OutStreamWriter
, something like this.
fn read_callback(stream: &mut soundio::InStreamReader) {
let frame_count_max = stream.frame_count_max();
if let Err(e) = stream.begin_read(frame_count_max) {
println!("Error reading from stream: {}", e);
return;
}
for f in 0..stream.frame_count() {
for c in 0..stream.channel_count() {
do_something_with(stream.sample::<i16>(c, f));
}
}
}
In memory samples are stored LRLRLRLR rather than LLLLRRRR so for optimisation purposes it is probably better to loop over frames and then channels, rather than the other way around (though I’ve not tested the actual effect this has).
Finally call InStream::start()
to start your stream.
input_stream.start()?;
There are some extra details regarding Context::wait_events()
and Context::wakeup()
, and you
will likely want to use scoped threads via the crossbeam
crate for those. The best way to learn
more is to see the examples.
§Examples
§list_devices
This example is very similar to libsoundio’s list_devices example. It simply lists the devices on the system. It currently has no command line options.
§recorder
This records audio to a wav file until you press enter. Note that it actually writes the wav file in the audio callback which is a bad idea because writing files can be slow. In a real program it might be better to have a separate thread for buffered file writing.
§player
The opposite of recorder - it plays a wav file. This also has the flaw of reading the file in the audio callback. Also currently it does not exit when the file ends because I am still learning Rust.
§sine
A very simple example that plays a sine wave.
§Bugs, Credits, etc.
libsoundio was written by Andrew Kelley (legend). This wrapper was written by Tim Hutt. There is another wrapper available here if this one doesn’t satisfy you for some reason. It is developed on github. Bugs, suggestions and praise are welcome!
Modules§
- native
- This module provides some aliases for native endian formats, and foreign endian formats.
Structs§
- Channel
Layout - A
ChannelLayout
specifies a number of channels, and theChannelId
of each channel. AChannelLayout
also has a name, though it is really only for display purposes and does not affect execution at any point. - Context
Context
represents the libsoundio library context.- Context
User Data - Device
- Device represents an input or output device.
- InStream
- InStream represents an input stream for recording.
- InStream
Reader InStreamReader
is passed to the read callback and can be used to read from the stream.- InStream
User Data - The callbacks required for an instream are stored in this object. We also store a pointer
to the raw instream so that it can be passed to
InStreamReader
in the write callback. - OutStream
- OutStream represents an output stream for playback.
- OutStream
User Data - OutStream
Writer OutStreamWriter
is passed to the write callback and can be used to write to the stream.- Sample
Rate Range - Devices report their supported sample rates as ranges. For non-range sample
rates
min
andmax
are the same. - Software
Latency - This is used for reporting software latency, that is the latency not including
latency due to hardware. It is returned by
Device::software_latency()
. - i24
- u24
Enums§
- Backend
- Backend indicates one of the supported audio backends.
- Channel
Id - ChannelId indicates the location or intent of a channel (left, right, LFE, etc.).
- Channel
Layout Id - Built-in channel layouts for convenience.
These can be used with
ChannelLayout::get_builtin()
. - Device
Aim - Used to identify devices as input or output. In this library
all devices are either input or output. If a physical device supports
both it is exposed as two devices with the same id, but with different
aims returned by
Device::aim()
. - Endian
- This is a small helper type to find the endianness of a sample format.
- Error
- Error is the error return type for many functions. These are
taken directly from libsoundio. It supports conversion to
String
using theFrom
trait. - Format
- Format defines the format of the samples. In 90% of cases you’ll want
S16LE
, or maybeFloat64LE
.
Traits§
- Sample
- The Sample trait defines functions to convert between the various sample formats. The full range
of the integer sample formats is always used, so
0u16.to_i8()
is -128. Converting between signed and unsigned of the same size is lossless, as is increasing the bit depth.
Functions§
- endianness
- Return the endianness of a sample format.
Format::Invalid
,Format::S8
andFormat::U8
returnEndian::Little
. - have_
backend - Return
true
if libsoundio supports the givenBackend
. - instream_
error_ callback - instream_
overflow_ callback - instream_
read_ callback - This is called when an instream has been read. The
InStreamUserData
struct is obtained from the stream.userdata, then the user-supplied callback is called with anInStreamReader
object. - outstream_
error_ callback - outstream_
underflow_ callback - outstream_
write_ callback - This is called when an outstream needs to be written to. The
OutStreamUserData
struct is obtained from the stream.userdata, then the user-supplied callback is called with anOutStreamWriter
object. - version
- Return the libsoundio version as a tuple, for exaample
(1, 0, 2)
. - version_
string - Return the libsoundio version string, for example
"1.0.2"
.
Type Aliases§
- Result
- Local typedef for results that soundio-rs returns.