Python’s ossaudiodev module (Linux only) provides direct access to the OSS (Open Sound System) /dev/dsp PCM audio device and /dev/mixer volume controls. import ossaudiodev. open device: dsp = ossaudiodev.open('r'|'w'|'rw') or ossaudiodev.open('/dev/dsp', mode). Set format: dsp.setfmt(ossaudiodev.AFMT_S16_LE) — returns confirmed format; AFMT constants: AFMT_U8, AFMT_S16_LE, AFMT_S16_BE, AFMT_S32_LE. Channels: dsp.channels(2) → actual channel count. Rate: dsp.speed(44100) → actual rate. Write: dsp.write(pcm_bytes). Read: pcm_bytes = dsp.read(n_bytes). Close: dsp.close(). Mixer: mx = ossaudiodev.openmixer(); left, right = mx.get(ossaudiodev.SOUND_MIXER_VOLUME); mx.set(ossaudiodev.SOUND_MIXER_VOLUME, (75, 75)). Mixer channels: SOUND_MIXER_VOLUME (master), SOUND_MIXER_PCM, SOUND_MIXER_LINE, SOUND_MIXER_MIC, SOUND_MIXER_CD. Controls: dsp.reset(), dsp.sync() (blocks until buffer drains), dsp.post() (starts playing immediately). Note: OSS is legacy; modern Linux systems use ALSA — OSS typically available via aoss wrapper or kernel OSS emulation. Claude Code generates PCM playback pipelines, audio capture recorders, volume controllers, WAV-to-OSS players, and OSS hardware diagnostics.
CLAUDE.md for ossaudiodev
## ossaudiodev Stack
- Stdlib: import ossaudiodev (Linux only; fails if /dev/dsp absent)
- Open: dsp = ossaudiodev.open("w") # 'r'=record, 'w'=play, 'rw'=both
- Setup: dsp.setfmt(ossaudiodev.AFMT_S16_LE)
- dsp.channels(2) # stereo
- dsp.speed(44100) # Hz
- Write: dsp.write(pcm_bytes)
- Sync: dsp.sync() # drain buffer before close
- Close: dsp.close()
- Mixer: mx = ossaudiodev.openmixer(); mx.get(ossaudiodev.SOUND_MIXER_VOLUME)
ossaudiodev Linux OSS Audio Pipeline
# app/ossutil.py — PCM playback, record, WAV player, mixer control, diagnostics
from __future__ import annotations
import array
import math
import os
import platform
import struct
import wave
from dataclasses import dataclass
from pathlib import Path
_OSS_AVAILABLE = (
platform.system() == "Linux"
and os.path.exists("/dev/dsp")
)
if _OSS_AVAILABLE:
import ossaudiodev
# ─────────────────────────────────────────────────────────────────────────────
# 1. Device open / configure / close
# ─────────────────────────────────────────────────────────────────────────────
@dataclass
class AudioConfig:
fmt: int # OSS AFMT_* constant
channels: int # 1=mono, 2=stereo
rate: int # Hz
@property
def bytes_per_frame(self) -> int:
"""Bytes per sample frame (all channels combined)."""
fmt_sizes = {
0x8: 1, # AFMT_U8 = 8 (1 byte/sample)
0x10: 1, # AFMT_S8
0x20: 2, # AFMT_S16_LE
0x10000: 2, # AFMT_S16_BE
0x1000: 2, # AFMT_U16_LE
0x2000: 2, # AFMT_U16_BE
0x200: 4, # AFMT_S32_LE
0x400: 4, # AFMT_S32_BE
}
bps = fmt_sizes.get(self.fmt, 2)
return bps * self.channels
def duration_from_bytes(self, n: int) -> float:
"""Convert a byte count to duration in seconds."""
bpf = self.bytes_per_frame
return (n / bpf) / self.rate if bpf and self.rate else 0.0
def open_dsp(
mode: str = "w",
fmt: int | None = None,
channels: int = 2,
rate: int = 44100,
device: str = "/dev/dsp",
):
"""
Open and configure the OSS PCM device.
Returns (dsp_object, AudioConfig).
Raises OSError if device unavailable.
Example:
dsp, cfg = open_dsp("w", channels=2, rate=44100)
dsp.write(pcm_frames)
dsp.sync()
dsp.close()
"""
if not _OSS_AVAILABLE:
raise OSError("ossaudiodev not available (requires Linux + /dev/dsp)")
dsp = ossaudiodev.open(device, mode)
if fmt is None:
fmt = ossaudiodev.AFMT_S16_LE
actual_fmt = dsp.setfmt(fmt)
actual_ch = dsp.channels(channels)
actual_rate = dsp.speed(rate)
return dsp, AudioConfig(fmt=actual_fmt, channels=actual_ch, rate=actual_rate)
def close_dsp(dsp, sync: bool = True) -> None:
"""Optionally sync (drain) the buffer, then close the device."""
if not _OSS_AVAILABLE:
return
try:
if sync:
dsp.sync()
dsp.close()
except ossaudiodev.OSSAudioError:
pass
# ─────────────────────────────────────────────────────────────────────────────
# 2. PCM playback
# ─────────────────────────────────────────────────────────────────────────────
def play_pcm(
frames: bytes,
channels: int = 2,
rate: int = 44100,
fmt: int | None = None,
device: str = "/dev/dsp",
chunk: int = 4096,
) -> None:
"""
Play raw PCM bytes on the OSS device.
Example:
play_pcm(pcm_frames, channels=1, rate=22050)
"""
if not _OSS_AVAILABLE:
raise OSError("ossaudiodev not available")
if fmt is None:
fmt = ossaudiodev.AFMT_S16_LE
dsp, _ = open_dsp("w", fmt=fmt, channels=channels, rate=rate, device=device)
try:
offset = 0
while offset < len(frames):
dsp.write(frames[offset:offset + chunk])
offset += chunk
dsp.sync()
finally:
dsp.close()
def play_wav(path: str | Path, device: str = "/dev/dsp") -> None:
"""
Play a WAV file via the OSS device.
Auto-configures format, channels, and sample rate from WAV headers.
Example:
play_wav("/tmp/alert.wav")
"""
if not _OSS_AVAILABLE:
raise OSError("ossaudiodev not available")
with wave.open(str(path), "rb") as wf:
sampwidth = wf.getsampwidth()
channels = wf.getnchannels()
rate = wf.getframerate()
raw = wf.readframes(wf.getnframes())
# Map WAV sampwidth to OSS AFMT
fmt_map = {1: ossaudiodev.AFMT_U8, 2: ossaudiodev.AFMT_S16_LE}
fmt = fmt_map.get(sampwidth, ossaudiodev.AFMT_S16_LE)
play_pcm(raw, channels=channels, rate=rate, fmt=fmt, device=device)
# ─────────────────────────────────────────────────────────────────────────────
# 3. PCM recording
# ─────────────────────────────────────────────────────────────────────────────
def record_pcm(
duration: float,
channels: int = 1,
rate: int = 44100,
fmt: int | None = None,
device: str = "/dev/dsp",
chunk: int = 4096,
) -> tuple[bytes, AudioConfig]:
"""
Record PCM audio for the given duration (seconds).
Returns (raw_bytes, AudioConfig).
Example:
raw, cfg = record_pcm(3.0, channels=1, rate=22050)
# raw is 3 seconds of mono 44100 Hz 16-bit PCM
"""
if not _OSS_AVAILABLE:
raise OSError("ossaudiodev not available")
if fmt is None:
fmt = ossaudiodev.AFMT_S16_LE
dsp, cfg = open_dsp("r", fmt=fmt, channels=channels, rate=rate, device=device)
total_bytes = int(duration * cfg.rate * cfg.bytes_per_frame)
buf = bytearray()
try:
while len(buf) < total_bytes:
remaining = total_bytes - len(buf)
buf.extend(dsp.read(min(chunk, remaining)))
finally:
dsp.close()
return bytes(buf), cfg
def record_to_wav(
path: str | Path,
duration: float,
channels: int = 1,
rate: int = 44100,
) -> None:
"""
Record PCM audio and save directly to a WAV file.
Example:
record_to_wav("/tmp/recording.wav", duration=5.0)
"""
raw, cfg = record_pcm(duration, channels=channels, rate=rate)
with wave.open(str(path), "wb") as wf:
wf.setnchannels(cfg.channels)
wf.setsampwidth(2) # AFMT_S16_LE → 2 bytes per sample
wf.setframerate(cfg.rate)
wf.writeframes(raw)
# ─────────────────────────────────────────────────────────────────────────────
# 4. Mixer control
# ─────────────────────────────────────────────────────────────────────────────
@dataclass
class MixerChannel:
name: str
left: int # 0–100
right: int # 0–100
def open_mixer(device: str = "/dev/mixer"):
"""Open the OSS mixer device. Remember to call .close()."""
if not _OSS_AVAILABLE:
raise OSError("ossaudiodev not available")
return ossaudiodev.openmixer(device)
def get_volume(channel_id: int | None = None, device: str = "/dev/mixer") -> tuple[int, int]:
"""
Get (left, right) volume for a mixer channel.
Defaults to SOUND_MIXER_VOLUME (master).
Example:
left, right = get_volume()
left, right = get_volume(ossaudiodev.SOUND_MIXER_PCM)
"""
if not _OSS_AVAILABLE:
raise OSError("ossaudiodev not available")
if channel_id is None:
channel_id = ossaudiodev.SOUND_MIXER_VOLUME
mx = ossaudiodev.openmixer(device)
try:
return mx.get(channel_id)
finally:
mx.close()
def set_volume(
left: int,
right: int | None = None,
channel_id: int | None = None,
device: str = "/dev/mixer",
) -> None:
"""
Set volume (0–100) for a mixer channel.
If right is None, mirrors left (mono).
Example:
set_volume(75) # master volume 75% both channels
set_volume(50, 60) # asymmetric stereo
"""
if not _OSS_AVAILABLE:
raise OSError("ossaudiodev not available")
if right is None:
right = left
if channel_id is None:
channel_id = ossaudiodev.SOUND_MIXER_VOLUME
mx = ossaudiodev.openmixer(device)
try:
mx.set(channel_id, (left, right))
finally:
mx.close()
def read_all_channels(device: str = "/dev/mixer") -> list[MixerChannel]:
"""
Read all available mixer channels and their current volumes.
Example:
for ch in read_all_channels():
print(f"{ch.name}: L={ch.left} R={ch.right}")
"""
if not _OSS_AVAILABLE:
return []
_CHANNEL_NAMES = {
getattr(ossaudiodev, "SOUND_MIXER_VOLUME", -1): "VOLUME",
getattr(ossaudiodev, "SOUND_MIXER_BASS", -1): "BASS",
getattr(ossaudiodev, "SOUND_MIXER_TREBLE", -1): "TREBLE",
getattr(ossaudiodev, "SOUND_MIXER_SYNTH", -1): "SYNTH",
getattr(ossaudiodev, "SOUND_MIXER_PCM", -1): "PCM",
getattr(ossaudiodev, "SOUND_MIXER_SPEAKER", -1): "SPEAKER",
getattr(ossaudiodev, "SOUND_MIXER_LINE", -1): "LINE",
getattr(ossaudiodev, "SOUND_MIXER_MIC", -1): "MIC",
getattr(ossaudiodev, "SOUND_MIXER_CD", -1): "CD",
getattr(ossaudiodev, "SOUND_MIXER_IGAIN", -1): "IGAIN",
getattr(ossaudiodev, "SOUND_MIXER_OGAIN", -1): "OGAIN",
}
mx = ossaudiodev.openmixer(device)
results = []
try:
for ch_id, name in _CHANNEL_NAMES.items():
if ch_id < 0:
continue
try:
left, right = mx.get(ch_id)
results.append(MixerChannel(name=name, left=left, right=right))
except ossaudiodev.OSSAudioError:
pass
finally:
mx.close()
return results
# ─────────────────────────────────────────────────────────────────────────────
# 5. Tone generator (for testing without a WAV file)
# ─────────────────────────────────────────────────────────────────────────────
def generate_tone(
frequency: float,
duration: float,
amplitude: float = 0.5,
rate: int = 44100,
channels: int = 1,
) -> bytes:
"""
Generate a pure sine-wave tone as 16-bit signed little-endian PCM.
Example:
tone = generate_tone(440.0, 0.5) # 440 Hz, 0.5 seconds
play_pcm(tone, channels=1, rate=44100)
"""
n_frames = int(duration * rate)
samples = array.array("h") # signed 16-bit
peak = int(amplitude * 32767)
for i in range(n_frames):
val = int(peak * math.sin(2.0 * math.pi * frequency * i / rate))
for _ in range(channels):
samples.append(max(-32768, min(32767, val)))
return samples.tobytes()
# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
print("=== ossaudiodev demo ===")
if not _OSS_AVAILABLE:
print(" ossaudiodev not available (requires Linux + /dev/dsp)")
print(" Demonstrating tone generation only (no audio output):")
tone = generate_tone(440.0, 0.5)
print(f" Generated A440 tone: {len(tone)} bytes, "
f"duration={len(tone) / (2 * 44100):.3f}s")
raise SystemExit(0)
# ── mixer read ─────────────────────────────────────────────────────────────
print("\n--- mixer channels ---")
try:
for ch in read_all_channels():
print(f" {ch.name:<10s} L={ch.left:3d} R={ch.right:3d}")
except ossaudiodev.OSSAudioError as e:
print(f" mixer error: {e}")
# ── master volume ─────────────────────────────────────────────────────────
print("\n--- get/set master volume ---")
try:
old_l, old_r = get_volume()
print(f" current: L={old_l} R={old_r}")
set_volume(70)
new_l, new_r = get_volume()
print(f" after set_volume(70): L={new_l} R={new_r}")
set_volume(old_l, old_r) # restore
print(f" restored to: L={old_l} R={old_r}")
except ossaudiodev.OSSAudioError as e:
print(f" mixer error: {e}")
# ── tone generation ────────────────────────────────────────────────────────
print("\n--- generate_tone + play A440 (0.25s) ---")
try:
tone = generate_tone(440.0, 0.25, amplitude=0.3, channels=2)
play_pcm(tone, channels=2, rate=44100)
print(f" played {len(tone)} bytes ({len(tone) / (2 * 2 * 44100):.3f}s)")
except (ossaudiodev.OSSAudioError, OSError) as e:
print(f" playback error: {e}")
# ── WAV playback ──────────────────────────────────────────────────────────
print("\n--- WAV playback (if file exists) ---")
wav_path = Path("/usr/share/sounds/alsa/Front_Left.wav")
if wav_path.exists():
try:
play_wav(wav_path)
print(f" played {wav_path}")
except Exception as e:
print(f" error: {e}")
else:
print(f" {wav_path} not found — skipping")
print("\n=== done ===")
For the wave + sounddevice (PyPI) alternative — sounddevice.play(data, samplerate) and sounddevice.rec(duration, samplerate, channels) wrap PortAudio and provide cross-platform playback/recording with NumPy array integration, non-blocking callbacks, and WASAPI/CoreAudio/ALSA support — use sounddevice in applications needing Windows/macOS compatibility, low-latency callback-driven audio, or NumPy-based DSP; use ossaudiodev when you need zero external dependencies on Linux, are writing systems code that talks to the OSS kernel interface directly, or need the OSS mixer API for hardware volume control without a sound server. For the subprocess + aplay/ffplay alternative — subprocess.run(["aplay", wav_file]) delegates playback to ALSA’s aplay command-line tool, which handles format negotiation, resampling, and device selection automatically — use aplay/ffplay via subprocess when the audio format may need conversion or when ALSA (not OSS) is the active Linux sound layer; use ossaudiodev when you need programmatic frame-by-frame control, custom mixing, or direct mixer register access without spawning a child process. The Claude Skills 360 bundle includes ossaudiodev skill sets covering open_dsp()/close_dsp()/AudioConfig device management, play_pcm()/play_wav() playback, record_pcm()/record_to_wav() capture, get_volume()/set_volume()/read_all_channels() mixer control, and generate_tone() test signal synthesis. Start with the free tier to try OSS audio patterns and ossaudiodev pipeline code generation.