Итак, это мое первое приложение Kivy. У меня возникла идея создать сценарий, который будет искать информацию о песне в Spotify, а затем загружать ее с YouTube в виде аудио,
до сих пор он отлично работал на моих Windows, поэтому я решил чтобы попытаться заставить его работать на моем Android.
Я запустил сборку buildozer, указал требования и разрешения, все работало гладко, но после установки apk он показал мне логотип, который я выбрал как presplash, а затем сразу автоматически произошел сбой, я попробовал еще раз, и он по-прежнему ведет себя так же.
Я подозреваю, что проблема, с которой я столкнулся, связана с использованием нескольких модулей и отсутствием ссылки на них в требованиях.
для экземпляр, у меня есть два класса каждый в отдельном модуле и main.py
#main.py
import os
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.uix.scrollview import ScrollView
from musicdownloader import MusicDownloader
from youtube import YoutubeDownloader
class DownloaderApp(App):
def build(self):
# Create a BoxLayout
self.layout = BoxLayout(orientation='vertical', padding=10, spacing=10)
# YouTube Downloader Section
self.layout.add_widget(Label(text="YouTube Video URL:"))
self.youtube_url_input = TextInput(hint_text="Enter YouTube URL")
self.layout.add_widget(self.youtube_url_input)
youtube_download_btn = Button(text="Download YouTube Video")
youtube_download_btn.bind(on_press=self.download_youtube_video)
self.layout.add_widget(youtube_download_btn)
# Spotify Downloader Section
self.layout.add_widget(Label(text="Spotify Track URL or ID:"))
self.spotify_input = TextInput(hint_text="Enter Spotify URL or ID")
self.layout.add_widget(self.spotify_input)
spotify_download_btn = Button(text="Download Spotify Song")
spotify_download_btn.bind(on_press=self.download_spotify_song)
self.layout.add_widget(spotify_download_btn)
return self.layout
def get_save_path(self):
"""
Determines the save path based on the platform.
On Android: Uses the app's storage directory.
On other platforms: Uses the "Downloads" directory.
"""
if os.name == "posix": # Likely Android
save_path = "/storage/emulated/0/Download" # Typical Android download path
else: # Likely Windows or Linux
save_path = os.path.join(os.getcwd(), "videos")
os.makedirs(save_path, exist_ok=True)
return save_path
def download_youtube_video(self, instance):
url = self.youtube_url_input.text
if not url:
self.show_popup("Error", "Please enter a YouTube URL.")
return
save_path = self.get_save_path()
try:
# Use YoutubeDownloader class to download video
YoutubeDownloader.download_video(url, save_path)
self.show_popup("Success", "YouTube video downloaded successfully!")
except Exception as e:
self.show_popup("Error", f"Failed to download YouTube video: {e}")
def download_spotify_song(self, instance):
spotify_input = self.spotify_input.text
if not spotify_input:
self.show_popup("Error", "Please enter a Spotify URL or ID.")
return
save_path = self.get_save_path()
try:
# Use MusicDownloader class to search and download song
music_downloader = MusicDownloader()
music_downloader.search_song_on_spotify_and_youtube(spotify_input)
self.show_popup("Success", "Spotify song downloaded successfully!")
except Exception as e:
self.show_popup("Error", f"Failed to download Spotify song: {e}")
def show_popup(self, title, message):
content = BoxLayout(orientation='vertical', padding=10)
content.add_widget(Label(text=message))
close_btn = Button(text="Close")
content.add_widget(close_btn)
popup = Popup(title=title, content=content, size_hint=(None, None), size=(300, 200))
close_btn.bind(on_press=popup.dismiss)
popup.open()
if __name__ == "__main__":
DownloaderApp().run()
#youtube.py
from yt_dlp import YoutubeDL
import os
class YoutubeDownloader():
@staticmethod
def download_video(url, save_path='videos'):
try:
# Ensure the 'videos' folder exists (default to 'videos' if no path is provided)
if not os.path.exists(save_path):
os.makedirs(save_path)
# Configure yt-dlp options
ydl_opts = {
'format' : 'best[ext=mp4]', # Best quality mp4 format
'outtmpl' : os.path.join(save_path, '%(title)s.%(ext)s'), # Save path with video title
}
with YoutubeDL(ydl_opts) as ydl:
ydl.download()
print("Video downloaded successfully" ... -is-loaded
Приложение Kivy автоматически вылетает на Android после загрузки предварительной заставки ⇐ Python
Программы на Python
1732554257
Anonymous
Итак, это мое первое приложение Kivy. У меня возникла идея создать сценарий, который будет искать информацию о песне в Spotify, а затем загружать ее с YouTube в виде аудио,
до сих пор он отлично работал на моих Windows, поэтому я решил чтобы попытаться заставить его работать на моем Android.
Я запустил сборку buildozer, указал требования и разрешения, все работало гладко, но после установки apk он показал мне логотип, который я выбрал как presplash, а затем сразу автоматически произошел сбой, я попробовал еще раз, и он по-прежнему ведет себя так же.
Я подозреваю, что проблема, с которой я столкнулся, связана с использованием нескольких модулей и отсутствием ссылки на них в требованиях.
для экземпляр, у меня есть два класса каждый в отдельном модуле и main.py
#main.py
import os
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.uix.scrollview import ScrollView
from musicdownloader import MusicDownloader
from youtube import YoutubeDownloader
class DownloaderApp(App):
def build(self):
# Create a BoxLayout
self.layout = BoxLayout(orientation='vertical', padding=10, spacing=10)
# YouTube Downloader Section
self.layout.add_widget(Label(text="YouTube Video URL:"))
self.youtube_url_input = TextInput(hint_text="Enter YouTube URL")
self.layout.add_widget(self.youtube_url_input)
youtube_download_btn = Button(text="Download YouTube Video")
youtube_download_btn.bind(on_press=self.download_youtube_video)
self.layout.add_widget(youtube_download_btn)
# Spotify Downloader Section
self.layout.add_widget(Label(text="Spotify Track URL or ID:"))
self.spotify_input = TextInput(hint_text="Enter Spotify URL or ID")
self.layout.add_widget(self.spotify_input)
spotify_download_btn = Button(text="Download Spotify Song")
spotify_download_btn.bind(on_press=self.download_spotify_song)
self.layout.add_widget(spotify_download_btn)
return self.layout
def get_save_path(self):
"""
Determines the save path based on the platform.
On Android: Uses the app's storage directory.
On other platforms: Uses the "Downloads" directory.
"""
if os.name == "posix": # Likely Android
save_path = "/storage/emulated/0/Download" # Typical Android download path
else: # Likely Windows or Linux
save_path = os.path.join(os.getcwd(), "videos")
os.makedirs(save_path, exist_ok=True)
return save_path
def download_youtube_video(self, instance):
url = self.youtube_url_input.text
if not url:
self.show_popup("Error", "Please enter a YouTube URL.")
return
save_path = self.get_save_path()
try:
# Use YoutubeDownloader class to download video
YoutubeDownloader.download_video(url, save_path)
self.show_popup("Success", "YouTube video downloaded successfully!")
except Exception as e:
self.show_popup("Error", f"Failed to download YouTube video: {e}")
def download_spotify_song(self, instance):
spotify_input = self.spotify_input.text
if not spotify_input:
self.show_popup("Error", "Please enter a Spotify URL or ID.")
return
save_path = self.get_save_path()
try:
# Use MusicDownloader class to search and download song
music_downloader = MusicDownloader()
music_downloader.search_song_on_spotify_and_youtube(spotify_input)
self.show_popup("Success", "Spotify song downloaded successfully!")
except Exception as e:
self.show_popup("Error", f"Failed to download Spotify song: {e}")
def show_popup(self, title, message):
content = BoxLayout(orientation='vertical', padding=10)
content.add_widget(Label(text=message))
close_btn = Button(text="Close")
content.add_widget(close_btn)
popup = Popup(title=title, content=content, size_hint=(None, None), size=(300, 200))
close_btn.bind(on_press=popup.dismiss)
popup.open()
if __name__ == "__main__":
DownloaderApp().run()
#youtube.py
from yt_dlp import YoutubeDL
import os
class YoutubeDownloader():
@staticmethod
def download_video(url, save_path='videos'):
try:
# Ensure the 'videos' folder exists (default to 'videos' if no path is provided)
if not os.path.exists(save_path):
os.makedirs(save_path)
# Configure yt-dlp options
ydl_opts = {
'format' : 'best[ext=mp4]', # Best quality mp4 format
'outtmpl' : os.path.join(save_path, '%(title)s.%(ext)s'), # Save path with video title
}
with YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
print("Video downloaded successfully")
except Exception as e:
print(f"An error occurred: {e}")
@staticmethod
def download_audio(url, save_path='music', preferred_codec="mp3", preferred_quality="320"):
try:
# Ensure the save_path exists (default to 'music' if no path is provided)
if not os.path.exists(save_path):
os.makedirs(save_path)
# Configure yt-dlp options for high-quality audio
ydl_opts = {
'format': 'bestaudio/best', # Get the best audio format available
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': preferred_codec, # Codec: mp3, wav, flac, etc.
'preferredquality': preferred_quality, # Quality: 128, 192, 320 kbps
}],
'outtmpl': os.path.join(save_path, '%(title)s.%(ext)s'), # Save with audio title
}
# Download the audio
with YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
print(f"Audio downloaded successfully in {preferred_codec} format at {preferred_quality} kbps.")
except Exception as e:
print(f"An error occurred: {e}")
@staticmethod
def download_playlist(url, save_path='videos'):
try:
# Ensure the save_path exists
if not os.path.exists(save_path):
os.makedirs(save_path)
# Configure yt-dlp options for downloading a playlist
ydl_opts = {
'format': 'best[ext=mp4]', # Best quality mp4 format
'outtmpl': os.path.join(save_path, '%(playlist)s', '%(title)s.%(ext)s'), # Save playlist in a folder
'noplaylist': False, # Allow downloading the entire playlist
'ignoreerrors': True, # Ignore errors and continue downloading
}
with YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
print("Playlist downloaded successfully")
except Exception as e:
print(f"An error occurred while downloading the playlist: {e}")
#musicdownloader.py
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
from yt_dlp import YoutubeDL
import os
import re
from dotenv import load_dotenv
import logging
# Load environment variables from .env
load_dotenv()
class MusicDownloader:
def __init__(self):
# Get Spotify credentials from environment variables
self.spotify_client_id = os.getenv("SPOTIFY_CLIENT_ID")
self.spotify_client_secret = os.getenv("SPOTIFY_CLIENT_SECRET")
self.spotify = self.authenticate_spotify()
def authenticate_spotify(self):
"""
Authenticates with Spotify API using Client Credentials Flow.
"""
client_credentials_manager = SpotifyClientCredentials(
client_id=self.spotify_client_id,
client_secret=self.spotify_client_secret
)
return spotipy.Spotify(client_credentials_manager=client_credentials_manager)
def extract_track_id(self, spotify_input):
"""
Extracts the track ID from a Spotify URL or validates if it's already an ID.
"""
if "open.spotify.com" in spotify_input:
match = re.search(r"track/([a-zA-Z0-9]+)", spotify_input)
if match:
return match.group(1)
else:
raise ValueError("Invalid Spotify URL.")
return spotify_input # Assume input is a valid track ID if it's not a URL
def get_song_details(self, track_input):
"""
Retrieves song details from Spotify using the song's Spotify track ID or URL.
"""
try:
track_id = self.extract_track_id(track_input)
track = self.spotify.track(track_id)
song_details = {
'name': track['name'],
'artist': track['artists'][0]['name'],
'album': track['album']['name'],
}
return song_details
except Exception as e:
print(f"An error occurred while retrieving song details: {e}")
return None
def search_youtube(self, song_details):
"""
Searches YouTube for the song based on the song details (name + artist).
Downloads the audio as MP3 into a 'music' folder.
"""
try:
# Search query
search_query = f"{song_details['name']} {song_details['artist']} "
print(f"Searching for: {search_query}")
# Set up the music folder path
music_folder = os.path.join(os.getcwd(), 'music')
# Ensure the 'music' folder exists
if not os.path.exists(music_folder):
os.makedirs(music_folder)
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()
# yt-dlp options
ydl_opts = {
'quiet': False, # Enable verbose logging to track what's happening
'format': 'bestaudio/best', # Download the best available audio
'noplaylist': True, # Avoid playlist results
'extractaudio': True, # Extract audio only (not video)
'audioquality': 1, # Highest audio quality
'outtmpl': os.path.join(music_folder, '%(title)s.%(ext)s'), # Save to 'music' folder
'postprocessors': [{
'key': 'FFmpegExtractAudio', # Use FFmpeg to extract and convert audio
'preferredcodec': 'mp3', # Convert to MP3
'preferredquality': '192', # Set bitrate to 192kbps
}],
'logger': logger # Add logger to yt-dlp options
}
# Perform download
with YoutubeDL(ydl_opts) as ydl:
ydl.download([f"ytsearch:{search_query}"])
print(f"Search complete. Audio downloaded and converted to MP3 successfully.")
except Exception as e:
print(f"An error occurred while searching on YouTube: {e}")
def search_song_on_spotify_and_youtube(self, track_input):
"""
Searches for a song on Spotify (via URL or ID) and then finds it on YouTube.
"""
song_details = self.get_song_details(track_input)
if song_details:
print(f"Song details retrieved: {song_details}")
self.search_youtube(song_details)
else:
print("Failed to retrieve song details.")
Подробнее здесь: [url]https://stackoverflow.com/questions/79223988/kivy-app-automaticly-crashing-on-android-after-presplash-is-loaded[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия