杰瑞科技汇

Python getframerate() 如何获取音频帧率?

Of course! In Python, getframerate() is a method you'll find primarily in the wave module for handling WAV files and in libraries like pydub that use it under the hood.

Python getframerate() 如何获取音频帧率?-图1
(图片来源网络,侵删)

It tells you the sampling rate of an audio file, which is the number of samples per second used to represent the audio. A higher sampling rate generally means higher audio quality.

Here’s a complete guide covering the most common ways to use it.


Using the Built-in wave Module

This is the most direct and fundamental way to work with WAV files in Python. It doesn't require any external installations.

Basic Example

This code opens a WAV file, gets its frame rate, and then closes the file.

Python getframerate() 如何获取音频帧率?-图2
(图片来源网络,侵删)
import wave
# Make sure you have a 'my_audio.wav' file in the same directory,
# or provide the full path to your file.
file_path = 'my_audio.wav'
try:
    # Open the WAV file in read mode ('rb')
    with wave.open(file_path, 'rb') as wav_file:
        # Get the frame rate (sampling rate)
        framerate = wav_file.getframerate()
        print(f"The file '{file_path}' has a frame rate of: {framerate} Hz")
except FileNotFoundError:
    print(f"Error: The file '{file_path}' was not found.")
except wave.Error:
    print(f"Error: The file '{file_path}' is not a valid WAV file.")

Common Frame Rates and Their Meanings:

  • 8000 Hz: Very low quality, often used for telephony (like a phone call).
  • 22050 Hz: Decent quality, often used for speech and lower-quality audio.
  • 44100 Hz: CD quality. The standard for most digital music.
  • 48000 Hz: Standard for digital video and professional audio.
  • 96000 Hz / 192000 Hz: High-resolution audio, used in professional music production.

Using pydub (A More User-Friendly Library)

pydub is a fantastic library for audio manipulation that simplifies many tasks. It can handle various formats (like MP3, FLAC, etc.) and uses wave internally for WAV files.

First, you need to install it:

pip install pydub

pydub requires an external dependency like FFmpeg to handle non-WAV formats (like MP3). Make sure FFmpeg is installed and accessible in your system's PATH.

Basic Example with pydub

from pydub import AudioSegment
# For MP3, you need ffmpeg installed. For WAV, it's not strictly needed.
# Replace with your file's path.
file_path = 'my_audio.mp3' # or 'my_audio.wav'
try:
    # AudioSegment.from_file() is a versatile way to load audio
    audio = AudioSegment.from_file(file_path)
    # The frame rate is available as an attribute
    framerate = audio.frame_rate
    print(f"The file '{file_path}' has a frame rate of: {framerate} Hz")
except FileNotFoundError:
    print(f"Error: The file '{file_path}' was not found.")

Using librosa (For Audio Analysis and Machine Learning)

librosa is the go-to library for audio analysis in Python. It's often used in machine learning and signal processing tasks. A key feature is that it resamples audio to a default rate (22050 Hz) by default to ensure consistency.

Python getframerate() 如何获取音频帧率?-图3
(图片来源网络,侵删)

First, install it:

pip install librosa

Basic Example with librosa

Notice how librosa gives you the original rate, but also resamples the audio for analysis.

import librosa
file_path = 'my_audio.wav' # or 'my_audio.mp3'
try:
    # sr=None tells librosa to NOT resample and to keep the original rate
    y, sr = librosa.load(file_path, sr=None)
    # 'sr' now holds the original sampling rate
    print(f"The original frame rate of '{file_path}' is: {sr} Hz")
    # 'y' is the audio data, resampled to the default rate (22050 Hz)
    # if you had used librosa.load(file_path) without sr=None
    default_sr = y.shape[0] / librosa.get_duration(y=y) # A way to see the default rate
    print(f"If resampled, the default rate would be: {int(default_sr)} Hz")
except FileNotFoundError:
    print(f"Error: The file '{file_path}' was not found.")

Using soundfile (A Powerful Alternative)

soundfile is another excellent library for reading and writing audio files. It's known for its speed and support for a wide range of formats.

First, install it:

pip install soundfile

Basic Example with soundfile

import soundfile as sf
file_path = 'my_audio.wav' # or 'my_audio.flac'
try:
    # soundfile.read() returns the audio data and the sample rate
    audio_data, samplerate = sf.read(file_path)
    # 'samplerate' holds the frame rate
    print(f"The file '{file_path}' has a frame rate of: {samplerate} Hz")
    print(f"The audio data has a shape of: {audio_data.shape}")
except FileNotFoundError:
    print(f"Error: The file '{file_path}' was not found.")

Summary: Which One Should You Use?

Library Best For Key Feature Installation
wave Simple WAV file operations, scripts with minimal dependencies. Built-in, no external installs needed. import wave
pydub General audio manipulation (format conversion, splitting, effects). Very high-level, easy-to-use API. pip install pydub
librosa Audio analysis, machine learning, feature extraction. Resamples by default for consistency, powerful analysis tools. pip install librosa
soundfile High-performance I/O, reading/writing many formats. Fast, supports many formats, returns rate directly. pip install soundfile

For just getting the frame rate of a WAV file, the built-in wave module is perfectly sufficient. For more complex tasks or different audio formats, pydub or soundfile are excellent choices.

分享:
扫描分享到社交APP
上一篇
下一篇