Reputation: 1
I need to extract exaclly 8 seconds from the middle of the audio data from the wav. file with lenght 0:27 sec.
--All what I did already, it took the middle 9 sec by divided wav. file on 3 parts and took the middle one, but it's 9s I need 8s.
And how find a number of bits in that numpy array?
import scipy.io.wavfile
import pyaudio
import numpy as np
(samplRate,data)=scipy.io.wavfile.read('Track48.wav')
print
CHANNELS=2
p= pyaudio.PyAudio()
#
nine_sec=len(data)/3
eight_sec=2*len(data)/3
stream = p.open(format=pyaudio.paInt16,
channels=CHANNELS,
rate=44100,
output=True
)
cuted_data=data[nine_sec:eight_sec]
newdata = cuted_data.astype(np.int16).tostring()
stream.write(newdata)
print(cuted_data)
Thank you for your help.
Upvotes: 0
Views: 2263
Reputation: 331
I know this question is old but someone may like the solution i want to offer which uses numpy only. No need of pydub
.
import scipy.io.wavfile as wavfile
fs, data - wavefile.read("Track48.wav")
# number of samples N
N = data.shape[0]
# Convert seconds to samples
eight_secs_in_samples = float(fs)*8 # time = number_of_samples / rate
midpoint_sample = N//2 # Midpoint of sample
# substract 4 seconds from midpoint
left_side = midpoint_sample-(eight_secs_in_samples//2)
# Add 4 seconds from midpoint up
right_side = midpoint_sample + (eight_secs_in_samples//2)
# The midpoint of samples is therefore:
mid8secs = array_data[int(left_side):int(right_side)] # this range contains the required samples
# Save the file
wavfile.write("eightSecSlice.wav",fs,mid8secs)
Upvotes: 0
Reputation: 11473
You can use pydub
to slice middle 8 seconds very easily.
Details on pydub are here
And you can install as pip install pydub
I had a wav file of 348 sec duration whose middle 8 seconds are sliced.
>>> song.duration_seconds
348.05551020408166
You can also use different file formats such as wav
, mp3
, m4a
, ogg
etc. for import (convert to data-segments) and export.
Source Code
from pydub import AudioSegment
from pydub.playback import play
song = AudioSegment.from_wav("music.wav")
#slice middle eight seconds of audio
midpoint = song.duration_seconds // 2
left_four_seconds = (midpoint - 4) * 1000 #pydub workds in milliseconds
right_four_seconds = (midpoint + 4) * 1000 #pydub workds in milliseconds
eight_sec_slice = song[left_four_seconds:right_four_seconds ]
#Play slice
play(eight_sec_slice )
#or save to file
eight_sec_slice.export("eight_sec_slice.wav", format="wav")
As you can see length of middle 8 seconds slice is exactly as desired.
>>> eight_sec_slice.duration_seconds
8.0
Upvotes: 2