How to convert a wav file -> bytes-like object?

前端 未结 1 1224
感动是毒
感动是毒 2021-01-03 12:08

I\'m trying to programmatically analyse wav files with the audioop module of Python 3.5.1 to get channel, duration, sample rate, volumes etc. however I can find no documenta

相关标签:
1条回答
  • 2021-01-03 12:28

    file.read() returns a bytes object, so if you're just trying to get the contents of a file as bytes, something like the following would suffice:

    with open(filename, 'rb') as fd:
        contents = fd.read()
    

    However, since you're working with audioop, what you need is raw audio data, not raw file contents. Although uncompressed WAVs contain raw audio data, they also contain headers which tell you important parameters about the raw audio. Also, these headers must not be treated as raw audio.

    You probably want to use the wave module to parse WAV files and get to their raw audio data. A complete example that reverses the audio in a WAV file looks like this:

    import wave
    import audioop
    
    with wave.open('intput.wav') as fd:
        params = fd.getparams()
        frames = fd.readframes(1000000) # 1 million frames max
    
    print(params)
    
    frames = audioop.reverse(frames, params.sampwidth)
    
    with wave.open('output.wav', 'wb') as fd:
        fd.setparams(params)
        fd.writeframes(frames)
    
    0 讨论(0)
提交回复
热议问题