To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.
root / audio_io.py @ 1:003b86796d1b
History | View | Annotate | Download (1.52 KB)
| 1 |
# imports audiolab
|
|---|---|
| 2 |
import scikits.audiolab as audiolab |
| 3 |
|
| 4 |
# create Sndfile instance with our example audio file
|
| 5 |
f = audiolab.Sndfile('viola.wav', 'r') |
| 6 |
|
| 7 |
#################
|
| 8 |
## Extracting metadata from audio file
|
| 9 |
#################
|
| 10 |
|
| 11 |
# sample rate
|
| 12 |
fs = f.samplerate |
| 13 |
print "Sample rate: ", fs |
| 14 |
|
| 15 |
# number of channels
|
| 16 |
nc = f.channels |
| 17 |
print "Number of channels: ", nc |
| 18 |
|
| 19 |
# encoding format
|
| 20 |
enc = f.encoding |
| 21 |
print "Encoding format: ", enc |
| 22 |
|
| 23 |
# number of frames - single samples for
|
| 24 |
# mono and pairs of samples for stereo
|
| 25 |
num_samples = f.nframes |
| 26 |
|
| 27 |
#################
|
| 28 |
## Reading Audio Samples from the file
|
| 29 |
#################
|
| 30 |
|
| 31 |
# We can read audio samples using the read_frame method
|
| 32 |
samples = f.read_frames(num_samples) |
| 33 |
|
| 34 |
# We can now close the file...
|
| 35 |
f.close() |
| 36 |
|
| 37 |
#################
|
| 38 |
## Playing the audio
|
| 39 |
#################
|
| 40 |
|
| 41 |
# play the audio file data in 'samples' at the sampling frequency 'fs'
|
| 42 |
audiolab.play(samples,fs) |
| 43 |
|
| 44 |
#################
|
| 45 |
## Choosing only the first half second of audio
|
| 46 |
#################
|
| 47 |
|
| 48 |
# the new number of samples is the
|
| 49 |
# (duration times sampling frequency)
|
| 50 |
new_nsamples = 0.5 * fs
|
| 51 |
|
| 52 |
# creating the new samples array
|
| 53 |
new_samples = samples[0:new_nsamples]
|
| 54 |
|
| 55 |
#################
|
| 56 |
## Writing the shorter audio to a new file
|
| 57 |
#################
|
| 58 |
|
| 59 |
# create a name for the new file
|
| 60 |
new_filename = 'output_file.wav'
|
| 61 |
|
| 62 |
# Create a Sndfile instance for writing a mono wav file @ 44100 Hz
|
| 63 |
format = audiolab.Format('wav')
|
| 64 |
f = audiolab.Sndfile(new_filename, 'w', format, 1, 44100) |
| 65 |
|
| 66 |
# Write out the shorter audio file
|
| 67 |
f.write_frames(new_samples) |
| 68 |
|
| 69 |
# close the audio file
|
| 70 |
f.close() |