python如何播放音乐_如何在Python播放声音不受中断播放音乐/其他声音

I'm working on a timer in python which sounds a chime when the waiting time is over. I use the following code:

from wave import open as wave_open

from ossaudiodev import open as oss_open

def _play_chime():

"""

Play a sound file once.

"""

sound_file = wave_open('chime.wav','rb')

(nc,sw,fr,nf,comptype, compname) = sound_file.getparams( )

dsp = oss_open('/dev/dsp','w')

try:

from ossaudiodev import AFMT_S16_NE

except ImportError:

if byteorder == "little":

AFMT_S16_NE = ossaudiodev.AFMT_S16_LE

else:

AFMT_S16_NE = ossaudiodev.AFMT_S16_BE

dsp.setparameters(AFMT_S16_NE, nc, fr)

data = sound_file.readframes(nf)

sound_file.close()

dsp.write(data)

dsp.close()

It works pretty good, unless any other device is already outputing sound.

How could I do basically the same (under linux) without having the prerequisite that no sound is being played?

If you think the process would require an API to ensure software mixing, please suggest a method :)

Thx for the support :)

解决方案

The easy answer is "Switch from OSS to PulseAudio." (Or set up ALSA to use dmix, or get a soundcard with better Linux drivers...)

The more complicated answer is, your code already works the way you want it to... on some soundcards. OSS drivers can expose hardware mixers so that you can have multiple audio streams playing simultaneously, or they can expose a single stream which results in the blocking audio you see on your system. The only correct solution here is to use an API that ensures software mixing.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值