Open audio file python

Read Audio File With Python wave Module

Python program is famous for the number of modules they provide. Some people mock this amazing language and underestimate the power of using this beautiful module that python programming provides to us. While some of us enjoy using these built-in and third-party python packages.

Python wave module is used to work with the WAV sound format. Though the python wave module does not support the compression and decompression of the WAV files still it is helpful in mono/stereo. If you are looking for the compression of files with Python, you can have a look on here.

What is a WAV File?

WAV stands for Waveform File Format and this is a file format used as a standard for the audio file format. It is developed by IBM and Microsoft collectively. WAV file has better quality than the MP3 file format.

Before going to the FAQ about the wave module, let’s see a few examples of the wave file. We will see the different methods available in the python wave module, which can help us read and write the audio file.

How to Play audio files with Python?

To open an audio file with Python we can use the wave.open(fname) method. We can open the WAV audio file with the help of the open() method available in the wave module. wave is a built-in Python module and we do not need to install it separately.

Example No 1 : Play Audio Files

This Example uses pyauido module, if you do not know about the pyaudio module in Python, please check out it here. In this example, we will see how we can create a function that can make use of the wave.open() method to play a WAV audio file. Below is a Simple callback function to play a wave file. By default, it plays a Ding sound which is a constant in the wave module.

See the following code Example

import wave import time import pyaudio def play_audio_file(fname=wave.DETECT_DING): """ :param str fname: wave file name :return: None """ ding_wav = wave.open(fname, 'rb') ding_data = ding_wav.readframes(ding_wav.getnframes()) audio = pyaudio.PyAudio() stream_out = audio.open( format=audio.get_format_from_width(ding_wav.getsampwidth()), channels=ding_wav.getnchannels(), rate=ding_wav.getframerate(), input=False, output=True) stream_out.start_stream() stream_out.write(ding_data) time.sleep(0.2) stream_out.stop_stream() stream_out.close() audio.terminate() 

Load an Audio file in chunks with Python

We can use the following function that can help us load the audio file not all at once, but rather in chunk of bytes and then play it. We first create the audio object, we open the stream, we then read the data based on the chunk size we start playing it.

Читайте также:  Constructor class c sharp

See the following code Example

import wave import pyaudio def play_wav(fname, chunk=CHUNK): # create an audio object wf = wave.open(fname, 'rb') p = pyaudio.PyAudio() # open stream based on the wave object which has been input. stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True) # read data (based on the chunk size) data = wf.readframes(chunk) # play stream (looping from beginning of file to the end) while len(data) > 0: # writing to the stream is what *actually* plays the sound. stream.write(data) data = wf.readframes(chunk) # cleanup stuff stream.close() p.terminate()

How to Play Audio file from Network with Python?

To receive an audio file from the network and then play it, we can use the about play_wav() function to do so. We first read the data in chunks and then create objects of it, once the objects are created we then write them locally and play them. check out the above code.

How to Play a WAV file with Python?

If the file is located in a local disk then it is much easier for us. To read a WAV file with Python, use the wave.open() method. The wave module is only used for reading the WAV file and the pyaudio is used to actually play the file.

We need to use both the modules, the pyauido module for playing the WAV file and the python wave module to read the WAV file.

Python Example No 2: See the following code Example

import wave import pyaudio def play_file(fname): # create an audio object wf = wave.open(fname, 'rb') p = pyaudio.PyAudio() chunk = 1024 # open stream based on the wave object which has been input. stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True) # read data (based on the chunk size) data = wf.readframes(chunk) # play stream (looping from beginning of file to the end) while len(data) > 0: # writing to the stream is what *actually* plays the sound. stream.write(data) data = wf.readframes(chunk) # cleanup stuff. stream.close() p.terminate()

How to find the length of the audio file with Python?

The python wave module has methods that can help us find the length of an audio file if we do a few calculations. To find the length of an audio file we first have to divide the number of frames by the frame rate. We will get the total duration of the audio file. See the following example where we find the duration of an audio file.

Python Example No 3:See the following Code Example

def audio_length(): wav_file = wave.open(f"filepath.wav", 'r') frames = wav_file.getnframes() rate = wav_file.getframerate() duration = frames / float(rate) wav_file.close() return duration

How to find the duration of any sound file?

The use case of the wave file is that we can find the duration or length of any sound file. To find the duration we have to need two things, frame rate and a number of frames. We then divide the number of frames by the frame rate. See the following example.

Читайте также:  Javascript var array value

Python Example No 4:See the following code Example

def getSoundFileDuration(fn): ''' Returns the duration of a wav file (in seconds) ''' audiofile = wave.open(fn, "r") params = audiofile.getparams() framerate = params[2] nframes = params[3] duration = float(nframes) / framerate return duration 

How to find if a .wav file is valid or not?

To find the validity of a .wav audio file we need the frame rate and channels then we do the following calculations to find if the .wav file is valid or not. see the following example.Python Example No 5:
See the following code Example

def is_valid_wav(filename): # check the sampling rate and number bits of the WAV try: wav_file = wave.Wave_read(filename) except: return False if wav_file.getframerate() != 16000 or wav_file.getsampwidth() != 2 or wav_file.getnchannels() != 1 \ or wav_file.getcomptype() != 'NONE': return False return True

Summary and Conclusion

In this article, we have seen how we can work with sound files. the Python wave module is explored very well. If you still have any questions please let me know in the comment section. or email me at haxratali0@gmail.com with your contact information.

I am a software Engineer having 4+ Years of Experience in Building full-stack applications.

Источник

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’ .

Читайте также:  Уровень java для android

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 .

Источник

Оцените статью