Wav to pcm python

Wav to pcm python

How to convert a format file .wav to file. .wav Standard PCM. using.

As far as I understood under PCM, you understand the raw data that is, The sequence of bytes where each (for example is 16-bit) sample is encoded with a 2-byte Signed-16-bit-integer. Samples of course there may be 8 bit, I just mentioned 16-bit. If PCM is something else than raw sample bytes, then my answer will be useful just for those who need raw samples. Such data from WAV can be obtained for example in two ways, one of them is more reliable using the library> Pydub.(Installing Pip Install Pydub. ). The second more top, without libraries, but may not always work, it is better not to use it. Uncompressed WAV Files often have a headline exactly 44 bytes, but not always, then it is completely pure data, as a result, if starting with this offset to read, you will read raw PCM data. Raw PCM data will be in the format in which they were inside WAV coded, i.e. The same bit, the same byte order and the same badge. Both methods are shown below, return bytes of raw data in Data. and Data2. variables. Attention! Use only the first Pydub. -nounted method, the second method is only given for example and will not always work (if the WAV header is not 44 bytes). Try online code!

Import Pydub. With Open ('Sound.wav', 'Rb') AS F: Data= Pydub.Audiosegment (F) .Export (Format= 'Raw'). Read () With Open ('Sound.wav', 'Rb') AS F: F.Seek (44) Data2= F.Read () Assert Data== Data2 

If you need to convert the format from one species to another, for example, from compressed WAV in uncompressed, then we do the following, here Format= ‘WAV’ can be replaced by any format, say ‘Mp3’ or ‘Flac’ :

Import Pydub. With Open ('Sound.wav', 'Rb') AS F, Open ('Sound_out.wav', 'WB') AS FO: FO.WRITE (PYDUB.AUDIOSEGMENT (F) .export (Format= 'Wav'). Read ()) 

@ Msdn.whiteknight Thanks for the information. In fact, 16-bit I mentioned simply for example, we say about what it is talking about speaking about PCM, I did not say that it only the 16-bit happens. Also about the header of 172 bytes, it was for this that I wrote that the first method through the Pydub library is reliable, it is necessary to use it, and the second one after 172 bytes does not always work and it is better not to use it. I just updated the answer by writing big letters does not always work. Arty 2021-04-09 17:28:34

Читайте также:  Example for Frame

Источник

WAV turn PCM

Principle: Remove the file header, data is converted to an INT type.

1 import numpy as np 2 def wav2pcm(wavfile, pcmfile, data_type=np.int16): 3 f = open(wavfile, "rb") 4 f.seek(0) 5 f.read(44) 6 data = np.fromfile(f, dtype= data_type) 7 data.tofile(pcmfile)

PCM turn WAV

