在Python中连续播放采样的音频数据

时间:2018-12-10 13:25:49

标签: python audio buffer audio-streaming

我正在尝试通过Python FM解调器从SDR中传递采样/捕获的IQ数据。

现在,我得到的结果是短音频样本的连续断续循环。我要像普通的FM收音机一样连续播放。

关于如何进行这项工作的任何建议?

#!/usr/bin/env python

import numpy as np
import scipy.signal as signal
from rtlsdr import RtlSdr
import sounddevice as sd

device_index = RtlSdr.get_device_index_by_serial('00000001')

class fmDemodulator(object):
    def __init__(self, sdr=None):
        self.sdr = sdr if sdr else RtlSdr(device_index)

    def demod(self, *args):
        Fs = self.sdr.sample_rate

        # Read IQ samples
        samples = self.sdr.read_samples(256*1024)
        print(samples)
        # Convert sampled data into numpy array
        x1 = np.array(samples).astype("complex64")

        # Downmixed Baseband Signal (Adjust offset to be centered)
        offsetFreq = 0    # already centered
        fc1 = np.exp(-1.0j*2.0*np.pi* offsetFreq/Fs*np.arange(len(x1)))  
        x2 = x1 * fc1  
        # Filter and downsample the FM Radio Signal
        bwFM = 200000   # approx. 170 kHz for a single channel
        decRate = int(Fs/bwFM)
        x3 = signal.decimate(x2, decRate)
        newFs = Fs/decRate
        ### Demodulate 200kHz FM Signal
        # Polar discriminator
        y4 = x3[1:] * np.conj(x3[:-1])  
        x4 = np.angle(y4)  
        # The de-emphasis filter
        # Given a signal 'x4' (in a numpy array) with sampling rate newFS
        d = newFs * 75e-6   # Calculate the # of samples to hit the -3dB point  
        x = np.exp(-1/d)   # Calculate the decay between each sample  
        b = [1-x]          # Create the filter coefficients  
        a = [1,-x]  
        x5 = signal.lfilter(b,a,x4)  

        # Find a decimation rate to achieve audio sampling rate between 44-48 kHz
        audioFreq = 44100.0  
        dec_audio = int(newFs/audioFreq)  
        audioFs = newFs/dec_audio
        print(audioFreq)
        x6 = signal.decimate(x5, dec_audio) 

        # Scale audio to adjust volume
        x6 *= 10000 / np.max(np.abs(x6))  

        return x6, audioFs

    def start(self):
        while True:
            x6, audioFs = self.demod()
            sd.play(x6, audioFs)

        return


def main():
    sdr = RtlSdr(device_index)
    fm = fmDemodulator(sdr)

    # SDR Configurations
    sdr.sample_rate = int(2.4e6)        # Hz
    sdr.center_freq = int(102e6)     # Hz
    sdr.freq_correction = 77            # PPM +- 20
    sdr.gain = 'auto'

    fm.start()

    # Clean up
    sdr.close()
    del(sdr)

if __name__ == '__main__':
    main()

谢谢!

0 个答案:

没有答案