Add callback for processing FM files

This commit is contained in:
Brandon Skari
2016-01-17 15:07:35 +07:00
parent 2df0f54626
commit 96db9cb3dc
5 changed files with 107 additions and 65 deletions

View File

@@ -2,55 +2,43 @@
from pydub import AudioSegment
import StringIO
import array
import _rpitx
import wave
import array
import logging
import os
def play_fm(file_, frequency):
def broadcast_fm(file_, frequency):
"""Play a music file over FM."""
logging.basicConfig()
logger = logging.getLogger('rpitx')
def _reencode(file_name):
"""Returns a file-like object reencoded to the proper WAV format."""
reencoded = StringIO.StringIO()
# AudioSegment doesn't support context managers either
"""Returns an AudioSegment file reencoded to the proper WAV format."""
original = AudioSegment.from_file(file_name)
if original.channels > 2:
raise ValueError('Too many channels in sound file')
if original.channels == 2:
# TODO: Support stereo. For now, just overlay into mono.
logger.info('Reducing stereo channels to mono')
left, right = original.split_to_mono()
original = left.overlay(right)
original.export(reencoded, format='wav', bitrate='44k')
return reencoded
if (
original.frame_rate != 48000
# TODO: There should be a better way to check if it's wav
or not file_name.endswith('.wav')
):
logger.debug('Reencoding file')
reencoded = StringIO.StringIO()
original.export(reencoded, format='wav', bitrate='44k')
return reencoded
encoded_file = None
if isinstance(file_, str):
if file_.endswith('.wav'):
with open(file_) as raw_file:
# wave.open doesn't support context managers, so we need to be
# careful about closing the file
wav_file = wave.open(raw_file, 'r')
num_channels = wav_file.getnchannels()
framerate = wav_file.getframerate()
sample_width = wav_file.getsampwidth()
wav_file.close()
if (
num_channels != 1
or framerate != 1
or sample_width != 2
):
encoded_file = _reencode(file_)
else:
encoded_file = AudioSegment.from_file(file_)
else:
encoded_file = _reencode(file_)
else:
encoded_file = _reencode(file_)
return original
encoded_file = _reencode(file_)
raw_array = array.array('c')
raw_array.fromstring(str(encoded_file))
raw_array.fromstring(encoded_file.raw_data)
array_address, length = raw_array.buffer_info()
_rpitx.broadcast(array_address, length, frequency)
_rpitx.broadcast_fm(array_address, length, frequency)