Revision 0:b234c3417899

View differences:

1-wavread.py
1
from scikits.audiolab import wavread
2
from scikits.audiolab import play
3

  
4
# specify a file name
5
filename = "viola.wav"
6

  
7
# extract audio from file
8
samples, fs, enc = wavread(filename)     
9

  
10
# print out the first 50 samples
11
print samples[0:50]
12

  
13

  
14
#################################################
15
############# PLAYING AN AUDIO FILE #############
16
#################################################
17

  
18
# play the audio file data in 'data' at 44100Hz
19
play(samples,fs=44100)
20

  
21

  
22
#################################################
23
#################################################
24
#################################################
2-sndfile-read-and-play.py
1
from scikits.audiolab import Sndfile
2
from scikits.audiolab import Format
3
from scikits.audiolab import play
4

  
5
#################################################
6
######## CREATING A SOUND FILE INSTANCE #########
7
#################################################
8

  
9
# create Sndfile instance with our example audio file
10
f = Sndfile('viola.wav', 'r')
11

  
12

  
13
#################################################
14
######## EXTRACTING AUDIO FILE META-DATA ########
15
#################################################
16

  
17
# extract and print sample rate
18
fs = f.samplerate
19
print "sample rate: ",fs
20

  
21
# extract and print the number of channels
22
nc = f.channels
23
print "number of channels: ",nc
24

  
25
# extract and print the encoding format
26
enc = f.encoding
27
print "encoding format: ",enc
28

  
29
# extract the number of frames - single samples for
30
# mono and pairs of samples for stereo
31
num_samples = f.nframes
32

  
33

  
34
#################################################
35
######## READ AUDIO SAMPLES FROM THE FILE #######
36
#################################################
37

  
38
# we can read audio samples using the read_frame method
39
samples = f.read_frames(num_samples)
40

  
41

  
42
#################################################
43
############# PLAYING AN AUDIO FILE #############
44
#################################################
45

  
46
# play the audio file data in 'samples' at the sampling frequency 'fs' 
47
play(samples,fs)
48

  
49

  
50
#################################################
51
#################################################
52
#################################################
3-sndfile-write.py
1
from scikits.audiolab import Sndfile
2
from scikits.audiolab import Format
3
from scikits.audiolab import play
4

  
5
#################################################
6
######## CREATING A SOUND FILE INSTANCE #########
7
#################################################
8

  
9
# create Sndfile instance with our example audio file
10
f = Sndfile('viola.wav', 'r')
11

  
12

  
13
#################################################
14
######## EXTRACTING AUDIO FILE META-DATA ########
15
#################################################
16

  
17
# extract and print sample rate
18
fs = f.samplerate
19
print "sample rate: ",fs
20

  
21
# extract and print the number of channels
22
nc = f.channels
23
print "number of channels: ",nc
24

  
25
# extract and print the encoding format
26
enc = f.encoding
27
print "encoding format: ",enc
28

  
29
# extract the number of frames - single samples for
30
# mono and pairs of samples for stereo
31
num_samples = f.nframes
32

  
33

  
34
#################################################
35
######## READ AUDIO SAMPLES FROM THE FILE #######
36
#################################################
37

  
38
# we can read audio samples using the read_frame method
39
samples = f.read_frames(num_samples)
40

  
41

  
42
#################################################
43
########## WRITING TO A NEW AUDIO FILE ##########
44
#################################################
45

  
46
# create a name for the new file
47
new_filename = 'output_file.wav'
48

  
49
# create the output audio data, in this case a simple copy
50
output_samples = samples
51

  
52
# Create a Sndfile instance for writing wav files @ 44100 Hz
53
format = Format('wav')
54
f = Sndfile(new_filename, 'w', format, 1, 44100)
55

  
56
# Write out the first 3 seconds worth of samples (fs*3)
57
f.write_frames(output_samples)
58

  
59
# close the audio file
60
f.close()
61

  
62
#################################################
63
#################################################
64
#################################################
3a-sndfile-convert-wav-to-aiff-in-folder.py
1
import os
2
from scikits.audiolab import Sndfile
3
from scikits.audiolab import Format
4

  
5
# get the current working directory
6
path = os.getcwd()
7

  
8
# get all file names in the current directory
9
files = os.listdir(path)
10

  
11
# for each file name
12
for filename in files:
13
    
14
    # if the file ends with a .wav extension
15
    if filename.endswith('.wav'):
16
        
17
        # create a Sndfile instance for the file
18
        f_in = Sndfile(filename, 'r')
19
        
20
        # extract the number of frames
21
        numframes = f_in.nframes
22

  
23
        # read all audio samples into 'data'
24
        data = f_in.read_frames(numframes)
25

  
26
        # extract the name (without extension from the file name)
27
        name,extension = os.path.splitext(filename)
28

  
29
        # create a new filename with a .aiff extension
30
        new_filename = name + '.aiff'
31

  
32
        # create the new format based on aiff
33
        format = Format('aiff')
34
        
35
        # create a new Sndfile instance for the output file
36
        f_out = Sndfile(new_filename, 'w', format, f_in.channels, f_in.samplerate)
37

  
38
        # write out audio samples to the new file
39
        f_out.write_frames(data[:numframes])
40

  
41
        # close the audio file
42
        f_out.close()
43

  
44
        
4-lists-and-python-arrays-for-audio.py
1
import array as array
2

  
3

  
4
#################################################
5
############# PYTHON LISTS FOR AUDIO? ###########
6
#################################################
7

  
8
# I am a list of audio samples
9
myAudio = [-0.25,0.0,0.25,0.5]
10

  
11
# turn it up!
12
myAudio = myAudio*2
13

  
14
# oh dear!
15
print myAudio
16

  
17
# also, look what got into our array 
18
myAudio.append("hello!")
19

  
20
# oh dear again! - Python stores type information for every entry? Do we want
21
# to do that 44100 times a second?
22
print myAudio
23

  
24
"""
25
#################################################
26
############# PYTHON ARRAYS FOR AUDIO? ##########
27
#################################################
28

  
29
# I am an array of audio samples
30
myAudio = array.array('d',[-0.25,0.0,0.25,0.5])
31

  
32
# this doesn't work, that's good
33
# myAudio.append("hello")
34

  
35
# but what about this!
36
myAudio = myAudio*2
37

  
38
# oh dear oh dear oh dear
39
print myAudio
40
"""
5-basic-numpy.py
1
import numpy as np
2

  
3

  
4
#################################################
5
############# NUMPY ARRAYS FOR AUDIO? ###########
6
#################################################
7

  
8
# I am a numpy array containing some audio
9
myAudio = np.array([-0.25,0.0,0.25,0.5])
10

  
11
# turn it up!
12
myAudio = myAudio*2.
13

  
14
# great!
15
print myAudio
16

  
17

  
18
# what can we find out about our numpy audio?
19

  
20

  
21
print "Dimensions: ",myAudio.ndim
22

  
23
print "Size of each dimension: ",myAudio.shape
24

  
25
print "Total number of elements: ", myAudio.size # this is product of shape dimensions
26

  
27
print "Data type: ",myAudio.dtype # ...or dtype.name
28

  
29
print "Bytes per element: ",myAudio.itemsize 
30

  
31
print "Second element: ",myAudio[1]
32

  
33
print "All elements up to (but not including) 2: ",myAudio[:2]
34

  
35
print "All elements from index 2 to end: ",myAudio[2:]
36

  
37
print "Abs!: ",np.abs(myAudio)
38

  
39
print "Min: ",np.min(myAudio)
40

  
41
print "Max: ",np.max(myAudio)
42

  
43
print "Sum: ",np.sum(myAudio)
44

  
45
print "Sqrt: ",np.sqrt(9)
46

  
47
print "FFT!: ",np.fft.fft(myAudio)
48

  
49
print "Random!: ",np.random.random(4)
50

  
51
print "Ones: ",np.ones(4)
52

  
53
print "Zeros: ",np.zeros(4)
6-synthesize-mono-noise-with-numpy.py
1
import numpy as np
2
from scikits.audiolab import Sndfile
3
from scikits.audiolab import Format
4
import pylab as plt
5

  
6

  
7
#################################################
8
############ CREATE SOME RANDOM NOISE ###########
9
#################################################
10

  
11
# set our sampling frequency
12
fs = 44100
13

  
14
# create a numpy array that can hold 3 seconds of sound
15
noise = np.empty(3*fs)
16

  
17
# set each element to a random value (noise)
18
for i in range(noise.size):
19
    # generate random value and turn it down!
20
    noise[i] = np.random.random()*0.2
21

  
22
#################################################
23
########## WRITING NOISE TO AUDIO FILE ##########
24
#################################################
25

  
26
# create a name for the new file
27
new_filename = 'noise.wav'
28

  
29
# Create a Sndfile instance for writing wav files @ 44100 Hz
30
format = Format('wav')
31
f = Sndfile(new_filename, 'w', format, 1, fs)
32

  
33
# Write out the samples to the file
34
f.write_frames(noise)
35

  
36
# close the audio file
37
f.close()
38

  
39

  
40
#################################################
41
############### PLOTTING THE NOISE ##############
42
#################################################
43

  
44
plt.plot(noise[0:512])
45
plt.show()
7-synthesize-stereo-sines-with-numpy.py
1
import numpy as np
2
import pylab as plt
3
from scikits.audiolab import Sndfile
4
from scikits.audiolab import Format
5

  
6

  
7
#################################################
8
############## CREATE A SINE TONE ###############
9
#################################################
10

  
11
# set our sampling frequency
12
fs = 44100
13

  
14
# create a numpy array that can hold 3 seconds of sound
15
tone = np.zeros((3*fs,2))
16

  
17
# set frequency to 440Hz
18
freq = 440
19

  
20
# set volume to 0.3
21
amp = 0.3
22

  
23
# set values of each channel
24
for i in range(tone.shape[0]):
25
    
26
    # calculate phase value
27
    phaseVal = np.float(i)/np.float(fs)
28
    
29
    # generate tone and set volume for left and right
30
    tone[i][0] = np.sin(2*np.pi*freq*phaseVal)*amp
31
    tone[i][1] = np.sin(2*np.pi*(freq*2)*phaseVal)*amp
32

  
33

  
34
#################################################
35
########## WRITING TONES TO AUDIO FILE ##########
36
#################################################
37

  
38
# create a name for the new file
39
new_filename = 'tone.wav'
40

  
41
# Create a Sndfile instance for writing wav files @ 44100 Hz
42
format = Format('wav')
43
f = Sndfile(new_filename, 'w', format, 2, fs)
44

  
45
# Write out the samples to the file
46
f.write_frames(tone)
47

  
48
# close the audio file
49
f.close()
50

  
51

  
52
#################################################
53
############### PLOT USING PYLAB ################
54
#################################################   
55

  
56
toneL = tone[:,0]
57
toneR = tone[:,1]
58

  
59
plt.subplot(211)
60
plt.plot(toneL[0:200])
61
plt.subplot(212)
62
plt.plot(toneR[0:200])
63
plt.show()
8-dsp-delay.py
1
import numpy as np
2
from scikits.audiolab import wavread
3
from scikits.audiolab import Format
4
from scikits.audiolab import Sndfile
5

  
6
#################################################
7
######## CREATING A SOUND FILE INSTANCE #########
8
#################################################
9

  
10
# extract audio from file
11
samples, fs, enc = wavread('viola.wav')  
12

  
13
#################################################
14
########## APPLY A DELAY TO THE SAMPLES #########
15
#################################################
16

  
17
# delay in samples
18
delay = fs/2
19

  
20
# volume of delayed sound
21
alpha = 0.75
22

  
23
# create an empty array for the output
24
out = np.zeros(samples.size)
25

  
26
# for every sample in the array
27
for i in range(samples.size):
28

  
29
    # if we are safe to apply the delay without negative indexing
30
    if (i >= delay):
31
        out[i] = samples[i] + samples[i-delay]*alpha
32
    else:
33
        out[i] = samples[i] # hacky
34

  
35

  
36
#################################################
37
########## WRITING TO A NEW AUDIO FILE ##########
38
#################################################
39

  
40
# create a name for the new file
41
new_filename = 'delayed_audio.wav'
42

  
43
# Create a Sndfile instance for writing wav files @ 44100 Hz
44
format = Format('wav')
45
f = Sndfile(new_filename, 'w', format, 1, 44100)
46

  
47
# Write out the samples to an audio file
48
f.write_frames(out)
49

  
50
# close the audio file
51
f.close()
52

  
53
#################################################
54
#################################################
55
#################################################
9-dsp-block-by-block.py
1
import numpy as np
2
import pylab as plt
3
from scikits.audiolab import wavread
4

  
5
#################################################
6
############ EXTRACT AUDIO FROM FILE ############
7
#################################################
8

  
9
x, fs, enc = wavread("viola.wav")
10

  
11

  
12
#################################################
13
####### CALCULATE RMS OF EACH AUDIO BLOCK #######
14
#################################################
15

  
16
hop_size = 512                             # set hop size
17
frame_size = hop_size*2                     # set frame size
18
frame = np.zeros(frame_size)                # initialise frame with zeros
19
window = np.hanning(frame_size)             # create window of the same length as the hop size
20

  
21
# create empty numpy array to hold our 
22
rms = np.array([])
23

  
24
# run through signal frame by frame 
25
for n in range(0,x.size-hop_size,hop_size):
26
    
27
    # extract a segment of length hop_size
28
    frame = x[n:n+hop_size]                               
29
        
30
    # calculate RMS
31
    rms_val = np.sqrt(np.power(frame,2).mean())
32
    
33
    # add amplitude to our numpy array
34
    rms = np.append(rms,rms_val)
35

  
36
print rms
37

  
38
""" I AM THE OVERLAP VERSION
39
# run through signal frame by frame 
40
for n in range(0,x.size-hop_size,hop_size):
41
    
42
    # extract a segment of length hop_size
43
    buffer = x[n:n+hop_size]                               
44
    
45
    # add new segment to frame, shifting back samples of frame
46
    frame = np.append(frame[hop_size:frame_size],buffer)  
47
    
48
    # calculate RMS
49
    rms_val = np.sqrt(np.power(frame,2).mean())
50
    
51
    # add amplitude to our numpy array
52
    rms = np.append(rms,rms_val)
53

  
54
print rms
55
"""
56

  
57
plt.plot(rms)
58
plt.title("RMS")
59
plt.xlabel("time")
60
plt.ylabel("value")
61
plt.show()
62
                                   
63
 

Also available in: Unified diff