Claude Code for ossaudiodev: Python Linux OSS Audio Device — Claude Skills 360 Blog
Blog / AI / Claude Code for ossaudiodev: Python Linux OSS Audio Device
AI

Claude Code for ossaudiodev: Python Linux OSS Audio Device

Published: October 27, 2028
Read time: 5 min read
By: Claude Skills 360

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.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free