简体   繁体   English

Python 从缓冲区播放声音

[英]Python play sound from a buffer

I am trying to make simple music streaming app using socket such that the client requests for a song and the server reads the song from the file and sends it part by part to the client to play.我正在尝试使用socket制作简单的音乐流媒体应用程序,以便客户端请求歌曲,服务器从文件中读取歌曲并将其部分发送给客户端播放。 I want a way to put the parts into a buffer so that I can play it in continuation.我想要一种将零件放入缓冲区的方法,以便我可以继续播放它。 I am using sounddevice library to play the sound.我正在使用sounddevice库来播放声音。 The problem is if I play the parts one after other, they sound broken.问题是如果我一个接一个地演奏这些部分,它们听起来就坏了。 This is my code:这是我的代码:

import socket
import soundfile as sf
import sounddevice as sd

data, samplerate = sf.read('audio.wav')

sd.play(data[:100000], samplerate)
sd.wait()
sd.play(data[100000:200000], samplerate)
sd.wait()

What is the proper way to do this?这样做的正确方法是什么?

Make it multi threaded.使其成为多线程。

Thread 1 will read data from the file/socket and put them in the Buffer.线程 1 将从文件/套接字中读取数据并将它们放入缓冲区中。

Thread 2 read the data from the buffer and play it to the sound device.线程 2 从缓冲区读取数据并将其播放到声音设备。

Have a ping pong buffer mechanism, so that both the threads are not blocked.有一个乒乓缓冲机制,这样两个线程都不会被阻塞。

example:例子:

https://embedded.fm/blog/2017/3/21/ping-pong-buffers https://embedded.fm/blog/2017/3/21/ping-pong-buffers

https://overlay.technology/ping-pong-buffer-to-embedded-systems/ https://overlay.technology/ping-pong-buffer-to-embedded-systems/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM