Write wav files python

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Reading and Writing .WAV files in Python

License

GPL-3.0, GPL-3.0 licenses found

Licenses found

saisyam/pywav

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

I am building a tool to test SIP applications. I am trying to convert RTP payload which was sent as PCMA/PCMU (mu-law or A-law compression) format. I tried Python Wave module but didn’t work as expected because it will not consider any compression. So I digged a little bit and came up with my own way of creating and reading WAV files by looking at their formats here.

There are two classes WavRead and WavWrite which will perform reading and writing of wave files respectively. Currenlty PCM, PCMU and PCMA formats are supported. You will get the raw data from the RTP stream which you can write into the wave file by providing information about the audio format, number of channels, sample rate etc.

You can install pywav using pip3. No additional dependencies required.

wave_read = pywav.WavRead("") # print parameters like number of channels, sample rate, bits per sample, audio format etc # Audio format 1 = PCM (without compression) # Audio format 6 = PCMA (with A-law compression) # Audio format 7 = PCMU (with mu-law compression) print(wave_read.getparams())
# first parameter is the file name to write the wave data # second parameter is the number of channels, the value can be 1 (mono) or 2 (stereo) # third parameter is the sample rate, 8000 samples per second # fourth paramaer is the bits per sample, here it is 8 bits per sample # fifth parameter is the audio format, here it is 1 meand PCM with no compression. wave_write = pywav.WavWrite("", 1, 8000, 8, 1) # raw_data is the byte array. Write can be done only once for now. # Incremental write will be implemented later wave_write.write(raw data>) # close the file stream and save the file wave_write.close()

About

Reading and Writing .WAV files in Python

Источник

wave — Read and write WAV files¶

The wave module provides a convenient interface to the Waveform Audio “WAVE” (or “WAV”) file format. Only files using WAVE_FORMAT_PCM are supported. Note that this does not include files using WAVE_FORMAT_EXTENSIBLE even if the subformat is PCM.

The wave module defines the following function and exception:

wave. open ( file , mode = None ) ¶

If file is a string, open the file by that name, otherwise treat it as a file-like object. mode can be:

Note that it does not allow read/write WAV files.

A mode of ‘rb’ returns a Wave_read object, while a mode of ‘wb’ returns a Wave_write object. If mode is omitted and a file-like object is passed as file, file.mode is used as the default value for mode.

If you pass in a file-like object, the wave object will not close it when its close() method is called; it is the caller’s responsibility to close the file object.

The open() function may be used in a with statement. When the with block completes, the Wave_read.close() or Wave_write.close() method is called.

Changed in version 3.4: Added support for unseekable files.

An error raised when something is impossible because it violates the WAV specification or hits an implementation deficiency.

Wave_read Objects¶

Wave_read objects, as returned by open() , have the following methods:

Close the stream if it was opened by wave , and make the instance unusable. This is called automatically on object collection.

Returns number of audio channels ( 1 for mono, 2 for stereo).

Returns sample width in bytes.

Returns sampling frequency.

Returns number of audio frames.

Returns compression type ( ‘NONE’ is the only supported type).

Human-readable version of getcomptype() . Usually ‘not compressed’ parallels ‘NONE’ .

Returns a namedtuple() (nchannels, sampwidth, framerate, nframes, comptype, compname) , equivalent to output of the get*() methods.

Reads and returns at most n frames of audio, as a bytes object.

Rewind the file pointer to the beginning of the audio stream.

The following two methods are defined for compatibility with the aifc module, and don’t do anything interesting.

The following two methods define a term “position” which is compatible between them, and is otherwise implementation dependent.

Set the file pointer to the specified position.

Return current file pointer position.

Wave_write Objects¶

Wave_write objects, as returned by open() .

For seekable output streams, the wave header will automatically be updated to reflect the number of frames actually written. For unseekable streams, the nframes value must be accurate when the first frame data is written. An accurate nframes value can be achieved either by calling setnframes() or setparams() with the number of frames that will be written before close() is called and then using writeframesraw() to write the frame data, or by calling writeframes() with all of the frame data to be written. In the latter case writeframes() will calculate the number of frames in the data and set nframes accordingly before writing the frame data.

Changed in version 3.4: Added support for unseekable files.

Wave_write objects have the following methods:

Make sure nframes is correct, and close the file if it was opened by wave . This method is called upon object collection. It will raise an exception if the output stream is not seekable and nframes does not match the number of frames actually written.

Set the number of channels.

Set the sample width to n bytes.

Changed in version 3.2: A non-integral input to this method is rounded to the nearest integer.

Set the number of frames to n. This will be changed later if the number of frames actually written is different (this update attempt will raise an error if the output stream is not seekable).

