我使用python的these预编译二进制文件和WASAPI支持。我想通过WASAPI播放一个wav文件。我找到了这个api的默认输出设备的索引:
import pyaudio
p = pyaudio.PyAudio()
print p.get_host_api_info_by_index(3)
>>{'index': 3, 'name': u'Windows WASAPI', 'defaultOutputDevice': 11L, 'type': 13L, 'deviceCount': 3L, 'defaultInputDevice': 12L, 'structVersion': 1L}
然后我通过这个设备播放一个wav文件:
import pyaudio
import wave
CHUNK = 1024
wf = wave.open('test.wav', 'rb')
# instantiate PyAudio (1)
p = pyaudio.PyAudio()
# open stream (2)
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output_device_index=11,
output=True)
# read data
data = wf.readframes(CHUNK)
# play stream (3)
while data != '':
stream.write(data)
data = wf.readframes(CHUNK)
# stop stream (4)
stream.stop_stream()
stream.close()
# close PyAudio (5)
p.terminate()
当正在播放文件时,我仍然能够听到系统中的其他声音,但在独家WASAPI模式下,必须阻止所有其他声音。那么如何在pyaudio中启用WASAPI独占模式?
答案 0 :(得分:1)
需要更改pyaudio的来源。我们需要修改_portaudiomodule.c。
包括pa_win_wasapi.h:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="radio">
<input name="somename" type="radio">
<label id='somelabel' for="somename">description</label>
</div>
<div class="well">
<div class="line">Something</div>
<div class="line">Something else</div>
</div>
</div>
更改此行:
#include pa_win_wasapi.h
关于这个:
outputParameters->hostApiSpecificStreamInfo = NULL;
现在我们需要编译pyaudio。
struct PaWasapiStreamInfo wasapiInfo;
wasapiInfo.size = sizeof(PaWasapiStreamInfo);
wasapiInfo.hostApiType = paWASAPI;
wasapiInfo.version = 1;
wasapiInfo.flags = (paWinWasapiExclusive|paWinWasapiThreadPriority);
wasapiInfo.threadPriority = eThreadPriorityProAudio;
outputParameters->hostApiSpecificStreamInfo = (&wasapiInfo);
./configure --with-winapi=wasapi --enable-shared=no
make
更改以下行:
cd ..
external_libraries += ['winmm']
在setup.py上的这些:
extra_link_args += ['-lwinmm']
external_libraries += ["winmm","ole32","uuid"]
extra_link_args += ["-lwinmm","-lole32","-luuid"]
python setup.py build --static-link -cmingw32
这就是全部。现在pyadio能够以WASAPI独占模式播放声音。