What type of file is the "sound fragment" parameter for audioop?

import audioop
import wave
read = wave.open("C:/Users/Pratik/sampy/cat.wav")
string_wav = read.readframes(read.getnframes())
a = audioop.lin2alaw(string_wav,read.getsampwidth())
print(a)
----------------------------------------------------------
how to convert wav file  to alaw

You may want to look into the wave module. You probably want to open a file in read mode and use readframes to get the sample you need for audiooop.


You can do so by using the wave module

The open() method opens the file and readframes(n) returns (maximum) n frames of audio as a string of bytes, just what audioop wants.

For example, let's say you need to use the avg() method from audioop. This is how you could do it:

import wave
import audioop


wav = wave.open("piano2.wav")
print(audioop.avg(wav.readframes(wav.getnframes()), wav.getsampwidth()))

Outputs:

-2

Also, you may be interested in the rewind() method from the wave module. It puts the reading position back to the beginning of the wav file.

If you need to read through your wav file twice you can write this:

wav = wave.open("piano2.wav")
print(audioop.avg(wav.readframes(wav.getnframes()), wav.getsampwidth()))

# if you don't call rewind, next readframes() call 
# will return nothing and audioop will fail

wav.rewind() 
print(audioop.max(wav.readframes(wav.getnframes()), wav.getsampwidth()))

Or alternatively you can cache the string:

wav = wave.open("piano2.wav")
string_wav = wav.readframes(wav.getnframes())
print(audioop.avg(string_wav, wav.getsampwidth()))
# wav.rewind()
print(audioop.max(string_wav, wav.getsampwidth()))

To answer what exactly a fragment is, it's a bytes object, which is just a string of bytes. I believe that for 8-bit audio files, there would be one byte for each frame for 8-bit audio, two bytes per frame for 16-bit audio, and four bytes for 32-bit audio.