本文整理汇总了Python中scikits.audiolab.Sndfile.write_frames方法的典型用法代码示例。如果您正苦于以下问题:Python Sndfile.write_frames方法的具体用法?Python Sndfile.write_frames怎么用?Python Sndfile.write_frames使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scikits.audiolab.Sndfile
的用法示例。
在下文中一共展示了Sndfile.write_frames方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _test_int_io
# 需要导入模块: from scikits.audiolab import Sndfile [as 别名]
# 或者: from scikits.audiolab.Sndfile import write_frames [as 别名]
def _test_int_io(self, dt):
# TODO: check if neg or pos value is the highest in abs
rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav')
try:
# Use almost full possible range possible for the given data-type
nb = 2 ** (8 * np.dtype(dt).itemsize - 3)
fs = 22050
nbuff = fs
a = np.random.random_integers(-nb, nb, nbuff)
a = a.astype(dt)
# Open the file for writing
format = Format('wav', _DTYPE_TO_ENC[dt])
b = Sndfile(fd, 'w', format, 1, fs)
b.write_frames(a)
b.close()
b = Sndfile(cfilename, 'r')
read_a = b.read_frames(nbuff, dtype=dt)
b.close()
assert_array_equal(a, read_a)
finally:
close_tmp_file(rfd, cfilename)
示例2: Format
# 需要导入模块: from scikits.audiolab import Sndfile [as 别名]
# 或者: from scikits.audiolab.Sndfile import write_frames [as 别名]
class AudioWriter:
syllableIndex = 0
baseFilename = "syllable"
fileOpen = False
format = Format('flac', 'pcm24')
f = None
filecount = 0
def open(self):
self.f = Sndfile(self.baseFilename + "." + str(self.syllableIndex) + '.flac', 'w', self.format, 1, 44100)
self.fileOpen = True
def close(self):
if self.fileOpen:
self.f.close()
self.syllableIndex += 1
self.fileOpen = False
def write(self, data):
if not self.fileOpen:
self.open()
self.f.write_frames(data)
def parseData(self, data):
buffer = []
for i in range(len(data) - 1):
if i == len(data) - 2 or (data[i] == zero_val and data[i + 1] == zero_val):
if len(buffer) > 0:
self.write(np.array(buffer))
self.filecount += 1
buffer = []
self.close()
else:
buffer.append(data[i])
示例3: test_bad_wavread
# 需要导入模块: from scikits.audiolab import Sndfile [as 别名]
# 或者: from scikits.audiolab.Sndfile import write_frames [as 别名]
def test_bad_wavread(self):
""" Check wavread on bad file"""
# Create a tmp audio file with non wav format, write some random data into it,
# and check it can not be opened by wavread
rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav')
try:
nbuff = 22050
noise = 0.1 * N.random.randn(nbuff)
# Open the copy file for writing
format = audio_format('aiff', 'pcm16')
b = Sndfile(cfilename, 'w', format, 1, nbuff)
b.write_frames(noise)
b.close()
b = Sndfile(cfilename, 'r')
rcnoise = b.read_frames(nbuff)
b.close()
try:
rnoise = wavread(cfilename)[0]
raise Exception("wavread on non wav file succeded, expected to fail")
except ValueError, e:
pass
#print str(e) + ", as expected"
finally:
close_tmp_file(rfd, cfilename)
示例4: _test_write
# 需要导入模块: from scikits.audiolab import Sndfile [as 别名]
# 或者: from scikits.audiolab.Sndfile import write_frames [as 别名]
def _test_write(self, func, format, filext):
""" Check *write functions from matpi """
rfd1, fd1, cfilename1 = open_tmp_file('matapi_test.' + filext)
rfd2, fd2, cfilename2 = open_tmp_file('matapi_test.' + filext)
try:
nbuff = 22050
fs = nbuff
noise = 0.1 * N.random.randn(nbuff)
# Open the first file for writing with Sndfile
b = Sndfile(cfilename1, 'w', format, 1, fs)
b.write_frames(noise)
b.close()
# Write same data with wavwrite
func(noise, cfilename2, fs)
# Compare if both files have both same audio data and same
# meta-data
f1 = Sndfile(cfilename1)
f2 = Sndfile(cfilename2)
assert_array_equal(f1.read_frames(f1.nframes), f2.read_frames(f2.nframes))
assert_equal(f1.format, f2.format)
assert_equal(f1.samplerate, f2.samplerate)
assert_equal(f1.channels, f2.channels)
f1.close()
f2.close()
finally:
close_tmp_file(rfd1, cfilename1)
close_tmp_file(rfd2, cfilename2)
示例5: timeStretchAudio
# 需要导入模块: from scikits.audiolab import Sndfile [as 别名]
# 或者: from scikits.audiolab.Sndfile import write_frames [as 别名]
def timeStretchAudio(inputAudio, outputAudio, outputDuration, writeOutput=1):
originalWav = Sndfile(inputAudio, 'r')
x = originalWav.read_frames(originalWav.nframes)
fs = originalWav.samplerate
nChannel = originalWav.channels
print fs
if nChannel >1:
x = x[0]
w = np.hamming(801)
N = 2048
t = -90
minSineDur = .005
maxnSines = 150
freqDevOffset = 20
freqDevSlope = 0.02
Ns = 512
H = Ns/4
tfreq, tmag, tphase = SM.sineModelAnal(x, fs, w, N, H, t, maxnSines, minSineDur, freqDevOffset, freqDevSlope)
inputDur = float(len(tfreq)*H/fs)
#timeScale = np.array([0.1,0.1, inputDur, inputDur*2])
timeScale = np.array([0,0, .4,outputDuration])
ytfreq, ytmag = trans.sineTimeScaling(tfreq, tmag, timeScale)
y = SM.sineModelSynth(ytfreq, ytmag, np.array([]), Ns, H, fs)
if writeOutput ==1:
outputWav = Sndfile(outputAudio, 'w', originalWav.format, originalWav.channels, originalWav.samplerate)
outputWav.write_frames(y)
outputWav.close()
else:
return y, fs, nChannel
示例6: WaveWriter
# 需要导入模块: from scikits.audiolab import Sndfile [as 别名]
# 或者: from scikits.audiolab.Sndfile import write_frames [as 别名]
class WaveWriter(object) :
def __init__(self,
filename,
samplerate = 44100,
channels = 1,
format = Format('wav','float32'),
) :
self._info = { 'filename' : filename ,
'samplerate' : samplerate,
'channels' : channels,
'format' : format,
'frames' : 0,
} # TODO: metadata not implemented
self._sndfile = Sndfile(filename, 'w', format, channels, samplerate)
if not self._sndfile :
raise NameError('Sndfile error loading file %s' % filename)
def __enter__(self) :
return self
def __exit__(self, type, value, traceback) :
self._sndfile.sync()
self._sndfile.close()
if value: raise # ????
def write(self, data) :
nframes, channels = data.shape
assert channels == self._info['channels']
self._sndfile.write_frames(data)
示例7: downsample
# 需要导入模块: from scikits.audiolab import Sndfile [as 别名]
# 或者: from scikits.audiolab.Sndfile import write_frames [as 别名]
def downsample(fs, sig):
in_file = random_string() + ".wav"
out_file = random_string() + ".wav"
frame_len = fs * WINDOW_SIZE
pad = len(sig)%frame_len
if pad > 0:
sig = np.append(sig, np.zeros(frame_len - pad))
f = Sndfile(in_file, 'w', Format(type="wav", encoding='pcm16', endianness="file"), 1, fs)
f.write_frames(sig)
f.close()
sox_in = pysox.CSoxStream(in_file)
sox_out = pysox.CSoxStream(out_file, 'w', pysox.CSignalInfo(SAMPLE_RATE, 1, 8), fileType='wav')
sox_chain = pysox.CEffectsChain(sox_in, sox_out)
sox_chain.add_effect(pysox.CEffect("rate", [str(SAMPLE_RATE)]))
sox_chain.flow_effects()
sox_out.close()
f = Sndfile(out_file, 'r')
sig = f.read_frames(f.nframes)
f.close()
os.unlink(in_file)
os.unlink(out_file)
return sig
示例8: test_basic_io
# 需要导入模块: from scikits.audiolab import Sndfile [as 别名]
# 或者: from scikits.audiolab.Sndfile import write_frames [as 别名]
def test_basic_io(self):
""" Check open, close and basic read/write"""
# dirty !
ofilename = join(TEST_DATA_DIR, 'test.wav')
rfd, fd, cfilename = open_tmp_file('pysndfiletest.wav')
try:
nbuff = 22050
# Open the test file for reading
a = Sndfile(ofilename, 'r')
nframes = a.nframes
# Open the copy file for writing
format = Format('wav', 'pcm16')
b = Sndfile(fd, 'w', format, a.channels, a.samplerate)
# Copy the data
for i in range(nframes / nbuff):
tmpa = a.read_frames(nbuff)
assert tmpa.dtype == np.float
b.write_frames(tmpa)
nrem = nframes % nbuff
tmpa = a.read_frames(nrem)
assert tmpa.dtype == np.float
b.write_frames(tmpa)
a.close()
b.close()
finally:
close_tmp_file(rfd, cfilename)
示例9: writeWAV
# 需要导入模块: from scikits.audiolab import Sndfile [as 别名]
# 或者: from scikits.audiolab.Sndfile import write_frames [as 别名]
def writeWAV(self, data, filename):
format = Format('wav')
if (len(data.shape) == 2):
f = Sndfile(filename, 'w', format, 2, self.samplingRate)
f.write_frames(data)
f.close()
else:
f = Sndfile(filename, 'w', format, 1, self.samplingRate)
f.write_frames(data)
f.close()
示例10: hodorifyIt
# 需要导入模块: from scikits.audiolab import Sndfile [as 别名]
# 或者: from scikits.audiolab.Sndfile import write_frames [as 别名]
def hodorifyIt(inputFile, outputFile, karaokeExt = '.txt'):
#reading input wave file
inputAudio = Sndfile(inputFile, 'r')
audio = inputAudio.read_frames(inputAudio.nframes)
nframes = inputAudio.nframes
fs = inputAudio.samplerate
nChannel = inputAudio.channels
fname, ext = os.path.splitext(inputFile)
karaokeFile = fname + karaokeExt
#parse the karaoke file
karaokeData = KP.parseKaraokeFile(karaokeFile)
#assign which syllable to use ho and which ones to use dor
toogle = 0
sylType = ['ho', 'dor']
for ii,elem in enumerate(karaokeData['data']):
if elem['syl'] == '-':
toogle =0
continue
karaokeData['data'][ii]['sylType'] = sylType[toogle]
toogle = (toogle +1)%2
dumpSonicVisualizerAnnotFile("tryHODOR.txt", karaokeData['data'])
#initialize all the hodor locations with not processed flag (later to be for exploiting repetitive hodors)
for ii,elem in enumerate(karaokeData['data']):
karaokeData['data'][ii]['processed']=0
#creating mapping between file names and tones
toneMapp = createToneMappFiles(toneMappFile)
#processHere the logic for Hodor input file for each word
karaokeData = hodorFileSelection(karaokeData, toneMapp)
#do center channel cut
audio = cutCenterChannel(audio, fs, karaokeData)
#estimate the possible repetitions in the karaoke data, i.e. output with same note and duration
print len(karaokeData['data'])
repMTX = estimateRepetitiveHodors(karaokeData)
emptyTrack = np.zeros(len(audio))
emptyTrack = generateHodorTrack(emptyTrack, fs, karaokeData, repMTX)
audio[:,1] = audio[:,1] + emptyTrack
audio[:,0] = audio[:,0] + emptyTrack
outputWav = Sndfile(outputFile, 'w', inputAudio.format, inputAudio.channels, inputAudio.samplerate)
outputWav.write_frames(audio)
outputWav.close()
示例11: save_wav
# 需要导入模块: from scikits.audiolab import Sndfile [as 别名]
# 或者: from scikits.audiolab.Sndfile import write_frames [as 别名]
def save_wav(sound, action_label, object_label):
wav_path = '/tmp/new_wav'
filename = os.path.join(wav_path, action_label + '-' + object_label + '-' + str(time.time()) + '.wav')
format = Format('wav')
print 'writing', filename, '...',
f = Sndfile(filename, 'w', format, 1, 44100)
f.write_frames(sound)
f.close()
print 'DONE'
示例12: extractOnsets
# 需要导入模块: from scikits.audiolab import Sndfile [as 别名]
# 或者: from scikits.audiolab.Sndfile import write_frames [as 别名]
def extractOnsets(audio):
od1 = OnsetDetection(method = 'hfc')
od2 = OnsetDetection(method = 'complex')
# let's also get the other algorithms we will need, and a pool to store the results
w = Windowing(type = 'hann')
fft = FFT() # this gives us a complex FFT
c2p = CartesianToPolar() # and this turns it into a pair (magnitude, phase)
pool = essentia.Pool()
# let's get down to business
for frame in FrameGenerator(audio, frameSize = 1024, hopSize = 512):
mag, phase, = c2p(fft(w(frame)))
pool.add('features.hfc', od1(mag, phase))
pool.add('features.complex', od2(mag, phase))
# Phase 2: compute the actual onsets locations
onsets = Onsets()
onsets_hfc = onsets(# this algo expects a matrix, not a vector
array([ pool['features.hfc'] ]),
# you need to specify weights, but as there is only a single
# function, it doesn't actually matter which weight you give it
[ 1 ])
# np.savetxt(outFile, onsets_hfc, fmt='%f')
#Let's just take the complex as an example
onsets_complex = onsets(array([ pool['features.complex'] ]), [ 1 ])
startTimes = onsets_hfc
endTimes = onsets_hfc[1:]
duration = Duration()
endTimes = np.append(endTimes, duration(audio))
slicer = Slicer(startTimes = array(startTimes), endTimes = array(endTimes))
frames = slicer(audio)
lengthInFrames = 0
for i in range(len(frames)):
lengthInFrames = lengthInFrames + len(frames[i])
format = Format('wav')
global counter
f = Sndfile('out'+ str(counter) + '.wav' , 'w', format, 1, 44100)
counter = counter + 1
f.write_frames(np.asarray(frames[0]))
return frames
示例13: specgram_to_file
# 需要导入模块: from scikits.audiolab import Sndfile [as 别名]
# 或者: from scikits.audiolab.Sndfile import write_frames [as 别名]
def specgram_to_file(path, mags, phasifiers, normalise=True, specgrammode=None):
if specgrammode==None:
mags = np.exp(mags)
if normalise:
mags -= np.min(mags)
cplx = mags * phasifiers
pcm = istft(cplx.T)
if normalise:
pcm /= np.max(pcm)
outsf = Sndfile(path, "w", Format('wav'), 1, fs)
outsf.write_frames(pcm)
outsf.close()
示例14: wav_to_flac
# 需要导入模块: from scikits.audiolab import Sndfile [as 别名]
# 或者: from scikits.audiolab.Sndfile import write_frames [as 别名]
def wav_to_flac(wav_name):
cd, tmp_name = mkstemp('tmp.flac')
Signal, fs = wavread(wav_name)[:2]
assert(fs == RATE)
fmt = Format('flac', 'pcm16')
nchannels = 1
flac_file = Sndfile(tmp_name, 'w', fmt, nchannels, RATE)
flac_file.write_frames(Signal)
return tmp_name
示例15: writeAudioOutput
# 需要导入模块: from scikits.audiolab import Sndfile [as 别名]
# 或者: from scikits.audiolab.Sndfile import write_frames [as 别名]
def writeAudioOutput(output, fs, f, f2, outputTitle):
"""Writes audio output"""
# Define an output audio format
formt = Format('wav', 'float64')
outFile = Sndfile(outputTitle, 'w', formt, 1, fs)
outFile.write_frames(output)
#Clean Up
f.close()
f2.close()
outFile.close()