'Error while using tf.audio.encode_wav(). TypeError: Cannot iterate over a scalar tensor

I am writing a code that chops a list of big audio files into tiny clips of uniform length to produce a dataset. Here is the code I have written.

# Code to break recordings into clips of uniform size (Equal number of samples). 

def GenerateDataset(original_audio_files, targetdir, samples = 48000):
    '''
    Generates a folder 'targetdir' with chopped audio file of 'samples' length each.
    '''
    for original_audio in original_audio_files:
        audio_file = tf.io.read_file(original_audio)
        audio, sample_rate = tf.audio.decode_wav(contents=audio_file)

        if not os.path.exists(targetdir):
            os.makedirs(targetdir)

        for n,i in enumerate(range(0,len(audio),samples)):
            if(i+samples < len(audio)):
                clip = audio[i:i+samples]
                print(sample_rate)
                print(clip.shape)
                audio_clip, _ = tf.audio.encode_wav(clip, sample_rate)
                tf.io.write_file(audio_clip,targetdir + "/sample_" + n + ".wav")
            else:
                break

The print(sample_rate) and print(clip.shape) lines produce the following output

tf.Tensor(48000, shape=(), dtype=int32)
(48000, 1)

But then it encounters the following error

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:\Users\ADITHY~1\AppData\Local\Temp/ipykernel_16052/3095087832.py in <module>
      1 #Generate the datasets from the audio file
      2 
----> 3 GenerateDataset(bg_file, "Samples/Background/")
      4 GenerateDataset(droneBl_file, "Samples/BlackDrone/")
      5 GenerateDataset(droneWh_file, "Samples/WhiteDrone/")

C:\Users\ADITHY~1\AppData\Local\Temp/ipykernel_16052/3884474546.py in GenerateDataset(original_audio_files, targetdir, samples)
     17                 print(sample_rate)
     18                 print(clip.shape)
---> 19                 audio_clip, _ = tf.audio.encode_wav(clip, sample_rate)
     20                 tf.io.write_file(audio_clip,targetdir + "/sample_" + n + ".wav")
     21             else:

F:\Softwares\Anaconda\lib\site-packages\tensorflow\python\framework\ops.py in __iter__(self)
    647       raise TypeError("Cannot iterate over a tensor with unknown shape.")
    648     if not shape:
--> 649       raise TypeError("Cannot iterate over a scalar tensor.")
    650     if shape[0] is None:
    651       raise TypeError(

TypeError: Cannot iterate over a scalar tensor.

I'm pretty sure the input isn't a scalar tensor. Any idea why this is happening? How do I fix this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source