Skip to content

Commit 91e0fbe

Browse files
author
Anton Schirg
committed
Method to read audio
1 parent b2904aa commit 91e0fbe

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,6 @@ nosetests.xml
3434
.mr.developer.cfg
3535
.project
3636
.pydevproject
37+
38+
#PyCharm
39+
.idea

read_audio.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
from scipy.io import wavfile
2+
import os
3+
import subprocess
4+
from tempfile import NamedTemporaryFile
5+
6+
7+
def from_file(path):
8+
'''
9+
Converts file to wav using ffmpeg and reads the wav. Returns sample rate, audio data
10+
'''
11+
12+
if not os.path.exists(path):
13+
raise ValueError('File not found')
14+
15+
if not os.path.isfile(path):
16+
raise ValueError('Path is no file')
17+
18+
if not os.access(path, os.R_OK):
19+
raise IOError('File is not readable')
20+
21+
output = NamedTemporaryFile(mode="rb", delete=False)
22+
ffmpeg_call = ['ffmpeg',
23+
'-y', # always overwrite existing files
24+
"-i", os.path.abspath(path), # input_file options (filename last)
25+
"-vn", # Drop any video streams if there are any
26+
"-ac", "1", # Convert audio to mono
27+
"-f", "wav", # output options (filename last)
28+
output.name
29+
]
30+
31+
subprocess.call(ffmpeg_call, stderr=open(os.devnull))
32+
33+
sr, data = wavfile.read(output.name)
34+
35+
output.close()
36+
os.remove(output.name)
37+
38+
return sr, data

0 commit comments

Comments
 (0)