2017-03-20 5 views
0

특정 곡이라고 불릴 때 재생해야하는 기능을 만들어야합니다. 나는 그것이 잘 작동 함수 내 beatstream 정의를 넣으면소스를 다시 가져올 필요없이 pyAudio에서 오디오 파일을 재생하는 기능은 무엇입니까?

import pyaudio 
import wave 

chunk = 1024 
p = pyaudio.PyAudio() 

beat = wave.open(r"D:/Escritorio/beat.wav","rb") 
stream = p.open(format = p.get_format_from_width(beat.getsampwidth()), 
       channels = beat.getnchannels(), 
       rate = beat.getframerate(), 
       output = True) 

def play_song(b, s, c): 
    data = b.readframes(c) 
    while data != '': 
     s.write(data) 
     data = b.readframes(c) 
    b.rewind() 
    s.stop_stream() 

for _ in range(10): 
    #Should play the audio file 10 times, but nothing happens 
    play_song(beat, stream, chunk) 

하지만, 각각의 반복 사이의 시간은 가능한 한 낮게해야하며, 그렇게 만들기의 지연을한다 : 여기

코드입니다 약 0.1 초입니다. 실제로는이 목적을 위해 매우 나쁩니다.

답변

0

대답은 비동기 적으로 오디오를 재생하는 콜백 콜백을 사용하는 것입니다.

def callback(in_data, frame_count, time_info, status): 
    data = beat.readframes(frame_count) 
    return (data, pyaudio.paContinue) 

#open stream 
stream = p.open(format = p.get_format_from_width(beat.getsampwidth()), 
       channels = beat.getnchannels(), 
       rate = beat.getframerate(), 
       output = True, 
       stream_callback=callback) 

def play_song(): 
    stream.start_stream() 
    while stream.is_active(): 
     True 
    stream.stop_stream() 
    beat.rewind()