簡體   English   中英

如何在 python sounddevice 中使用 OutputStream 播放聲音文件?

[英]How to play a sound file using an OutputStream in python sounddevice?

目標是同時播放兩個聲音文件,因此sounddevice.play function 不是一個選項。 我相信我應該為每個文件制作一個OutputStream 現在我一直在試圖讓一個OutputStream工作。 請幫忙。

到目前為止我的代碼:

import soundfile as sf
import sounddevice as sd

data, fs = sf.read('sound_file.wav', dtype='float32')

def callback(outdata, frames, time, status):
    outdata[:] = data

with sd.OutputStream(callback=callback):
               pass

編輯:切換到RawOutputStream

import soundfile as sf
import sounddevice as sd

wf = sf.SoundFile('sound_file.wav')

def callback(outdata, frames, time, status):
    data = wf.buffer_read(frames, dtype='float32')
    if len(data) <= 0:
        raise sd.CallbackAbort
    if len(outdata) > len(data):
        raise sd.CallbackAbort #wrong obviously
    outdata[:] = data

with sd.RawOutputStream(channels=wf.channels,
                        callback=callback) as stream:
    while stream.active:
        continue

如果采樣率相似,您可以將兩個數據 arrays 加在一起:

import numpy as np
import soundfile as sf
import sounddevice as sd

data_1, fs_1 = sf.read('sound_file_1.wav', dtype='float32')
data_2, fs_2 = sf.read('sound_file_2.wav', dtype='float32')

if len(data_1) > len(data_2):
    data = data_1 + np.pad(data_2, (0, len(data_1) - len(data_2)))
else:
    data = np.pad(data_1, (0, len(data_2) - len(data_1))) + data_2

# determine fs from a combination of fs_1 and fs_2 of your choosing, like
fs = min(fs_1, fs_2)

sd.play(data, fs)
import soundfile as sf
import sounddevice as sd
import threading

def _play(sound):
    event =threading.Event()

    def callback(outdata, frames, time, status):
        data = wf.buffer_read(frames, dtype='float32')
        if len(outdata) > len(data):
            outdata[:len(data)] = data
            outdata[len(data):] = b'\x00' * (len(outdata) - len(data))
            raise sd.CallbackStop
        else:
            outdata[:] = data

    with sf.SoundFile(sound) as wf:
        stream = sd.RawOutputStream(samplerate=wf.samplerate,
                                    channels=wf.channels,
                                    callback=callback,
                                    blocksize=1024,
                                    finished_callback=event.set)
        with stream:
            event.wait()

def _playsound(sound):
    new_thread = threading.Thread(target=_play, args=(sound,))
    new_thread.start()

_playsound('sounds_file.wav')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM