[파이썬] pydub 오디오 파일 검색 기능

pydub logo

pydub is a powerful Python library for processing audio files in various formats. It provides an extensive set of functionalities to manipulate and analyze audio files. In this blog post, we will explore how to implement an audio file search feature using pydub in Python.

Installing pydub

Before getting started, let’s install pydub library. Open your terminal or command prompt and run the following command:

pip install pydub

Searching for Audio Files

To implement the audio file search functionality, we need to perform the following steps:

  1. Define the directory where the audio files are stored.
  2. Retrieve all the audio files in that directory.
  3. Filter the audio files based on specific criteria, such as file format or duration.
  4. Display the matching audio files.

Let’s look at the code snippet below to understand how to achieve this:

from pydub.utils import make_chunks
import os

def search_audio_files(directory, file_format, duration):
    search_results = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith(file_format):
                audio_file_path = os.path.join(root, file)
                audio = AudioSegment.from_file(audio_file_path)

                # Check if audio file duration matches the search criteria
                if audio.duration_seconds <= duration:
                    search_results.append(audio_file_path)
    
    return search_results

# Example usage
directory = '/path/to/audio/directory'
file_format = '.mp3'
max_duration = 60 # seconds
results = search_audio_files(directory, file_format, max_duration)

for audio_file in results:
    print(audio_file)

In the above code, we use the os.walk() function to iterate through all the directories and files within the specified directory. We then filter the files based on the desired file format ('.mp3' in this example). We use the AudioSegment.from_file() method to load the audio file and retrieve its duration using the duration_seconds attribute.

By specifying a maximum duration, we can further filter the matching audio files. Finally, the code returns a list of audio file paths that match the search criteria.

Conclusion

With just a few lines of code, we can implement an audio file search feature using pydub in Python. This can be useful in various applications, such as organizing and managing large collections of audio files.

pydub offers a range of other powerful features, such as audio manipulation, conversion, and effects. Check out the official documentation for more information on how to leverage this library for audio processing tasks.

Now it’s your turn to explore and experiment with pydub! Happy coding!

Note: Make sure to have the necessary permissions to access the audio files on your system.