Skip to content

Commit

Permalink
Fix overlap and unrecognized audio format error.
Browse files Browse the repository at this point in the history
  • Loading branch information
kinuax committed May 11, 2024
1 parent 38154e3 commit 1c12531
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 13 deletions.
22 changes: 16 additions & 6 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ mutagen = "1.47.0"
platformdirs = "4.2.0"
pydantic = "2.7.0"
pydantic-settings = "2.2.1"
pydub = "0.25.1"
pygame = "2.5.2"
pymongo = "4.6.2"
tinydb = "4.8.0"
Expand Down
4 changes: 2 additions & 2 deletions rolabesti/views/tracklist.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import typer

from .utils import play_audio
from .utils import play_mp3
from rolabesti.models import FIELD_FILTERS, Track
from rolabesti.logger import Logger
from rolabesti.utils import length_to_string
Expand Down Expand Up @@ -37,7 +37,7 @@ def play(self, cli: bool, overlap_length: int) -> None:
if cli:
for i, track in enumerate(self.tracks):
self.logger.log(f"[green]playing --> [/green]{track}")
play_audio(track.path)
play_mp3(track.path, i % 2)

# Adjust waiting_length. Filter out last track and too short tracks.
if i < self.count - 1 and overlap_length < track.length:
Expand Down
23 changes: 18 additions & 5 deletions rolabesti/views/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import tempfile
from contextlib import contextmanager, redirect_stdout
from pathlib import Path

from pydub import AudioSegment


try:
from wurlitzer import pipes
except ModuleNotFoundError:
Expand All @@ -15,10 +19,19 @@ def pipes():
import pygame


def play_audio(trackpath: Path) -> None:
"""Play the audio file located at trackpath."""
pygame.mixer.init()
pygame.mixer.init()
channels = [pygame.mixer.Channel(0), pygame.mixer.Channel(1)]


def play_mp3(trackpath: Path, channel: int) -> None:
"""Play the track located at trackpath on the given channel."""
# Avoid messages from C libraries.
with pipes():
pygame.mixer.music.load(trackpath)
pygame.mixer.music.play()
try:
sound = pygame.mixer.Sound(trackpath)
except pygame.error:
# Convert mp3 to wav if "Unrecognized audio format" error.
with tempfile.TemporaryFile() as wav_file:
AudioSegment.from_mp3(trackpath).export(wav_file, format="wav")
sound = pygame.mixer.Sound(wav_file)
channels[channel].play(sound)

0 comments on commit 1c12531

Please sign in to comment.