Skip to content

Commit

Permalink
Merge pull request jiaaro#421 from sunjerry019/master
Browse files Browse the repository at this point in the history
Add try/finally to pyaudio to stop stream gracefully despite interrupts
  • Loading branch information
jiaaro committed Jan 30, 2020
2 parents 24fbb80 + ea51c73 commit 558d116
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
3 changes: 3 additions & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,6 @@ Antonio Larrosa

Aaron Craig
github: craigthelinguist

Yudong Sun
github: sunjerry019
27 changes: 15 additions & 12 deletions pydub/playback.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,22 +28,25 @@ def _play_with_pyaudio(seg):
rate=seg.frame_rate,
output=True)

# break audio into half-second chunks (to allows keyboard interrupts)
for chunk in make_chunks(seg, 500):
stream.write(chunk._data)

stream.stop_stream()
stream.close()
# Just in case there were any exceptions/interrupts, we release the resource
# So as not to raise OSError: Device Unavailable should play() be used again
try:
# break audio into half-second chunks (to allows keyboard interrupts)
for chunk in make_chunks(seg, 500):
stream.write(chunk._data)
finally:
stream.stop_stream()
stream.close()

p.terminate()
p.terminate()


def _play_with_simpleaudio(seg):
import simpleaudio
return simpleaudio.play_buffer(
seg.raw_data,
num_channels=seg.channels,
bytes_per_sample=seg.sample_width,
seg.raw_data,
num_channels=seg.channels,
bytes_per_sample=seg.sample_width,
sample_rate=seg.frame_rate
)

Expand All @@ -59,13 +62,13 @@ def play(audio_segment):
pass
else:
return

try:
_play_with_pyaudio(audio_segment)
return
except ImportError:
pass
else:
return

_play_with_ffplay(audio_segment)

0 comments on commit 558d116

Please sign in to comment.