Skip to content

Instantly share code, notes, and snippets.

@lukesnow
Created August 9, 2015 19:19
Show Gist options
  • Save lukesnow/96cd72f6bb68a54173cf to your computer and use it in GitHub Desktop.
Save lukesnow/96cd72f6bb68a54173cf to your computer and use it in GitHub Desktop.
A simple AM radio.
#!/usr/local/bin/python
from rtlsdr import RtlSdr
import scipy.signal as spsi
from scipy.io.wavfile import write
import numpy as np
sdr = RtlSdr()
freq_offset = 124996881 # Hz Use this offset when ham-it-up is turned on.
station = 810396 # Hz
tune_to = freq_offset + station
seconds = 5 # Seconds
Fs = 960000 # Hz Default: 2.048e6 # 1323000 = 44100 * 30,
audio_rate = 48000 # Hz 44100 Can't use multiples of this! Exact sampling rate is needed for this library.
# configure device
sdr.sample_rate = Fs
sdr.center_freq = tune_to # Hz
sdr.gain = 32.8 # set to auto to enable AGC
# set to a number for manual gain setting.
signal = sdr.read_samples(seconds*Fs) # Note: sample size (seconds*Fs) mustn't be too large
print(signal[0:10])
print(len(signal))
# signal = signal[0::int(Fs/audio_rate)] # Try downsampling before filtering.
# Doesn't sound as good! But it saves about 1-second off of total run time of this script.
# http://stackoverflow.com/questions/17833119/lowpass-filter-in-python
N=111
Fc=2000.0/Fs # = 8000/960000 (8KHz width in relative frequency.)
Fl= 63.0/Fs # reject below this frequency
h=spsi.firwin( numtaps=N, cutoff=Fc, nyq=Fs/2) # Low pass filter, 2KHz
# h=spsi.firwin( numtaps=N, cutoff=[Fl, Fc], nyq=Fs/2) # Band pass filter, 2KHz # Doesn't work very well!
filtered=spsi.lfilter( h, 1.0, signal) # 'signal' is the time-series data you are filtering
filtered = filtered[0::int(Fs/audio_rate)] # down-sampling after filtering sounds much better.
filtered = abs(filtered)
# filtered = filtered.real # didn't work
print(len(filtered))
# http://stackoverflow.com/questions/10357992/how-to-generate-audio-from-a-numpy-array
scaled = np.int16(filtered/np.max(np.abs(filtered)) * 32767)
write('test.wav', audio_rate, scaled)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment