Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash· GoogleHugging Face LMArena Human Preference 140K

I have a .wav file of music, what I want is a python file that returns how long the song…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with gpt-4.1-2025-04-14’s answer.
  1. User

    I have a .wav file of music, what I want is a python file that returns how long the song is.

  2. Gemini Assistant

    You're in luck! Python has built-in modules and excellent third-party libraries for handling WAV files. The wave module, which is part of Python's standard library, is perfect for this task as it can directly read the necessary header information (number of frames and frame rate) without loading the entire audio data into memory.

    Here's a Python script that does exactly what you want:


    Method 1: Using the Built-in wave module (Recommended for WAV)

    This method is preferred because it requires no external libraries.

    import wave
    import os
    
    def get_wav_duration(file_path):
        """
        Calculates the duration of a WAV file in seconds.
    
        Args:
            file_path (str): The path to the WAV file.
    
        Returns:
            float: The duration of the WAV file in seconds, or None if an error occurs.
        """
        if not os.path.exists(file_path):
            print(f"Error: File not found at '{file_path}'")
            return None
        
        try:
            with wave.open(file_path, 'rb') as wf:
                frames = wf.getnframes()      # Get the total number of frames
                rate = wf.getframerate()      # Get the frame rate (samples per second)
                duration_seconds = frames / float(rate) # Calculate duration
                return duration_seconds
        except wave.Error as e:
            print(f"Error reading WAV file '{file_path}': {e}")
            print("This might not be a valid WAV file or it's corrupted.")
            return None
        except Exception as e:
            print(f"An unexpected error occurred: {e}")
            return None
    
    if __name__ == "__main__":
        # --- How to use the script ---
        # 1. Save the code above as a Python file (e.g., get_wav_duration.py)
        # 2. Place your .wav music file in the same directory, or provide its full path.
        # 3. Replace 'your_music_file.wav' with the actual name/path of your file.
    
        wav_file_path = 'your_music_file.wav' # <--- IMPORTANT: Change this to your WAV file's path!
    
        duration = get_wav_duration(wav_file_path)
    
        if duration is not None:
            print(f"\n--- WAV File Duration ---")
            print(f"File: {wav_file_path}")
            print(f"Duration: {duration:.2f} seconds")
    
            minutes = int(duration // 60)
            seconds = duration % 60
            print(f"          ({minutes} minutes and {seconds:.2f} seconds)")
            print(f"-------------------------\n")
        else:
            print(f"Could not determine the duration for '{wav_file_path}'.")
    
    

    How to Use It:

    1. Save: Save the code above into a file named get_wav_duration.py (or any other .py name).
    2. Place WAV: Put your .wav music file in the same directory as the Python script, or provide its full path in the wav_file_path variable.
    3. Edit: Change the line wav_file_path = 'your_music_file.wav' to the actual name/path of your WAV file.
    4. Run: Open a terminal or command prompt, navigate to the directory where you saved the file, and run:
      python get_wav_duration.py
      

    You will see output like:

    --- WAV File Duration ---
    File: my_awesome_song.wav
    Duration: 210.50 seconds
              (3 minutes and 30.50 seconds)
    -------------------------
    

    Method 2: Using scipy.io.wavfile (Requires SciPy)

    If you already have scipy installed or plan to use it for other audio processing, this is also a good option.

    First, you need to install scipy: pip install scipy

    import scipy.io.wavfile as wavfile
    import os
    
    def get_wav_duration_scipy(file_path):
        """
        Calculates the duration of a WAV file using scipy.
    
        Args:
            file_path (str): The path to the WAV file.
    
        Returns:
            float: The duration of the WAV file in seconds, or None if an error occurs.
        """
        if not os.path.exists(file_path):
            print(f"Error: File not found at '{file_path}'")
            return None
        
        try:
            # read returns (samplerate, data)
            # data is a NumPy array where the first dimension is the number of samples.
            samplerate, data = wavfile.read(file_path)
            num_samples = data.shape[0]
            duration_seconds = num_samples / float(samplerate)
            return duration_seconds
        except FileNotFoundError:
            print(f"Error: File not found at '{file_path}'")
            return None
        except Exception as e:
            print(f"Error reading WAV file '{file_path}' with SciPy: {e}")
            print("This might not be a valid WAV file, or SciPy couldn't parse it.")
            return None
    
    if __name__ == "__main__":
        wav_file_path = 'your_music_file.wav' # <--- IMPORTANT: Change this to your WAV file's path!
    
        duration = get_wav_duration_scipy(wav_file_path)
    
        if duration is not None:
            print(f"\n--- WAV File Duration (using SciPy) ---")
            print(f"File: {wav_file_path}")
            print(f"Duration: {duration:.2f} seconds")
    
            minutes = int(duration // 60)
            seconds = duration % 60
            print(f"          ({minutes} minutes and {seconds:.2f} seconds)")
            print(f"----------------------------------------\n")
        else:
            print(f"Could not determine the duration for '{wav_file_path}' using SciPy.")
    
    

    Both methods will give you the duration. The wave module is generally sufficient and more lightweight for this specific task as it avoids the scipy dependency.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.