### Install Prerequisites Source: https://github.com/xavriley/ruby-aubio/blob/master/README.md System dependencies required for building the library. ```bash brew install aubio --with-libsndfile --with-fftw --with-libsamplerate ``` -------------------------------- ### Install Gem Source: https://github.com/xavriley/ruby-aubio/blob/master/README.md Methods for adding the gem to a project or installing it locally. ```ruby gem 'aubio' ``` ```bash $ bundle ``` ```bash $ gem install aubio ``` -------------------------------- ### Complete Error Handling Example Source: https://context7.com/xavriley/ruby-aubio/llms.txt A comprehensive function demonstrating safe audio analysis with error handling for file not found, invalid input, and ensuring resource cleanup using `ensure` and safe navigation (`&.`). ```ruby require 'aubio' # Complete error handling example def safe_analyze(path) audio = Aubio.open(path) { bpm: audio.bpm, beat_count: audio.beats.length, onset_count: audio.onsets.count } rescue Aubio::FileNotFound { error: "File not found: #{path}" } rescue Aubio::InvalidAudioInput { error: "Invalid audio file: #{path}" } ensure audio&.close end result = safe_analyze("/path/to/music.mp3") puts result.inspect ``` -------------------------------- ### Inspect Event Data Source: https://github.com/xavriley/ruby-aubio/blob/master/README.md Example of the Hash structure returned for audio events. ```ruby my_file.onsets.first #=> {s: 0.0, ms: 0.0, start: 1, end: 0} ``` -------------------------------- ### Optional Parameters Source: https://github.com/xavriley/ruby-aubio/blob/master/README.md Configuration options for opening audio files. ```ruby :sample_rate # Fetch the input source, resampled at the given sampling rate. The rate should be specified in Hertz as an integer. If 0, the sampling rate of the original source will be used. Defaults to 0. :bufsize The size of the buffer to analyze, that is the length of the window used for spectral and temporal computations. Defaults to 512. :hopsize ``` ```ruby Aubio.open("/path/to/audio/file", sample_rate: 44100) ``` -------------------------------- ### Run Tests Source: https://github.com/xavriley/ruby-aubio/blob/master/README.md Command to clean, build, and run the test suite. ```bash $ rake clobber && rake build && rake test ``` -------------------------------- ### Open Audio File Source: https://github.com/xavriley/ruby-aubio/blob/master/README.md Initialize an Aubio object with a path to an audio file. ```ruby my_file = Aubio.open("/path/to/file") ``` -------------------------------- ### Generate Bindings Source: https://github.com/xavriley/ruby-aubio/blob/master/README.md Commands to generate FFI bindings using clang. ```bash brew install aubio --with-libsndfile --with-fftw --with-libsamplerate brew install llvm --with-clang --enable-shared # clone this repo and cd into the root folder, then run LD_LIBRARY_PATH="/usr/local/opt/llvm35/lib/llvm-3.5/lib" ruby aubio-ffi-generator.rb ``` -------------------------------- ### Open Audio Files with Aubio Source: https://context7.com/xavriley/ruby-aubio/llms.txt Initializes an audio source from a file path. Supports custom parameters for sample rate, window size, and analysis-specific settings. ```ruby require 'aubio' # Basic usage - open an audio file with defaults audio = Aubio.open("/path/to/audio/file.wav") # Open with custom parameters audio = Aubio.open("/path/to/file.mp3", sample_rate: 44100, # Sample rate in Hz (default: 44100) window_size: 1024, # Window size for spectral analysis (default: 1024) hop_size: 512, # Hop size between frames (default: 512) pitch_method: 'yinfast', # Pitch detection algorithm confidence_thresh: 0.9, # Pitch confidence threshold (0.2-0.9) minioi: 0.15 # Minimum inter-onset interval in seconds ) # Always close when done to free memory audio.close ``` -------------------------------- ### Handle File Not Found Errors Source: https://context7.com/xavriley/ruby-aubio/llms.txt Catch `Aubio::FileNotFound` exceptions when attempting to open a non-existent audio file. Ensure the file path provided to `Aubio.open` is correct. ```ruby require 'aubio' # Handle file not found begin audio = Aubio.open("/nonexistent/file.wav") rescue Aubio::FileNotFound => e puts "File does not exist" end ``` -------------------------------- ### Handle Already Closed Source Errors Source: https://context7.com/xavriley/ruby-aubio/llms.txt Catch `Aubio::AlreadyClosed` exceptions when attempting to perform an operation on an audio source that has already been closed. Always ensure resources are properly managed and closed. ```ruby require 'aubio' audio = Aubio.open("/path/to/audio.wav") audio.close begin audio.onsets rescue Aubio::AlreadyClosed => e puts "Audio source has already been closed" end ``` -------------------------------- ### Error Handling Source: https://context7.com/xavriley/ruby-aubio/llms.txt Ruby Aubio provides specific exception classes for different error conditions: `FileNotFound` for missing files, `InvalidAudioInput` for unreadable audio formats, and `AlreadyClosed` for operations on closed sources. ```APIDOC ## Error Handling Ruby Aubio provides specific exception classes for different error conditions: - `Aubio::FileNotFound`: Raised when the specified audio file does not exist. - `Aubio::InvalidAudioInput`: Raised when the audio file format is not recognized or is unreadable. - `Aubio::AlreadyClosed`: Raised when attempting to perform an operation on an audio source that has already been closed. ### Method Implicit (raised by methods like `Aubio.open` or operations on `Aubio::Source` objects) ### Endpoint N/A ### Parameters N/A ### Request Example ```ruby require 'aubio' # Handle file not found begin audio = Aubio.open("/nonexistent/file.wav") rescue Aubio::FileNotFound => e puts "File does not exist" end # Handle invalid audio format begin audio = Aubio.open("/path/to/document.pdf") rescue Aubio::InvalidAudioInput => e puts "Not a valid audio file. Is aubio compiled with libsndfile support?" end # Handle already closed source audio = Aubio.open("/path/to/audio.wav") audio.close begin audio.onsets rescue Aubio::AlreadyClosed => e puts "Audio source has already been closed" end # Complete error handling example def safe_analyze(path) audio = Aubio.open(path) { bpm: audio.bpm, beat_count: audio.beats.length, onset_count: audio.onsets.count } rescue Aubio::FileNotFound { error: "File not found: #{path}" } rescue Aubio::InvalidAudioInput { error: "Invalid audio file: #{path}" } finally audio&.close end result = safe_analyze("/path/to/music.mp3") puts result.inspect ``` ### Response #### Error Responses - **`Aubio::FileNotFound`**: Indicates the audio file could not be found. - **`Aubio::InvalidAudioInput`**: Indicates the audio file is not in a supported format or is corrupted. - **`Aubio::AlreadyClosed`**: Indicates an operation was attempted on a closed audio source. ``` -------------------------------- ### Detect Audio Onsets Source: https://context7.com/xavriley/ruby-aubio/llms.txt Identifies attack points in audio files. Returns an Enumerator yielding timing information for each detected onset. ```ruby require 'aubio' audio = Aubio.open("/path/to/drums.wav") # Get all onsets as an array all_onsets = audio.onsets.to_a # => [ # {s: 0.0, ms: 0.0, start: 1, end: 0}, # {s: 0.211, ms: 211.74, start: 0, end: 0}, # {s: 0.440, ms: 440.47, start: 0, end: 0}, # ... # {s: 2.45, ms: 2450.0, start: 0, end: 1} # ] # Iterate through onsets lazily audio.onsets.each do |onset| puts "Onset at #{onset[:s]} seconds (#{onset[:ms]} ms)" puts " Start of file: #{onset[:start] == 1}" puts " End of file: #{onset[:end] == 1}" end # Get first few onsets first_three = audio.onsets.take(3) audio.close ``` -------------------------------- ### Access Audio Features Source: https://github.com/xavriley/ruby-aubio/blob/master/README.md Retrieve extracted audio data as Ruby Enumerators. ```ruby my_file.onsets # list of extracted onsets my_file.pitches # list of extracted pitches my_file.beats # where one would tap their foot # NOT YET IMPLEMENTED # my_file.notes # list of onsets with pitches # NOT YET IMPLEMENTED # my_file.silences # list of silent regions # NOT YET IMPLEMENTED # my_file.mel_frequency_cepstral_coefficients # list of mfccs ``` -------------------------------- ### Calculate BPM of an Audio File Source: https://context7.com/xavriley/ruby-aubio/llms.txt Use the `bpm` method to estimate the tempo of an audio file. It returns 60.0 as a fallback if tempo detection is unreliable. Ensure the audio file path is correct. ```ruby require 'aubio' audio = Aubio.open("/path/to/track.wav") # Get BPM tempo = audio.bpm puts "Estimated tempo: #{tempo.round(2)} BPM" # => "Estimated tempo: 126.66 BPM" # Handle edge cases short_audio = Aubio.open("/path/to/short_clip.wav") bpm = short_audio.bpm if bpm == 60.0 puts "Could not reliably detect tempo (defaulted to 60 BPM)" else puts "Detected tempo: #{bpm.round(1)} BPM" end audio.close short_audio.close ``` -------------------------------- ### Handle Invalid Audio Input Errors Source: https://context7.com/xavriley/ruby-aubio/llms.txt Catch `Aubio::InvalidAudioInput` exceptions when attempting to open a file that is not a valid audio format. This may occur if the file is corrupted or not an audio file, or if aubio lacks support for the format (e.g., missing libsndfile). ```ruby require 'aubio' # Handle invalid audio format begin audio = Aubio.open("/path/to/document.pdf") rescue Aubio::InvalidAudioInput => e puts "Not a valid audio file. Is aubio compiled with libsndfile support?" end ``` -------------------------------- ### Close Audio File Source: https://github.com/xavriley/ruby-aubio/blob/master/README.md Free memory allocated by the underlying C library. ```ruby my_file.close ``` -------------------------------- ### BPM Calculation Source: https://context7.com/xavriley/ruby-aubio/llms.txt Calculates the tempo of an audio file in beats per minute using beat tracking results and interquartile median filtering. Returns 60.0 as a fallback if insufficient beats are detected. ```APIDOC ## BPM Calculation The `bpm` method calculates the tempo of an audio file in beats per minute. It uses the beat tracking results and applies interquartile median filtering to reduce the effect of outliers. Returns 60.0 as a fallback if insufficient beats are detected. ### Method Implicit (called on an Aubio::Source object) ### Endpoint N/A (Method call on an object) ### Parameters None ### Request Example ```ruby require 'aubio' audio = Aubio.open("/path/to/track.wav") # Get BPM tempo = audio.bpm puts "Estimated tempo: #{tempo.round(2)} BPM" # => "Estimated tempo: 126.66 BPM" # Handle edge cases short_audio = Aubio.open("/path/to/short_clip.wav") bpm = short_audio.bpm if bpm == 60.0 puts "Could not reliably detect tempo (defaulted to 60 BPM)" else puts "Detected tempo: #{bpm.round(1)} BPM" end audio.close short_audio.close ``` ### Response #### Success Response (200) - **tempo** (Float) - The estimated tempo in beats per minute. ``` -------------------------------- ### Track Audio Beats Source: https://context7.com/xavriley/ruby-aubio/llms.txt Detects beat locations in audio files. Supports filtering via the minioi parameter to ignore spurious detections. ```ruby require 'aubio' # Open with beat-specific parameters audio = Aubio.open("/path/to/music.wav", minioi: 0.15 # Minimum interval between beats (filters spurious detections) ) # Get all beats beats = audio.beats # => [ # {confidence: 1, s: 0.0, ms: 0.0, sample_no: 0, rel_start: 0.0, rel_end: 0.22}, # {confidence: 0.85, s: 0.48, ms: 480.0, sample_no: 21168, rel_start: 0.22, rel_end: 0.44}, # ... # ] # Iterate through beats audio.beats.each do |beat| puts "Beat at #{beat[:s].round(3)}s" puts " Confidence: #{(beat[:confidence] * 100).round(1)}%" puts " Relative position: #{(beat[:rel_start] * 100).round(1)}%" end # Use minioi to filter for quarter notes at 120bpm (0.5s apart) audio_filtered = Aubio.open("/path/to/music.wav", minioi: 0.5) quarter_beats = audio_filtered.beats puts "Found #{quarter_beats.length} quarter note beats" audio.close ``` -------------------------------- ### Release Memory Resources with close() Source: https://context7.com/xavriley/ruby-aubio/llms.txt Call the `close` method on an Aubio audio source object to release its underlying C memory. This is crucial for preventing memory leaks. Attempting to use a closed source will raise an `AlreadyClosed` exception. ```ruby require 'aubio' audio = Aubio.open("/path/to/audio.wav") # Process audio onsets = audio.onsets.to_a beats = audio.beats # Clean up - REQUIRED to avoid memory leaks audio.close # Attempting to use after close raises exception begin audio.onsets rescue Aubio::AlreadyClosed => e puts "Cannot use closed audio source" end # Pattern for safe resource handling def analyze_file(path) audio = Aubio.open(path) begin { onsets: audio.onsets.to_a, beats: audio.beats, bpm: audio.bpm } ensure audio.close end end ``` -------------------------------- ### Memory Management Source: https://context7.com/xavriley/ruby-aubio/llms.txt Releases the underlying C memory allocated by aubio. This must be called when finished with an audio source to prevent memory leaks. Attempting to use a closed source raises an `AlreadyClosed` exception. ```APIDOC ## Memory Management The `close` method releases the underlying C memory allocated by aubio. This must be called when finished with an audio source to prevent memory leaks. Attempting to use a closed source raises an `AlreadyClosed` exception. ### Method Implicit (called on an Aubio::Source object) ### Endpoint N/A (Method call on an object) ### Parameters None ### Request Example ```ruby require 'aubio' audio = Aubio.open("/path/to/audio.wav") # Process audio onsets = audio.onsets.to_a beats = audio.beats # Clean up - REQUIRED to avoid memory leaks audio.close # Attempting to use after close raises exception begin audio.onsets rescue Aubio::AlreadyClosed => e puts "Cannot use closed audio source" end # Pattern for safe resource handling def analyze_file(path) audio = Aubio.open(path) begin { onsets: audio.onsets.to_a, beats: audio.beats, bpm: audio.bpm } ensure audio.close end end ``` ### Response #### Success Response (200) No direct response, but ensures memory is freed. Subsequent calls on the closed object will raise `Aubio::AlreadyClosed`. ``` -------------------------------- ### Extract Audio Pitches Source: https://context7.com/xavriley/ruby-aubio/llms.txt Extracts MIDI note numbers and confidence scores from audio. Results can be filtered by confidence threshold. ```ruby require 'aubio' # Open with pitch-specific parameters audio = Aubio.open("/path/to/vocals.mp3", pitch_method: 'yinfast', # Options: 'yin', 'yinfast', 'yinfft', etc. confidence_thresh: 0.9 # Higher = more confident detections only ) # Get all detected pitches pitches = audio.pitches.to_a # => [ # {pitch: 62.0, confidence: 0.95, start: 0, end: 0}, # {pitch: 64.0, confidence: 0.92, start: 0, end: 0}, # ... # ] # Iterate and convert MIDI to note names audio.pitches.each do |p| midi_note = p[:pitch].round confidence = (p[:confidence] * 100).round(1) puts "MIDI note: #{midi_note}, Confidence: #{confidence}%" end # Filter for high-confidence pitches only high_confidence = audio.pitches.select { |p| p[:confidence] > 0.95 } audio.close ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.