如何在pyaudio

时间:2015-07-09 00:12:12

标签: portaudio pyaudio wasapi

我使用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独占模式?

1 个答案:

答案 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。

  1. 将portaudio目录放在pyaudio中,名称为portaudio-v19,名称很重要
  2. 安装MinGW / MSYS:我们需要的gcc,make和MSYS控制台
  3. 在MSYS console cd to portaudio-v19
  4. struct PaWasapiStreamInfo wasapiInfo; wasapiInfo.size = sizeof(PaWasapiStreamInfo); wasapiInfo.hostApiType = paWASAPI; wasapiInfo.version = 1; wasapiInfo.flags = (paWinWasapiExclusive|paWinWasapiThreadPriority); wasapiInfo.threadPriority = eThreadPriorityProAudio; outputParameters->hostApiSpecificStreamInfo = (&wasapiInfo);
  5. ./configure --with-winapi=wasapi --enable-shared=no
  6. make
  7. 更改以下行:

    cd ..

    external_libraries += ['winmm']

    在setup.py上的这些:

    extra_link_args += ['-lwinmm']

    external_libraries += ["winmm","ole32","uuid"]

  8. extra_link_args += ["-lwinmm","-lole32","-luuid"]
  9. python setup.py build --static-link -cmingw32
  10. 这就是全部。现在pyadio能够以WASAPI独占模式播放声音。