Set the compression type and description. At the moment, only compression type NONE is supported, meaning no compression.

The tuple should be (nchannels, sampwidth, framerate, nframes, comptype, compname) , with values valid for the set*() methods. Sets all parameters.

Return current position in the file, with the same disclaimer for the Wave_read.tell() and Wave_read.setpos() methods.

Write audio frames, without correcting nframes.

Changed in version 3.4: Any bytes-like object is now accepted.

Write audio frames and make sure nframes is correct. It will raise an error if the output stream is not seekable and the total number of frames that have been written after data has been written does not match the previously set value for nframes.

Changed in version 3.4: Any bytes-like object is now accepted.

Note that it is invalid to set any parameters after calling writeframes() or writeframesraw() , and any attempt to do so will raise wave.Error .

Источник

scipy.io.wavfile.write#

A 1-D or 2-D NumPy array of either integer or float data-type.

  • Writes a simple uncompressed WAV file.
  • To write multiple-channels, use a 2-D array of shape (Nsamples, Nchannels).
  • The bits-per-sample and PCM/float will be determined by the data-type.

Note that 8-bit PCM is unsigned.

IBM Corporation and Microsoft Corporation, “Multimedia Programming Interface and Data Specifications 1.0”, section “Data Format of the Samples”, August 1991 http://www.tactilemedia.com/info/MCI_Control_Info.html

Create a 100Hz sine wave, sampled at 44100Hz. Write to 16-bit PCM, Mono.

>>> from scipy.io.wavfile import write >>> import numpy as np >>> samplerate = 44100; fs = 100 >>> t = np.linspace(0., 1., samplerate) >>> amplitude = np.iinfo(np.int16).max >>> data = amplitude * np.sin(2. * np.pi * fs * t) >>> write("example.wav", samplerate, data.astype(np.int16)) 

Источник

Read and write WAV files using Python (wave)

The wave module in Python’s standard library is an easy interface to the audio WAV format. The functions in this module can write audio data in raw format to a file like object and read the attributes of a WAV file.

The file is opened in ‘write’ or read mode just as with built-in open() function, but with open() function in wave module

wave.open()

This function opens a file to read/write audio data. The function needs two parameters — first the file name and second the mode. The mode can be ‘wb’ for writing audio data or ‘rb’ for reading.

A mode of ‘rb’ returns a Wave_read object, while a mode of ‘wb’ returns a Wave_write object.

Wave_write object has following methods

close() Close the file if it was opened by wave.
setnchannels() Set the number of channels. 1 for Mono 2 for stereo channels
setsampwidth() Set the sample width to n bytes.
setframerate() Set the frame rate to n.
setnframes() Set the number of frames to n.
setcomptype() Set the compression type and description. At the moment, only compression type NONE is supported, meaning no compression.
setparams() accepts parameter tuple (nchannels, sampwidth, framerate, nframes, comptype, compname)
tell() Retrieves current position in the file
writeframesraw() Write audio frames, without correcting.
writeframes() Write audio frames and make sure they are correct.

Following code creates a WAV file with random short integer bytes of 99999 seconds duration.

import wave, struct, math, random sampleRate = 44100.0 # hertz duration = 1.0 # seconds frequency = 440.0 # hertz obj = wave.open('sound.wav','w') obj.setnchannels(1) # mono obj.setsampwidth(2) obj.setframerate(sampleRate) for i in range(99999): value = random.randint(-32767, 32767) data = struct.pack('

Wave_read object methods

close()Close the stream if it was opened by wave module.
getnchannels()Returns number of audio channels (1 for mono, 2 for stereo).
getsampwidth()Returns sample width in bytes.
getframerate()Returns sampling frequency.
getnframes()Returns number of audio frames.
getcomptype()Returns compression type ('NONE' is the only supported type).
getparams()Returns a namedtuple() (nchannels, sampwidth, framerate, nframes, comptype, compname), equivalent to output of the get*() methods.
readframes(n)Reads and returns at most n frames of audio, as a bytes object.
rewind()Rewind the file pointer to the beginning of the audio stream.

Following code reads some of the parameters of WAV file.

import wave obj = wave.open('sound.wav','r') print( "Number of channels",obj.getnchannels()) print ( "Sample width",obj.getsampwidth()) print ( "Frame rate.",obj.getframerate()) print ("Number of frames",obj.getnframes()) print ( "parameters:",obj.getparams()) obj.close()

Output

Number of channels 1 Sample width 2 Frame rate. 44100 Number of frames 99999 parameters: _wave_params(nchannels=1, sampwidth=2, framerate=44100, nframes=99999, comptype='NONE', compname='not compressed')

Источник

Читайте также:  Php ini чем открывать
Оцените статью