Python code to analyze and extract frequencies from a wav file

My background is in python, but I am relatively new to numpy, so please bear with me if I make any mistakes.

Currently, I am working on reading a .wav file that contains multiple frequencies separated by periods of silence. Up until now, I have been successful in extracting the values and identifying the sections within the file where there is sound. My next goal is to apply Discrete Cosine Transform to calculate the frequencies from these segments (reference: how to extract frequency associated with fft values in python)

However, I encountered an error:

index 46392 is out of bounds for axis 0 with size 25

This is the code snippet where the error occurs:

import wave
import struct
import numpy as np

def isSilence(windowPosition):
    sumVal = sum([x*x for x in sound[windowPosition:windowPosition+windowSize+1]])
    avg = sumVal / windowSize
    if avg <= 0.0001:
        return True
    else:
        return False

# Read from the wav file
sound_file = wave.open('test.wav', 'r')
file_length = sound_file.getnframes()
data = sound_file.readframes(file_length)
sound_file.close()
data = struct.unpack('{n}h'.format(n=file_length), data)
sound = np.array(data)

i = 0
windowSize = 2205
windowPosition = 0
listOfLists = []
listOfLists.append([])
maxVal = len(sound) - windowSize

while True:
    if windowPosition >= maxVal:
        break
    if not isSilence(windowPosition):
        while not isSilence(windowPosition):
            listOfLists[i].append(sound[windowPosition:windowPosition + windowSize + 1])
            windowPosition += windowSize
        listOfLists.append([])
        i += 1
    windowPosition += windowSize

frequencies = []

for signal in listOfLists:
    if not signal:
        break
    w = np.fft.fft(signal)
    freqs = np.fft.fftfreq(len(w))
    l = len(signal)
    
    imax = np.argmax(np.abs(w))
    fs = freqs[imax]

    freq = imax * fs / l
    frequencies.append(freq)

print(frequencies)

In addition, here is the traceback message:

Traceback (most recent call last):
  File "final.py", line 61, in <module>
    fs = freqs[imax]
IndexError: index 46392 is out of bounds for axis 0 with size 21

Answer №1

My mistake was assuming that listOfLists was a list of lists, when in fact it was a list of list of lists. The line:

        listOfLists[i].append(sound[windowPosition:windowPosition+ windowSize+1])

was adding a list each time, but I incorrectly thought it was adding elements to an existing list.

For example, if listOfLists looked like this:

[ [1,2,3] ]

Then, executing listOfLists[0].append([4,5,6]) would result in:

[ [ [1,2,3],[4,5,6] ] ]

However, my expectation was:

[ [1,2,3,4,5,6] ]

By replacing the problematic line with the code below, I was able to resolve the issue:

for v in sound[windowPosition:windowPosition+windowSize+1]:
            listOfLists[i].append(v)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for optimizing session.add with various relationships to improve performance

Below is the model structure of my source code, represented as an array in a dictionary format. # data structure user_list = [{user_name: 'A', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8feeeeeecfe ...

Preserve the status of the main page in tkinter

I have been working on creating a selection page at the top of my root page in an App using the tk.Toplevel() function in tkinter. The new page features an add button which generates new options on the selection page. Here is a simplified version of my cod ...

The cross validation estimator encountered an invalid parameter, causing a value error

While working on parameter tuning for an SVM model, I encountered an issue with the gamma value. Despite trying three different values for gamma, I received an error stating that the parameter is not valid for the estimator: Invalid parameter gamma for e ...

PyQt5 Code in Eclipse (PyDev) experiencing exception without traceback information retrieved

Although this question may sound familiar, it remains unanswered for over a year. I am sharing more details in hopes of finally getting a resolution. The problem arises when the code enters PyQt5's loops and a crash occurs without displaying the trac ...

Python script saves function results to a file

Is it more efficient to pass 'file' as an argument to multiple functions and append output, or is there a smarter way to handle this? Thank you! Output: FileA: OutA1, OutA2 FileB: OutB1, OutB2 (python2.7) def taskA1_func: <code> for ...

