To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Revision:

root / audio_io.py

History | View | Annotate | Download (1.85 KB)

1 0:ea12496723d2 luis
import scikits.audiolab as audiolab
2 2:9885d7b7aca0 luis
import pylab as plt
3
import numpy as np
4 0:ea12496723d2 luis
5
# create Sndfile instance with our example audio file
6
f = audiolab.Sndfile('viola.wav', 'r')
7
8
#################
9
## Extracting metadata from audio file
10
#################
11
12
# sample rate
13
fs = f.samplerate
14
print "Sample rate: ", fs
15
16
# number of channels
17
nc = f.channels
18
print "Number of channels: ", nc
19
20
# encoding format
21
enc = f.encoding
22
print "Encoding format: ", enc
23
24
# number of frames - single samples for
25
# mono and pairs of samples for stereo
26
num_samples = f.nframes
27
28
#################
29
## Reading Audio Samples from the file
30
#################
31
32
# We can read audio samples using the read_frame method
33
samples = f.read_frames(num_samples)
34
35
# We can now close the file...
36
f.close()
37
38
#################
39
## Playing the audio
40
#################
41
42
# play the audio file data in 'samples' at the sampling frequency 'fs'
43
audiolab.play(samples,fs)
44 1:003b86796d1b luis
45
#################
46
## Choosing only the first half second of audio
47
#################
48
49
# the new number of samples is the
50
# (duration times sampling frequency)
51
new_nsamples = 0.5 * fs
52
53
# creating the new samples array
54
new_samples = samples[0:new_nsamples]
55
56
#################
57 2:9885d7b7aca0 luis
## Plotting the new signal using pylab/matplotlib
58
#################
59
60 3:162d64fb861c luis
# the x axis now shows the time in seconds instead of the sample number
61
## using the Numpy function linspace in order to create the time array
62
x_axis = np.linspace(0, 0.5, new_samples.size)
63
plt.plot(x_axis, new_samples)
64 2:9885d7b7aca0 luis
plt.show()
65
66
#################
67 1:003b86796d1b luis
## Writing the shorter audio to a new file
68
#################
69
70
# create a name for the new file
71
new_filename = 'output_file.wav'
72
73
# Create a Sndfile instance for writing a mono wav file @ 44100 Hz
74
format = audiolab.Format('wav')
75
f = audiolab.Sndfile(new_filename, 'w', format, 1, 44100)
76
77
# Write out the shorter audio file
78
f.write_frames(new_samples)
79
80
# close the audio file
81
f.close()
82 2:9885d7b7aca0 luis
83
84
85