Principle: Use the WAVE library, add channel information, sampling bits, sampling rates as the file head, and PCM data is written directly.

 1 import wave 2 def pcm2wav(pcm_file, wav_file, channels=1, bits=16, sample_rate=16000): 3 pcmf = open(pcm_file, 'rb') 4 pcmdata = pcmf.read() 5 pcmf.close() 6 7 if bits % 8 != 0: 8 raise ValueError("bits % 8 must == 0. now bits:" + str(bits)) 9 10 wavfile = wave.open(wav_file, 'wb') 11 wavfile.setnchannels(channels) 12 wavfile.setsampwidth(bits // 8) 13 wavfile.setframerate(sample_rate) 14 wavfile.writeframes(pcmdata) 15 wavfile.close()

Источник

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.

This contains python scripts for converting wav files to pcm data for further processing.

haloboy777/wav-to-pcm

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

This contains python scripts for converting wav files to pcm data for further processing.

First record audio using ‘audio_record.py’ —> This will output a ‘output.wav’ file

Now if you run ‘check-output1.py’ it will print out..

  • Number of frames
  • Array containing all the frames
  • Rate of the Frame capture : 44100
  • Total Time recorded : 5

(Both can be changed in ‘audio_record.py’)

If you just want to use array of pcm data, Just include pcm_channels.py in your code and call «pcm_channels» by passing the name of the audio output file.

Function «pcm_channels» will return a tupple containing [pcm_data, sample_rate]

About

This contains python scripts for converting wav files to pcm data for further processing.

Источник

alkhimey / wav_to_pcm_array.py

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

«»» Assumes the input WAV file is mono (1 channel) with 16 bit samples «»»
import sys
if len ( sys . argv ) != 2 :
print ( «Wrong number of arguments.» )
exit ();
filename = sys . argv [ 1 ]
bytes = []
with open ( filename , «br» ) as f :
bytes = f . read ()
# Parse according to format
# Here: http://soundfile.sapp.org/doc/WaveFormat/
chunkID = bytes [ 0 : 4 ]. decode ()
chunkSize = int . from_bytes ( bytes [ 4 : 8 ], byteorder = ‘little’ )
innerFormat = bytes [ 8 : 12 ]. decode ()
subchunk1ID = bytes [ 12 : 16 ]. decode ()
subchunk1Size = int . from_bytes ( bytes [ 16 : 20 ], byteorder = ‘little’ )
audioFormat = int . from_bytes ( bytes [ 20 : 22 ], byteorder = ‘little’ )
numChannels = int . from_bytes ( bytes [ 22 : 24 ], byteorder = ‘little’ )
sampleRate = int . from_bytes ( bytes [ 24 : 28 ], byteorder = ‘little’ )
byteRate = int . from_bytes ( bytes [ 28 : 32 ], byteorder = ‘little’ )
blockAlign = int . from_bytes ( bytes [ 32 : 34 ], byteorder = ‘little’ )
bitsPerSample = int . from_bytes ( bytes [ 34 : 36 ], byteorder = ‘little’ )
subchunk2ID = bytes [ 36 : 40 ]. decode ()
subchunk2Size = int . from_bytes ( bytes [ 40 : 44 ], byteorder = ‘little’ )
data = []
lastSample = 40 + subchunk2Size
for byte_pair in zip ( bytes [ 40 : lastSample : 2 ], bytes [ 41 : lastSample : 2 ]):
data . append ( ( int . from_bytes ( byte_pair , byteorder = ‘little’ , signed = True )))
print ( ‘chunkID \t \t %s’ % chunkID )
print ( ‘chunkSize \t %d’ % chunkSize )
print ( ‘innerFormat \t %s’ % innerFormat )
print ( ‘subchunk1ID \t %s’ % subchunk1ID )
print ( ‘subchunk1Size \t %d’ % subchunk1Size )
print ( ‘audioFormat \t %d’ % audioFormat )
print ( ‘numChannels \t %d’ % numChannels )
print ( ‘sampleRate \t %d’ % sampleRate )
print ( ‘byteRate \t %d’ % byteRate )
print ( ‘blockAlign \t %d’ % blockAlign )
print ( ‘bitsPerSample \t %d’ % bitsPerSample )
print ( ‘subchunk2ID \t %s’ % subchunk2ID )
print ( ‘subchunk2Size \t %d’ % subchunk2Size )
print ( «Actual size of data (16 bit words): %d» % len ( data ))
assert ( chunkSize == 4 + ( 8 + subchunk1Size ) + ( 8 + subchunk2Size ))
assert ( byteRate == sampleRate * numChannels * ( bitsPerSample / 8 ))
assert ( blockAlign == numChannels * ( bitsPerSample / 8 ))
assert ( subchunk2Size == len ( data ) * numChannels * ( bitsPerSample / 8 ))
def chunks ( l , n ):
«»»Yield successive n-sized chunks from l.»»»
for i in range ( 0 , len ( l ), n ):
yield l [ i : i + n ]
with open ( ‘wav_data.h’ , ‘w’ ) as f :
f . write (
«»»
#ifndef WAV_DATA
#define WAV_DATA
#define NUM_SAMPLES %d
#define SAMPLE_RATE %d
int16_t data[NUM_SAMPLES] PROGMEM =
«»» % ( len ( data ), sampleRate ) )
for row in chunks ( data , 8 ):
f . write ( » » );
f . write ( «, » . join ( list (( str ( word ) for word in row ))))
f . write ( «,» )
f . write ( » \n » )
f . write ( «>; \n » )
f . write ( «#endif \n \n » )
try :
import matplotlib . pylab as plt
plt . plot ( data )
plt . show ()
except :
None

Источник

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.

python code for coverting mp3, wav, amr file to pcm file

Sohyun1798/pcm_audio_task

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

Actually, I’m not that kind of person who is good at explaning codes, programs, whatever(Screw me! 😂 ). But anyways I’ll do my best for describing what I made.

  • You need «pyaudio» to use this program. (maybe the command is «pip install pyaudio» but I can’t remember well so recommand you searching through google.)
  • And also need ‘wave’. Anyways you should install it to use ‘ac_utils.py’.
  • After you run this code(with command window or pycharm whatever) the program will record your voice or sound if it’s at certain frequency.
  • And the program will end if it senses a period of silence.
  • It will keep record sounds unless you press » control + c «

notice!) I revised certain codes on website to make this program so if there is any problem related to copyright or something, please let me know.

  • Install ‘wave’ before you use this. (command: pip install wave)
  • You need ‘ffmpeg’ also for using this. (Search google and install it appropriately according to your OS)
  • And this file is a set of functions so only existence of the file is enough.

parser.add_argument(«mode», choices = [‘amr2pcm’, ‘mp32pcm’, ‘wav2pcm’])

parser.add_argument(«-ap», «—amrpath», default = «»)

parser.add_argument(«-mp», «—mp3path», default = «»)

parser.add_argument(«-wp», «—wavpath», default = «»)

parser.add_argument(«-pp», «—pcmpath», default = «»)

  • You need directories before you run this code. And even though you don’t actually work with .wav file( for instance, amr file to pcm file or mp3 file to pcm file), you need wav file directory because of the converting process.
  • command: python audioconverter.py mode -ap amr_directory -mp mp3_directory -wp wav_directory -pp pcm_directory
  • command example(wav file to pcm file): python audioconverter.py wav2pcm -wp m2w/ -pp m2p/

About

python code for coverting mp3, wav, amr file to pcm file

Источник

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