Stacked components create visual interest in histogram

Imagine having a set of values measured daily for the past 90 days. Displaying these values in a histogram can be enhanced by visually segmenting each bar to highlight where measurements are concentrated within specific time frames throughout those 90 days ...

Is there a way to remove a key-value pair from a dictionary based on the values of the surrounding keys?

I have a puzzling question that requires some thought to solve. Consider the following dictionary: dictionary = {"first":["a", "b", "c"], "second":["a", "c", "d" ...

Pong Pygame Not Refreshing Scores

I'm having an issue with my score not updating correctly. Whenever a player scores, the debugger shows 0's. Here are the variables for tracking the scores. player_score = 0 opponent_score = 0 basic_font = pygame.font.Font('freesansbold.ttf& ...

Locate a specific condition within my document and display the entire row using Python

def novice(): dataFile = "studentgrades.csv" fileData = open(dataFile, "r") userScores = [] if "novice" in row print (row) fileData.close() I have attempted to write this function but I'm u ...

What is the process for clicking a button in Selenium Python that lacks a "select" tag and only becomes clickable after fulfilling certain conditions?

Currently, I am working on automating the process of downloading files. To locate these files, I need to interact with two dropdown menus: one named 'Select Period' where I choose a date, and the other named 'Select File Type' where I s ...

Can the python-shell package be used to install python packages in Node JS?

Just learned that Python scripts can be run in Node JS using the npm package mentioned below. python-shell Wondering if it's feasible to install python packages with this library, like pip install package I have to import some libraries to interact ...

Discovering all information within a defined timeframe

I'm currently working on an iPython notebook where I aim to display a graph of data points within a specific timeframe. Most of the coding is complete, but I need assistance in enabling the selection of a start and end date, after which the program wi ...

What types of events can be used to trigger the start of HTML5 audio playback in mobile Chrome?

When it comes to mobile browsers, Audio elements require user action before play can start. The click event usually satisfies this requirement, but touchstart doesn't seem to be an acceptable initiating event in Chrome on Android or iOS. (Refer below ...

What is the best way to extract data from multiple pages with varying xpaths in Selenium?

Seeking assistance with scraping a sequence of pages similar to the following: . The structure of the URLs is straightforward -- increment the number after "precinctreport" to navigate to subsequent pages. Specifically, I am interested in extracting only ...

Having trouble locating a webpage using BeautifulSoup based on its URL

Currently, I am utilizing Python along with Selenium for the purpose of extracting all links from the results page of a particular search site. Regardless of what term I enter on the previous screen, the URL for any search conducted on the results page rem ...

Tips for retrieving the URL of the selected article, rather than the Google News site

When you run the code provided, it randomizes categories and selects the first article from a new site. However, after waiting for 10 seconds for the site to load using time.sleep(10), the issue arises where instead of collecting the URL of the newly loade ...

Adding information to a MySQL database table with Python

As a Python beginner, I am attempting to insert JSON file data into my database table using Python. However, despite not encountering any errors, I only receive the message: Tweet number 49634 is uploading to the server I'm struggling to identify wh ...

Flask React constantly live at Localhost:5000

My current dilemma involves a rather peculiar situation with my flask/react app. Initially, everything was running smoothly on localhost:5000 via Flask. However, after closing the terminal application, the server continued to run inexplicably. Now, whene ...

Using JSON.load with a one-liner JSON isn't going to give you the desired result

I am dealing with JSON data that comes in two different formats - one is a single line, the other is formatted nicely. JSON A: {"id":1, "name":"BoxH", "readOnly":true, "children":[{ "id":100, "name":"Box1", "readOnly":true, "children":[ { "id":1003, "nam ...

Setting up VirtualenvWrapper

After using sudo pip install virtualenvwrapper to install virtualenvwrapper, I encountered an error when trying to run source bash_profile. The error message I received was: bash: /usr/local/share/python/virtualenvwrapper.sh: No such file or directory Her ...