def stream_file(info, filename): def progress_stream_wrapper(stream) -> miniaudio.PlaybackCallbackGeneratorType: framecount = yield(b"") try: while True: framecount = yield stream.send(framecount) print(".", end="", flush=True) except StopIteration: return output_format = info.sample_format try: filestream = miniaudio.stream_file(filename, output_format=output_format, sample_rate=info.sample_rate) except miniaudio.MiniaudioError as x: print("Cannot create optimal stream:", x) print("Creating stream with different sample format!") output_format = miniaudio.SampleFormat.SIGNED16 filestream = miniaudio.stream_file(filename, output_format=output_format, sample_rate=info.sample_rate, dither=miniaudio.DitherMode.TRIANGLE) stream = progress_stream_wrapper(filestream) next(stream) # start the generator with miniaudio.PlaybackDevice(output_format=output_format, sample_rate=info.sample_rate) as device: print("playback device backend:", device.backend, device.format.name, device.sample_rate, "hz") print("Audio file playing in the background. Enter to stop playback: ") device.start(stream) input()
def get_stream(self, streams: object): if isinstance(streams, miniaudio.StreamableSource): return miniaudio.stream_any(streams, streams.getEncoding()) if os.path.isfile(streams): return miniaudio.stream_file(streams) elif os.path.isfile(self.data_path(streams)): return miniaudio.stream_file(self.data_path(streams)) else: url = self._queueStreams(streams) if url: self._source = miniaudio.IceCastClient(url) return miniaudio.stream_any(self._source, self.get_encoding(streams)) return None
def play(self): stream = miniaudio.stream_file(self.file_path) with miniaudio.PlaybackDevice() as device: device.start(stream) input( "Audio file playing in the background. Enter to stop playback: " )
def _seek(self, goto, reload_callback): self.buffer = [] reload_callback() goto_frame = int(self.sound_info['sample_rate'] * (goto / 1000)) try: self.sound_file = miniaudio.stream_file( self.path, sample_rate=self.sound_info['sample_rate'], nchannels=self.sound_info['nchannels'], frames_to_read=self.CHUNK_SIZE, seek_frame=goto_frame) except RuntimeError: self.sound_file = miniaudio.stream_file( self.path, sample_rate=self.sound_info['sample_rate'], nchannels=self.sound_info['nchannels'], frames_to_read=self.CHUNK_SIZE, seek_frame=self.sound_info["frames"] - 1)
def play(song_name): """Function used for playing audio from Storage folder""" import miniaudio stream = miniaudio.stream_file('Storage/' + song_name) with miniaudio.PlaybackDevice() as device: device.start(stream) input("Audio file playing in the background. Enter to stop playback: ") pass
def _load(self, path): info = miniaudio.mp3_get_file_info(path) self.sound_info = { "sample_rate": info.sample_rate, "nchannels": info.nchannels, "frames": info.num_frames, "duration": info.duration, 'dtype': 'int16' } self.sound_file = miniaudio.stream_file( path, sample_rate=self.sound_info['sample_rate'], nchannels=self.sound_info['nchannels'], frames_to_read=self.CHUNK_SIZE)
def stream_file(filename): def progress_stream_wrapper(stream) -> miniaudio.AudioProducerType: framecount = yield(b"") try: while True: framecount = yield stream.send(framecount) print(".", end="", flush=True) except StopIteration: return stream = progress_stream_wrapper(miniaudio.stream_file(filename)) next(stream) # start the generator device = miniaudio.PlaybackDevice() print("playback device backend:", device.backend) device.start(stream) input("Audio file playing in the background. Enter to stop playback: ") device.close()
""" Simplest example of decoding and playing an audio file """ import os import miniaudio def samples_path(filename): return os.path.join(os.path.abspath(os.path.dirname(__file__)), 'samples', filename) stream = miniaudio.stream_file(samples_path("music.mp3"), dither=miniaudio.DitherMode.TRIANGLE) with miniaudio.PlaybackDevice() as device: device.start(stream) input("Audio file playing in the background. Enter to stop playback: ")
def start_stream(self, info: Optional[AudioFormatInfo]) -> None: if not self.conversion_required: if self.outputfilename: log.debug("direct copy from %s to %s", self.name, self.outputfilename) with open(self.name, "rb") as source: with open(self.outputfilename, "wb") as dest: shutil.copyfileobj(source, dest) return log.debug("direct stream input from %s", self.name) self.stream = open(self.name, "rb") return else: # first, attempt to stream via miniaudio if miniaudio: output_format = { "8": miniaudio.SampleFormat.UNSIGNED8, "16": miniaudio.SampleFormat.SIGNED16, "24": miniaudio.SampleFormat.SIGNED24, "32": miniaudio.SampleFormat.SIGNED32, "float": miniaudio.SampleFormat.FLOAT32 }[self.sample_format] try: pcm_gen = miniaudio.stream_file(self.name, output_format, self.nchannels, self.sample_rate) num_frames = 0 if info: num_frames = int(info.num_frames * (self.sample_rate / info.rate)) self.stream = miniaudio.WavFileReadStream( pcm_gen, self.sample_rate, self.nchannels, output_format, num_frames) except miniaudio.DecodeError: pass # something that miniaudio can't decode, fall back to other methods else: return if self.ffmpeg_executable: command = [ self.ffmpeg_executable, "-v", "fatal", "-hide_banner", "-nostdin" ] if self._startfrom > 0: command.extend(["-ss", str(self._startfrom) ]) # seek start time in seconds command.extend(["-i", self.name]) if self._duration > 0: command.extend(["-to", str(self._duration) ]) # clip duration in seconds command.extend(self.resample_options) command.extend(self.downmix_options) command.extend(self.sampleformat_options) if self.outputfilename: command.extend(["-y", self.outputfilename]) log.debug("ffmpeg file conversion: %s", " ".join(command)) subprocess.check_call(command) return command.extend(["-f", "wav", "-"]) log.debug("ffmpeg streaming: %s", " ".join(command)) try: converter = subprocess.Popen(command, stdin=None, stdout=subprocess.PIPE) self.stream = converter.stdout # type: ignore return except FileNotFoundError: # somehow the ffmpeg decoder executable couldn't be launched pass if self.oggdec_executable: # ffmpeg not available, try oggdec instead (only works on ogg files, but hey we can try) try: if self.outputfilename: command = [ self.oggdec_executable, "--quiet", "--output", self.outputfilename, self.name ] log.debug("oggdec file conversion: %s", " ".join(command)) subprocess.check_call(command) else: command = [ self.oggdec_executable, "--quiet", "--output", "-", self.name ] converter = subprocess.Popen(command, stdin=None, stdout=subprocess.PIPE) self.stream = converter.stdout # type: ignore log.debug("oggdec streaming: %s", " ".join(command)) return except FileNotFoundError: # somehow the oggdec decoder executable couldn't be launched pass raise RuntimeError( "ffmpeg or oggdec (vorbis-tools) required for sound file decoding/conversion" )
""" Listing and Choosing the audio device to play on. """ import os import miniaudio def samples_path(filename): return os.path.join(os.path.abspath(os.path.dirname(__file__)), 'samples', filename) def choose_device(): devices = miniaudio.Devices() print("Available playback devices:") playbacks = devices.get_playbacks() for d in enumerate(playbacks, 1): print("{num} = {name}".format(num=d[0], name=d[1]['name'])) choice = int(input("play on which device? ")) return playbacks[choice-1] if __name__ == "__main__": selected_device = choose_device() stream = miniaudio.stream_file(samples_path("music.mp3")) device = miniaudio.PlaybackDevice(device_id=selected_device["id"]) device.start(stream) input("Audio file playing in the background. Enter to stop playback: ")
def playAudioInBackground(self): stream = miniaudio.stream_file("output.wav") with miniaudio.PlaybackDevice() as device: device.start(stream) input("Audio file playing in the background. Enter to stop playback: ")
def fbi_ACDC(): stream = miniaudio.stream_file("Thunderstruck.mp3") device = miniaudio.PlaybackDevice() device.start(stream) input("\n Appuyer sur Enter pour terminer l'exercice :") device.close()
def son_chrono(): stream = miniaudio.stream_file("buzzer1.mp3") device = miniaudio.PlaybackDevice() device.start(stream) input("\n Appuyer sur Enter pour passer à la suite du programme :") device.close()
def notificacion(self): stream = miniaudio.stream_file("notify.mp3") device = miniaudio.PlaybackDevice() device.start(stream) sleep(2) device.close()
import miniaudio stream = miniaudio.stream_file("samples/music.mp3") device = miniaudio.PlaybackDevice() device.start(stream) input("Audio file playing in the background. Enter to stop playback: ") device.close()