Explore all Music Player open source software, libraries, packages, source code, cloud functions and APIs.

Popular New Releases in Music Player

BackgroundMusic

0.4.0-SNAPSHOT-b38f6dd

nuclear

bc8b7b

mopidy

v3.2.0

Clementine

1.4.0rc1-811-g20c6ae6c1

FeelUOwn

资源文件下载

Popular Libraries in Music Player

UnblockNeteaseMusic

by nondanee doticonjavascriptdoticon

star image 14911 doticonMIT

Revive unavailable songs for Netease Cloud Music

BackgroundMusic

by kyleneideck doticonc++doticon

star image 11173 doticonNOASSERTION

Background Music, a macOS audio utility: automatically pause your music, set individual apps' volumes and record system audio.

nuclear

by nukeop doticontypescriptdoticon

star image 8707 doticonAGPL-3.0

Streaming music player that finds free music for you

ieaseMusic

by trazyn doticonjavascriptdoticon

star image 8524 doticonMIT

网易云音乐第三方

Google-Play-Music-Desktop-Player-UNOFFICIAL-

by MarshallOfSound doticonjavascriptdoticon

star image 8451 doticonMIT

A beautiful cross platform Desktop Player for Google Play Music

mopidy

by mopidy doticonpythondoticon

star image 7322 doticonApache-2.0

Mopidy is an extensible music server written in Python

Clementine

by clementine-player doticonc++doticon

star image 3140 doticonGPL-3.0

:tangerine: Clementine Music Player

FeelUOwn

by feeluown doticonpythondoticon

star image 3091 doticonGPL-3.0

trying to be a robust, user-friendly and hackable music player

JamsMusicPlayer

by psaravan doticonjavadoticon

star image 3027 doticon

A free, powerful and elegant music player for Android.

Trending New libraries in Music Player

spot

by xou816 doticonrustdoticon

star image 1399 doticonMIT

Native Spotify client for the GNOME desktop

HyPlayer

by HyPlayer doticoncsharpdoticon

star image 634 doticonGPL-3.0

第三方网易云音乐播放器 | A Netease Cloud Music Player

DsoMusic

by Moriafly doticonkotlindoticon

star image 594 doticonGPL-3.0

Kotlin 开发的美观安卓音乐软件,音源:网易云音乐、QQ 音乐

Rise-Media-Player

by Rise-Software doticoncsharpdoticon

star image 384 doticonGPL-3.0

One media player for everything you own or stream; whether it's music or videos, online or offline Rise Media Player does it all. And it's beautiful and native with the latest version of WinUI.

Synfonia

by jmacato doticoncsharpdoticon

star image 154 doticon

Cross-platform C# Audio Player made with AvaloniaUI

HyPlayer

by kengwang doticoncsharpdoticon

star image 132 doticonGPL-3.0

第三方网易云音乐播放器 | A Netease Cloud Music Player

onetagger

by Marekkon5 doticonrustdoticon

star image 129 doticonGPL-3.0

Rust app to tag your music library.

ymuse

by yktoo doticongodoticon

star image 125 doticonApache-2.0

GTK client for Music Player Daemon (MPD) written in Go

Gemini

by Gabe-H doticonjavascriptdoticon

star image 123 doticonMIT

A dope, easy-on-the-eyes, currently-playing viewer for Spotify

Top Authors in Music Player

1

mopidy

6 Libraries

star icon8581

2

iamraufu

3 Libraries

star icon9

3

hbenl

3 Libraries

star icon26

4

sunny

2 Libraries

star icon144

5

arma7x

2 Libraries

star icon19

6

carlosrafaelgn

2 Libraries

star icon148

7

artemshuba

2 Libraries

star icon216

8

C-Aniruddh

2 Libraries

star icon333

9

iammert

2 Libraries

star icon1448

10

Debug-Studios

2 Libraries

star icon7

1

6 Libraries

star icon8581

2

3 Libraries

star icon9

3

3 Libraries

star icon26

4

2 Libraries

star icon144

5

2 Libraries

star icon19

6

2 Libraries

star icon148

7

2 Libraries

star icon216

8

2 Libraries

star icon333

9

2 Libraries

star icon1448

10

2 Libraries

star icon7

Trending Kits in Music Player

Nowadays, using Ruby Music Player libraries like Black_Candy, Slack_DJ, Ruby_mpd and mpd_client is a common practice among music lovers. These libraries allow us to play music from our favorite artists or songs from our favorite albums in our application. The Ruby Music Player library provides a complete Ruby interface to the MPD music player. It allows you to play audio files and manage your music collection with a familiar interface. Black_Candy - Black_Candy is the most popular music player library in Ruby. It has support for streaming audio from HTTP sources and radio stations. It also has an extendable plugin system that allows users to create their own plugins as well as customize existing ones by adding new high-level methods and classes, or extending existing ones with new low-level data types and functions. Black_Candy is a light-weight MPD client for the Ruby programming language. It's built on top of libmpdclient and uses Sinatra for routing and integration with Rails views. Slack_DJ - Slack DJ is a Ruby gem for playing music streams from Slack channels in your own application. The library was written by @slackbot, so it's 100% free and open source software. Ruby MPD client is a pure Ruby implementation of the MPD protocol, built on top of libmpd. mpd_client is an embedded MPD client for use in embedded projects. The following is a comprehensive list of the best open source Ruby Music Player libraries

The use of JavaScript Music Player libraries like APlayer, Groovebasin, Volumio2, Stretto and others has become more popular due to the popularity of the browser-based music player. It's easy to use and can be customized easily with various plugins. The JavaScript based players are great because they allow you to play music while working on other tasks such as browsing the web, or editing documents. The main advantage of using JavaScript MP library is that it allows you to create custom players for your websites and apps based on your needs. The APlayer is a music player for Android. It plays your music stored on your Android phone or tablet, as well as online playlists from the web. The Groovebasin is an open source music player for Android. It allows you to play music stored on your Android device and online radio stations, as well as stream music over the Internet. The Volumio2 is an open source Linux-based OS for streaming audio from one or more USB turntables directly to your HiFi system, using either USB or Ethernet connections. The Stretto JavaScript Music Player library lets you control Stretto players via JavaScript API, which allows for easy integration with web applications and websites. The following is a list of the most popular open source JavaScript Music Player libraries

The best way to start playing music on your PC is to use a C# music player library. The most popular and powerful ones are Dopamine-windows, BreadPlayer, gMusic and Meridian. These libraries are designed to be used in Windows Vista or later. They all use the same core API, but each one offers its own user interface and features. The most important part of these libraries is that they allow you to play any type of file format without having to install additional codecs or software. You can play everything from MP3s to OGGs with them! There are many C# music player libraries out there that you can use in your next project. Some of them require you to spend a lot of time and effort on building a custom UI while others are very simple and easy to use. Dopamine-windows is a free, open-source library that can be used in any Windows application. It supports all the common file formats and codecs, as well as streaming audio. BreadPlayer library is an alternative to the popular VLC media player. It was developed by the folks at Google, so you know it's well. GMusic library offers support for various audio players, including Winamp and Windows Media Player. Full list of the best open source C# music player libraries are below

Python Music Player libraries like FeelUOwn, Quodlibet, TauonMusicBox, Python-mpd2 are basically a wrapper around the mpd protocol. Each provides a slightly different interface for playing music from your local server or streaming audio from the internet. You can use them to play your own music files (you'll have to convert them to MP3 format) or stream online music from sites like Spotify, SoundCloud and YouTube. FeelUOwn is focused on playing music stored on your own computer - so you can use it to play any songs you have stored in your iTunes library. FeelUOwn is a lightweight, easy to use Python library for playing music with the MPD (Music Player Daemon) server. Quodlibet is focused on playing music stored on other people's computers - so you can use it to play any songs they've uploaded to their own websites. Quodlibet is a music player/library written in Python which works with the Music Player Daemon (MPD). Quodlibet supports many features such as album art fetching and tag editing. TauonMusicBox is focused on playing music played by other people (or vice versa). It is an open source library for playing music from various sources. Python-mpd2 is a fork of the original MPD2 music player written in Python. It has been rewritten from scratch to be much more intuitive and user friendly, with a focus on music discovery. Check out the list of free, open source Python Music Player libraries to help you with your projects

PHP Music Player libraries let you create a music player application as easily as you would build a simple HTML page. As with any programming language, a significant amount of time is required to master PHP and make it useful in your projects. PHP Music Player libraries like AdvMusicPlayer, Noctifer-Music, php-music-player, core and many others are available to download in the official PHP downloads section of the PHP website. These libraries provide a way to play music from your files or streams, by using a simple object model. PHP-Music-Player is one of the most popular music player libraries, which can be easily built with the help of composer and Laravel. Noctifer-Music produces simple, high-quality music using current server technologies. AdvMusicPlayer performs advanced audio manipulation including pitch shifting, thresholding and time stretching. The AdvMusicPlayer can be used with any standard situation where a music player should be: on the web, in an application or as a console application. It supports the following music formats: mp3, ogg and wav. Using the library you can easily create unlimited playlists, search for song and artist names and generate playlists from their tags, as well as get track information from youtube/lastfm. It allows you to access detailed information about every single song in a playlist by displaying album covers in coverflow mode when playing songs in list view mode. It also enables you to increment/decrement play speed for individual songs or entire playlist. Popular open source PHP Music Player libraries include

One of the most popular types of music players are C++ libraries like Clementine, Musikcube, Strawberry, Olivia and MPZ. C++ Music Player libraries are used to play music in a variety of ways. They can be used to automatically download music from the internet, or to provide a basic user interface for managing music. These libraries have been designed by professional developers who know what they are doing when it comes to coding for audio players. Clementine is a cross-platform media player for GNOME 3 that supports a wide range of audio and video formats on the Linux desktop. The latest version of Clementine was released in February 2019 with improvements for scrobbling and an improved web interface for controlling playback. MusikCube music player is designed for Linux/Unix users who want to enjoy their music collection from different sources like local disk, network shares or portable devices. It's easy to use and supports many different audios file formats, as well as video files in various formats such as OGG and MP4 (h264). Strawberry is a cross-platform GTK+2 music player, which can play all common audio formats supported by gstreamer such as FLAC, MP3, Ogg Vorbis, Musepack (also known as MP1), AAC (M4A) and so on. Olivia is a lightweight GTK+ audio player that supports many popular formats. It features an easy-to-use interface with many configuration options and customizable behaviour via plugins. Popular open source C++ music player libraries among developers include

The use of Java Music Player libraries like MusicDNA, Phonograph, Shuttle, Auro and many others allows you to write a program that plays music with very simple code. These libraries can help you to create a custom music player application that works with your company's existing music library. The following sections describe some of the popular Java music player libraries and how they can be used in your applications. MusicDNA is a Java-based audio player that can play MP3, OGG, WAV and other audio formats. It supports ID3v2 tags and has a simple but powerful user interface. You can also download songs directly from the web or stream them over the Internet using the included HTTP server. Phonograph is a Java-based music player that supports ID3v2 and OGG tags. It has an easy to use interface with support for downloading songs directly from the Web. Shuttle is a Java-based music player that supports ID3v2 and OGG tags. It has an easy to use interface with support for downloading songs from the Web as well as streaming them over the Internet using the included HTTP server. Auro is a Java-based music player that supports ID3v2 and OGG tags. It has an easy to use interface with support for downloading songs from the Web as well as streaming them over the Internet using the included HTTP server. The entire list of open source Java Music Player libraries is provided below

Go Music Player is a free and open source media player for Android. The player is designed to be simple, fast and easy to use. It features a familiar interface from the classic MP3 players. The main advantage of using Go Music Player is that it has a very simple interface with no unnecessary features which makes it easier for users who are not tech savvy. PMS, Orchid, Ymuse and Gompd are the most popular ones. They have their respective plugins for browsers like Firefox, Chrome and Safari. I recommend using them if you want to use your favorite music player on the desktop or in a browser tab. Trollibox is another good choice if you want to use your favorite music player on your Android device (but it doesn't work well with headphones). Ymuse will help you learn how to play the guitar. It has many high-quality songs, which are all free and downloadable. You can also find videos on the site that show you exactly how to play each song. The Gompd library includes several different styles of music, including pop, rock and country. There is also a section of songs with lyrics included so that you can learn how to sing along with them if you choose. Many developers depend on the following open source Go Music Player libraries

Trending Discussions on Music Player

How do I make a media player control notification in Gtk?

Can't play wav or mp3 files with Javafx MediaPlayer. Also can't play wav files with the native java library

Is it possible to create a browser based html/javascript audio player, that handles most of the MPRIS commands?

AudioManager auto switching own mode + not respecting setSpeakerphoneOn()

Apple MusicKit play album by identifier doesn't work

How to convert each row/cell values from a DataFrame to a list of dictionaries in pandas?

Tkinter animation goes faster and faster

how to make a loop for a play/pause button using javascript/jquery

Using Eel calling JavaScript function in python only when a condition is True

Icon not aligning in the center of FloatingActionButton

QUESTION

How do I make a media player control notification in Gtk?

Asked 2022-Mar-09 at 21:39

In Rhythmbox (GNOME's music player), when it's playing music, you can open the notifications panel and control the music playback from there. Here's a screenshot. The playback controls are bordered in orange; they have a little music note icon:

enter image description here

This is what I want to make; the media playback controls. Note that, while it is in the notifications panel, it's not technically a notification, because it never pops up on the screen, and you can't make it go away. In the screenshot, you can see the actual notification, which I don't want to make, below the controls.

I know that there's a Gio.Notification, but it's not quite what I need (unless I'm very much mistaken). I searched in Gio, Gdk, and Gtk, but I didn't find anything. I also searched, among other things, [gtk] media control and [gtk] media notification on Stack Overflow, but I didn't find anything there either.

Thanks to the help of BobMorane, I've now figured out that Rhythmbox uses libnotify for its player controls. I know how to create actions using Notify.Notification, and I can make them have images, etc., but what I still haven't figured out is how to:

  1. Make the notification so that it can't be closed;
  2. Make it so that the action buttons are next to the icon and text, not under;
  3. Keep the notification on top of all the others in the notifications panel.

Using Python's help() function to look at gi.repository.Notify.Notification, the only methods I see that seem to have potential are add_action() (particularly its user_data parameter) and set_hint() (and its variants). Could these be used to achieve my goal?

How do I make a media-control "notification" in Gtk with Python, as explained above?

ANSWER

Answered 2022-Mar-09 at 21:22

I think the technology used by Rhytmbox to acheive this is MPRIS (Media Player Remote Interfacing Specification). As they say on their we page:

The Media Player Remote Interfacing Specification (MPRIS) is a standard D-Bus interface which aims to provide a common programmatic API for controlling media players.

It provides a mechanism for discovery, querying and basic playback control of compliant media players, as well as a tracklist interface which is used to add context to the active media item.

In Rhythmbox, this is implemented as a core plug-in. The code is pretty complicated, but basically implements the MPRIS specification. This implementation then exposes some information and controls out to other applications which want to control the Rhythmbox, like the Gnome Shell in your case. If you deactivate the MPRIS plug-in, the "notification player" will no longer work.

In GNOME Shell, you can see they have their own MPRIS module as well (https://gitlab.gnome.org/GNOME/gnome-shell/-/blob/main/js/ui/mpris.js), which is used to:

  1. Respond to player notifications and display information (album art, title, buttons, etc).
  2. Send notifications to the player (ex.: pause the song).

In this module, the formatting of the buttons and all that stuff comes into life as well. This means that on your part (the player's designer), you should have no UI formatting to do (you don't have control over this, GNOME Shell has). What you need to do is expose what is needed by the GNOME Shell by implementing the MPRIS interfaces.

(As a side note: the calendar.js file is the one implementing the notification list, and you can see it uses MPRIS "notifications", which it puts on top of standard notifications.)

There exist Python libraries to do so, such as Mopidy-MPRIS, bit their support for the GNOME Shell seems not to be working at the moment. You may have to look for D-Bus related libraries on FreeDesktop.org. There exists many bindings, with some in Python.

I hope this points you in the right direction.

Source https://stackoverflow.com/questions/71288860

QUESTION

Can't play wav or mp3 files with Javafx MediaPlayer. Also can't play wav files with the native java library

Asked 2022-Feb-13 at 09:17

I have a java project where I have to make a music player that plays either wav or mp3 files. However I can't get my wav or mp3 files to play using the Javafx libraries or with native java libraries. I've checked and made sure the wav and mp3 files I'm using to test aren't corrupted. I'm using Javafx 17.0.2 and JDK 11.

Mini Reproducible Example With Javafx JavaFxMp3WavPlayer
1package mediaplayerjavafx;
2
3import java.io.File;
4import java.io.IOException;
5import java.net.MalformedURLException;
6import javafx.application.Application;
7import javafx.event.Event;
8import javafx.event.EventHandler;
9import javafx.scene.Scene;
10import javafx.scene.control.Button;
11import javafx.scene.media.Media;
12import javafx.scene.media.MediaPlayer;
13import javafx.stage.Stage;
14
15public class JavaFxMp3WavPlayer extends Application {
16
17    public static void main(String[] args) throws MalformedURLException, IOException {
18        launch(args);
19
20    }
21
22    @Override
23    public void start(Stage stage) throws Exception {
24        stage.setTitle("My");
25        Button button = new Button("My Button");
26        Scene scene = new Scene(button, 200, 100);
27        stage.setScene(scene);
28        stage.show();
29        File file = new File("C:\\Users\\John Doe\\MotisHarmony\\accounts\\yourLieInApril\\downloadedMusic\\Mp3Test.mp3");
30        String path = file.toURI().toASCIIString();
31        Media media = new Media(path);
32        MediaPlayer mediaPlayer = new MediaPlayer(media);
33        button.setOnAction(new EventHandler() {
34            @Override
35            public void handle(Event arg0) {
36                runMusicPlayer(mediaPlayer);
37            }
38        });
39    }
40
41    public void runMusicPlayer(MediaPlayer mediaPlayer) {
42        mediaPlayer.play();
43    }
44}
45
module-info
1package mediaplayerjavafx;
2
3import java.io.File;
4import java.io.IOException;
5import java.net.MalformedURLException;
6import javafx.application.Application;
7import javafx.event.Event;
8import javafx.event.EventHandler;
9import javafx.scene.Scene;
10import javafx.scene.control.Button;
11import javafx.scene.media.Media;
12import javafx.scene.media.MediaPlayer;
13import javafx.stage.Stage;
14
15public class JavaFxMp3WavPlayer extends Application {
16
17    public static void main(String[] args) throws MalformedURLException, IOException {
18        launch(args);
19
20    }
21
22    @Override
23    public void start(Stage stage) throws Exception {
24        stage.setTitle("My");
25        Button button = new Button("My Button");
26        Scene scene = new Scene(button, 200, 100);
27        stage.setScene(scene);
28        stage.show();
29        File file = new File("C:\\Users\\John Doe\\MotisHarmony\\accounts\\yourLieInApril\\downloadedMusic\\Mp3Test.mp3");
30        String path = file.toURI().toASCIIString();
31        Media media = new Media(path);
32        MediaPlayer mediaPlayer = new MediaPlayer(media);
33        button.setOnAction(new EventHandler() {
34            @Override
35            public void handle(Event arg0) {
36                runMusicPlayer(mediaPlayer);
37            }
38        });
39    }
40
41    public void runMusicPlayer(MediaPlayer mediaPlayer) {
42        mediaPlayer.play();
43    }
44}
45module MotisHarmony {
46    requires javafx.swt;
47    requires javafx.base;
48    requires javafx.controls;
49    requires javafx.fxml;
50    requires javafx.graphics;
51    requires javafx.media;
52    requires javafx.swing;
53    requires javafx.web;
54    exports mediaplayerjavafx;
55    opens mediaplayerjavafx to javafx.graphics;
56}
57
Error Produced
1package mediaplayerjavafx;
2
3import java.io.File;
4import java.io.IOException;
5import java.net.MalformedURLException;
6import javafx.application.Application;
7import javafx.event.Event;
8import javafx.event.EventHandler;
9import javafx.scene.Scene;
10import javafx.scene.control.Button;
11import javafx.scene.media.Media;
12import javafx.scene.media.MediaPlayer;
13import javafx.stage.Stage;
14
15public class JavaFxMp3WavPlayer extends Application {
16
17    public static void main(String[] args) throws MalformedURLException, IOException {
18        launch(args);
19
20    }
21
22    @Override
23    public void start(Stage stage) throws Exception {
24        stage.setTitle("My");
25        Button button = new Button("My Button");
26        Scene scene = new Scene(button, 200, 100);
27        stage.setScene(scene);
28        stage.show();
29        File file = new File("C:\\Users\\John Doe\\MotisHarmony\\accounts\\yourLieInApril\\downloadedMusic\\Mp3Test.mp3");
30        String path = file.toURI().toASCIIString();
31        Media media = new Media(path);
32        MediaPlayer mediaPlayer = new MediaPlayer(media);
33        button.setOnAction(new EventHandler() {
34            @Override
35            public void handle(Event arg0) {
36                runMusicPlayer(mediaPlayer);
37            }
38        });
39    }
40
41    public void runMusicPlayer(MediaPlayer mediaPlayer) {
42        mediaPlayer.play();
43    }
44}
45module MotisHarmony {
46    requires javafx.swt;
47    requires javafx.base;
48    requires javafx.controls;
49    requires javafx.fxml;
50    requires javafx.graphics;
51    requires javafx.media;
52    requires javafx.swing;
53    requires javafx.web;
54    exports mediaplayerjavafx;
55    opens mediaplayerjavafx to javafx.graphics;
56}
57Exception in Application start method
58java.lang.reflect.InvocationTargetException
59    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
60    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
61    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
62    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
63    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:465)
64    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:364)
65    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
66    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
67    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
68    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
69    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
70Caused by: java.lang.RuntimeException: Exception in Application start method
71    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:901)
72    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
73    at java.base/java.lang.Thread.run(Thread.java:834)
74Caused by: MediaException: UNKNOWN : com.sun.media.jfxmedia.MediaException: Could not create player! : com.sun.media.jfxmedia.MediaException: Could not create player!
75    at javafx.media/javafx.scene.media.MediaException.exceptionToMediaException(MediaException.java:146)
76    at javafx.media/javafx.scene.media.MediaPlayer.init(MediaPlayer.java:519)
77    at javafx.media/javafx.scene.media.MediaPlayer.<init>(MediaPlayer.java:422)
78    at MotisHarmony/mediaplayerjavafx.JavaFxMp3WavPlayer.start(JavaFxMp3WavPlayer.java:37)
79    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:847)
80    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:484)
81    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:457)
82    at java.base/java.security.AccessController.doPrivileged(Native Method)
83    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:456)
84    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
85    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
86    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
87    ... 1 more
88Caused by: com.sun.media.jfxmedia.MediaException: Could not create player!
89    at javafx.media/com.sun.media.jfxmediaimpl.NativeMediaManager.getPlayer(NativeMediaManager.java:297)
90    at javafx.media/com.sun.media.jfxmedia.MediaManager.getPlayer(MediaManager.java:118)
91    at javafx.media/javafx.scene.media.MediaPlayer.init(MediaPlayer.java:475)
92    ... 11 more
93Exception running application mediaplayerjavafx.JavaFxMp3WavPlayer
94

So after this didn't work, I tried it with native Java libraries.

Mini Reproducible Example With Native Java Libraries JavaWavPlayer
1package mediaplayerjavafx;
2
3import java.io.File;
4import java.io.IOException;
5import java.net.MalformedURLException;
6import javafx.application.Application;
7import javafx.event.Event;
8import javafx.event.EventHandler;
9import javafx.scene.Scene;
10import javafx.scene.control.Button;
11import javafx.scene.media.Media;
12import javafx.scene.media.MediaPlayer;
13import javafx.stage.Stage;
14
15public class JavaFxMp3WavPlayer extends Application {
16
17    public static void main(String[] args) throws MalformedURLException, IOException {
18        launch(args);
19
20    }
21
22    @Override
23    public void start(Stage stage) throws Exception {
24        stage.setTitle("My");
25        Button button = new Button("My Button");
26        Scene scene = new Scene(button, 200, 100);
27        stage.setScene(scene);
28        stage.show();
29        File file = new File("C:\\Users\\John Doe\\MotisHarmony\\accounts\\yourLieInApril\\downloadedMusic\\Mp3Test.mp3");
30        String path = file.toURI().toASCIIString();
31        Media media = new Media(path);
32        MediaPlayer mediaPlayer = new MediaPlayer(media);
33        button.setOnAction(new EventHandler() {
34            @Override
35            public void handle(Event arg0) {
36                runMusicPlayer(mediaPlayer);
37            }
38        });
39    }
40
41    public void runMusicPlayer(MediaPlayer mediaPlayer) {
42        mediaPlayer.play();
43    }
44}
45module MotisHarmony {
46    requires javafx.swt;
47    requires javafx.base;
48    requires javafx.controls;
49    requires javafx.fxml;
50    requires javafx.graphics;
51    requires javafx.media;
52    requires javafx.swing;
53    requires javafx.web;
54    exports mediaplayerjavafx;
55    opens mediaplayerjavafx to javafx.graphics;
56}
57Exception in Application start method
58java.lang.reflect.InvocationTargetException
59    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
60    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
61    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
62    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
63    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:465)
64    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:364)
65    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
66    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
67    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
68    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
69    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
70Caused by: java.lang.RuntimeException: Exception in Application start method
71    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:901)
72    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
73    at java.base/java.lang.Thread.run(Thread.java:834)
74Caused by: MediaException: UNKNOWN : com.sun.media.jfxmedia.MediaException: Could not create player! : com.sun.media.jfxmedia.MediaException: Could not create player!
75    at javafx.media/javafx.scene.media.MediaException.exceptionToMediaException(MediaException.java:146)
76    at javafx.media/javafx.scene.media.MediaPlayer.init(MediaPlayer.java:519)
77    at javafx.media/javafx.scene.media.MediaPlayer.<init>(MediaPlayer.java:422)
78    at MotisHarmony/mediaplayerjavafx.JavaFxMp3WavPlayer.start(JavaFxMp3WavPlayer.java:37)
79    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:847)
80    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:484)
81    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:457)
82    at java.base/java.security.AccessController.doPrivileged(Native Method)
83    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:456)
84    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
85    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
86    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
87    ... 1 more
88Caused by: com.sun.media.jfxmedia.MediaException: Could not create player!
89    at javafx.media/com.sun.media.jfxmediaimpl.NativeMediaManager.getPlayer(NativeMediaManager.java:297)
90    at javafx.media/com.sun.media.jfxmedia.MediaManager.getPlayer(MediaManager.java:118)
91    at javafx.media/javafx.scene.media.MediaPlayer.init(MediaPlayer.java:475)
92    ... 11 more
93Exception running application mediaplayerjavafx.JavaFxMp3WavPlayer
94import java.io.File;
95import java.io.IOException;
96import javax.sound.sampled.AudioFormat;
97import javax.sound.sampled.AudioInputStream;
98import javax.sound.sampled.AudioSystem;
99import javax.sound.sampled.Clip;
100import javax.sound.sampled.DataLine;
101import javax.sound.sampled.LineUnavailableException;
102import javax.sound.sampled.UnsupportedAudioFileException;
103
104public class JavaWavPlayer {
105
106    /**
107     * @param args the command line arguments
108     */
109    public static Clip clip;
110
111    public static void main(String[] args) throws UnsupportedAudioFileException, LineUnavailableException, IOException {
112        File yourFile = new File("C:\\Users\\John Doe\\MotisHarmony\\accounts\\yourLieInApril\\downloadedMusic\\WavTest.wav");
113        AudioInputStream stream;
114        AudioFormat format;
115        DataLine.Info info;
116        stream = AudioSystem.getAudioInputStream(yourFile);
117        format = stream.getFormat();
118        info = new DataLine.Info(Clip.class, format);
119        clip = (Clip) AudioSystem.getLine(info);
120        clip.open(stream);
121        clip.start();
122    }
123
124}
125
Error Produced
1package mediaplayerjavafx;
2
3import java.io.File;
4import java.io.IOException;
5import java.net.MalformedURLException;
6import javafx.application.Application;
7import javafx.event.Event;
8import javafx.event.EventHandler;
9import javafx.scene.Scene;
10import javafx.scene.control.Button;
11import javafx.scene.media.Media;
12import javafx.scene.media.MediaPlayer;
13import javafx.stage.Stage;
14
15public class JavaFxMp3WavPlayer extends Application {
16
17    public static void main(String[] args) throws MalformedURLException, IOException {
18        launch(args);
19
20    }
21
22    @Override
23    public void start(Stage stage) throws Exception {
24        stage.setTitle("My");
25        Button button = new Button("My Button");
26        Scene scene = new Scene(button, 200, 100);
27        stage.setScene(scene);
28        stage.show();
29        File file = new File("C:\\Users\\John Doe\\MotisHarmony\\accounts\\yourLieInApril\\downloadedMusic\\Mp3Test.mp3");
30        String path = file.toURI().toASCIIString();
31        Media media = new Media(path);
32        MediaPlayer mediaPlayer = new MediaPlayer(media);
33        button.setOnAction(new EventHandler() {
34            @Override
35            public void handle(Event arg0) {
36                runMusicPlayer(mediaPlayer);
37            }
38        });
39    }
40
41    public void runMusicPlayer(MediaPlayer mediaPlayer) {
42        mediaPlayer.play();
43    }
44}
45module MotisHarmony {
46    requires javafx.swt;
47    requires javafx.base;
48    requires javafx.controls;
49    requires javafx.fxml;
50    requires javafx.graphics;
51    requires javafx.media;
52    requires javafx.swing;
53    requires javafx.web;
54    exports mediaplayerjavafx;
55    opens mediaplayerjavafx to javafx.graphics;
56}
57Exception in Application start method
58java.lang.reflect.InvocationTargetException
59    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
60    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
61    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
62    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
63    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:465)
64    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:364)
65    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
66    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
67    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
68    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
69    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
70Caused by: java.lang.RuntimeException: Exception in Application start method
71    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:901)
72    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
73    at java.base/java.lang.Thread.run(Thread.java:834)
74Caused by: MediaException: UNKNOWN : com.sun.media.jfxmedia.MediaException: Could not create player! : com.sun.media.jfxmedia.MediaException: Could not create player!
75    at javafx.media/javafx.scene.media.MediaException.exceptionToMediaException(MediaException.java:146)
76    at javafx.media/javafx.scene.media.MediaPlayer.init(MediaPlayer.java:519)
77    at javafx.media/javafx.scene.media.MediaPlayer.<init>(MediaPlayer.java:422)
78    at MotisHarmony/mediaplayerjavafx.JavaFxMp3WavPlayer.start(JavaFxMp3WavPlayer.java:37)
79    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:847)
80    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:484)
81    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:457)
82    at java.base/java.security.AccessController.doPrivileged(Native Method)
83    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:456)
84    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
85    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
86    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
87    ... 1 more
88Caused by: com.sun.media.jfxmedia.MediaException: Could not create player!
89    at javafx.media/com.sun.media.jfxmediaimpl.NativeMediaManager.getPlayer(NativeMediaManager.java:297)
90    at javafx.media/com.sun.media.jfxmedia.MediaManager.getPlayer(MediaManager.java:118)
91    at javafx.media/javafx.scene.media.MediaPlayer.init(MediaPlayer.java:475)
92    ... 11 more
93Exception running application mediaplayerjavafx.JavaFxMp3WavPlayer
94import java.io.File;
95import java.io.IOException;
96import javax.sound.sampled.AudioFormat;
97import javax.sound.sampled.AudioInputStream;
98import javax.sound.sampled.AudioSystem;
99import javax.sound.sampled.Clip;
100import javax.sound.sampled.DataLine;
101import javax.sound.sampled.LineUnavailableException;
102import javax.sound.sampled.UnsupportedAudioFileException;
103
104public class JavaWavPlayer {
105
106    /**
107     * @param args the command line arguments
108     */
109    public static Clip clip;
110
111    public static void main(String[] args) throws UnsupportedAudioFileException, LineUnavailableException, IOException {
112        File yourFile = new File("C:\\Users\\John Doe\\MotisHarmony\\accounts\\yourLieInApril\\downloadedMusic\\WavTest.wav");
113        AudioInputStream stream;
114        AudioFormat format;
115        DataLine.Info info;
116        stream = AudioSystem.getAudioInputStream(yourFile);
117        format = stream.getFormat();
118        info = new DataLine.Info(Clip.class, format);
119        clip = (Clip) AudioSystem.getLine(info);
120        clip.open(stream);
121        clip.start();
122    }
123
124}
125Exception in thread "main" java.lang.IllegalArgumentException: No line matching interface Clip supporting format PCM_SIGNED 44100.0 Hz, 16 bit, stereo, 4 bytes/frame, little-endian is supported.
126    at java.desktop/javax.sound.sampled.AudioSystem.getLine(AudioSystem.java:425)
127    at javawavplayer.JavaWavPlayer.main(JavaWavPlayer.java:33)
128C:\Users\John Doe\Dropbox(Old)\My PC (DESKTOP-P6JNU2B)\Documents\NetBeansProjects\JavaWavPlayer\nbproject\build-impl.xml:1330: The following error occurred while executing this line:
129C:\Users\John Doe\Dropbox(Old)\My PC (DESKTOP-P6JNU2B)\Documents\NetBeansProjects\JavaWavPlayer\nbproject\build-impl.xml:936: Java returned: 1
130
Extra Information

Link to the Mp3 file I used to test. https://drive.google.com/file/d/1CvAafbMviQ7nvKyojnem9GK73LJsD6MJ/view?usp=sharing

Link to the Wav file I used to text. https://drive.google.com/file/d/1k7a93pZIGY65sGs8BrFMDgeRrgYc0C5k/view?usp=sharing

I am using JDK 11 and Javafx 17.0.2

System Type: 64-bit operating system, x64-based processor

Processor: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz 2.81 GHz

Windows Edition: Windows 10 Home

ANSWER

Answered 2022-Feb-13 at 09:17

I could not reproduce your issue.

Your issue is environmental, exactly what it is I could not say.

I advise creating a new project in idea and following the same steps I did and it should work as long as you have the file path correct.

These are the steps I followed to get allow the media to play with your sample app:

  1. Created a new JavaFX project in Idea with OpenJDK 17.0.2 and JavaFX 17.0.2 on Windows 11.

  2. Copy-and-pasted your JavaFX sample code into the new project.

  3. Followed the instructions to add media handling to the project:

  4. Downloaded your mp3 and wav files.

  5. Set the file path to each in turn.

  6. Ran the app and hit the play button for each file.

Both the MP3 and WAV files played without problem.

Your lie in april is nice, I will try to learn it.

Source https://stackoverflow.com/questions/71096610

QUESTION

Is it possible to create a browser based html/javascript audio player, that handles most of the MPRIS commands?

Asked 2022-Feb-12 at 09:09

I am trying to create a music player, that can handle most of the MPRIS commands.

During youtube is playing, playerctl list the firefox player (firefox.instance{id}), and if it has playlist then I can skip to previous / next item using $ playerctl -p firefox.instance{id} next. This works in chrome too.

I want to implement the same behavior in a React.js application, but first I'm looking for a html/javascript based solution.

One of my guesses that this is impossible (without using a browser add-on), because firefox implements this manually for each supported website.

Maybe I did something wrong, but no matter what I search for I couldn't find any information about this.

Thanks for reading / commenting!

ANSWER

Answered 2022-Feb-12 at 09:09

Media Session API seems to solve this problem pretty well: https://developer.mozilla.org/en-US/docs/Web/API/Media_Session_API

This event listener runs every time $ playerctl -p firefox.instance{id} next is run (or when any other MPRIS client calls 'next', like KDE connect on android):

1  navigator.mediaSession.setActionHandler('previoustrack', function() { /* Code excerpted. */ });
2

It even works in chrome (except the skipad event). More information can be found on the MDN Web Docs 'Media Session API' page I linked above.

Source https://stackoverflow.com/questions/71084867

QUESTION

AudioManager auto switching own mode + not respecting setSpeakerphoneOn()

Asked 2022-Feb-11 at 19:31

I want to play some audio with volume lvl adjusted to ear aka. "phone call mode". For this purpose, I'm using well-known and commonly advised

1audioManager.setMode(audioNormalState ?
2            AudioManager.MODE_NORMAL : AudioManager.MODE_IN_COMMUNICATION);
3

The problem is that I'm not always playing audio just after mode switching, I have to wait and can't be sure how long, it may be even minutes. I've made some looped logging and MODE_IN_COMMUNICATION mode is kept as long as the user is in "phone call mode" in my app on some Motorola with Android 9, but on Pixel 3 with Android 12 after 6 seconds mode is auto-switching back to MODE_NORMAL when nothing is played. No additional code executed (like some listener), no additional (system) logs. When I start playing audio 1 sec after switching to MODE_IN_COMMUNICATION mode it won't auto-switch as long as the audio is played (even more than 6 secs), but right after finishing mode gets also auto-switched to MODE_NORMAL.

My app makes sort-of real-time voice calls (commands), but can also "beep" a few signals-patterns, and there is also a history feature providing all chronological sound-making actions to be played again in order. If this would be only voice then switching to MODE_IN_COMMUNICATION and back only during a call might be sufficient, but what to do with highly-important SoundPool jingles, do I have to switch mode also for them? (or for history play, which is a mix) AFAIK mode switching isn't fast (even a few secs on some devices), so I may apply some significant delay for short hundreds-of-ms signals (no way, every ms is crucial!) or I'm risking playing out loud signal/voice even in "phone call mode", when mode doesn't change "fast enough" (user won't be happy). I was relying on setting fixed (but configured according to app state and settings) MODE_IN_COMMUNICATION, which was working till Android 12... (can confirm new/wrong behavior on Pixels and Samsungs)

currently used method for switching audio mode + configuration below, worth noting that setSpeakerphoneOn method also doesn't work always on Android 12. At least not when on MODE_NORMAL, which is default auto-switch-back-to mode now, also isSpeakerphoneOn is false on the very first start, but all my audio sources are in fact played loud...

1audioManager.setMode(audioNormalState ?
2            AudioManager.MODE_NORMAL : AudioManager.MODE_IN_COMMUNICATION);
3// forceAudioNormalState = true only when app exit!
4public static void resolveLoudState(AudioManager audioManager, boolean forceAudioNormalState) {
5    boolean silentPhoneCallMode = isPhoneCallModeEnabled(); // phone call GUI, only ear-friendly volume!!
6    boolean silentHeadset = HeadsetPlugReceiver.isHeadsetPlugged &&
7            !HeadsetPlugReceiver.forceSpeakerWhenHeadsetOn; // headset plugged, but "muted", force speaker
8    boolean silentBluetooth = BluetoothController.isAudioDeviceConnected() &&
9            !audioManager.isBluetoothScoOn(); // bt headset plugged, but "muted", force speaker
10
11    boolean loud = true; // by default
12    if (silentPhoneCallMode || silentHeadset || silentBluetooth) loud = false;
13
14    String log = String.format("resolveLoudState play loud: %s," +
15                    " silentPhoneCallMode: %s, silentHeadset: %s, silentBluetooth: %s",
16            loud, silentPhoneCallMode, silentHeadset, silentBluetooth);
17    Timber.i(log);
18
19    audioManager.setMode(forceAudioNormalState ?
20            AudioManager.MODE_NORMAL : AudioManager.MODE_IN_COMMUNICATION);
21    audioManager.setSpeakerphoneOn(loud);
22    // even if deprecated this still works! fake wired headset on even for bt
23    audioManager.setWiredHeadsetOn(!loud && (silentHeadset || silentBluetooth));
24    // not loud and any headset connected and "muted"
25}
26

note that in the above snippet there is no flag/information about the current playing state, only apps state/config

I want to manage these modes by myself and decide which audio output will be used or maybe there is any other way for forcing playing all audio (AudioTrack, SoundPool, MediaPlayer, ExoPlayer etc.) with ear-friendly adjusted volume?

edit: Just noticed when the mode auto-switches to MODE_NORMAL and I will start playing STREAM_VOICE_CALL it will auto switch to MODE_IN_COMMUNICATION (with some small but significant delay) and reset back again just after finishing audio... This is some new undocumented behavior of system overall, become very unfriendly, bugged and unclear API...

edit2: this looks like related issue

PS. I've noticed that MediaSession apps (e.g. music players) on Android 12 device got a new option straight on Notification for picking speaker/headphones when wired/bt headset/earphones connected, but I'm not using session API at all. bonus question: is there an API for that?

ANSWER

Answered 2022-Feb-11 at 19:31

found some answers to my own question, sharing with community

6-sec auto-switch mode is a new feature in Android 12, which works only if (mode == AudioSystem.MODE_IN_COMMUNICATION) (check out flow related to MSG_CHECK_MODE_FOR_UID flag). This should help for MODE_IN_COMMUNICATION set to AudioManager and left after app exit, this was messing with global/system-level audio routing. There is also a brand new AudioManager.OnModeChangedListener called when mode is (auto-)changing

and setSpeakerphoneOn turns out to be deprecated, even if this isn't marked in doc... we have new method setCommunicationDevice(AudioDeviceInfo) and in its description we have info about startBluetoothSco(), stopBluetoothSco() and setSpeakerphoneOn(boolean) deprecation. I'm using all three methods and now on Android 12 I'm iterating through getAvailableCommunicationDevices(), comparing type of every item and if desired type found I'm calling setCommunicationDevice(targetAudioDeviceInfo). I'm NOT switching audio mode at all now, staying on MODE_NORMAL. All my streams are AudioManager.STREAM_VOICE_CALL type (where applicable)

for built-in earpiece audio playback aka. "ear-friendly mode" we were using

1audioManager.setMode(audioNormalState ?
2            AudioManager.MODE_NORMAL : AudioManager.MODE_IN_COMMUNICATION);
3// forceAudioNormalState = true only when app exit!
4public static void resolveLoudState(AudioManager audioManager, boolean forceAudioNormalState) {
5    boolean silentPhoneCallMode = isPhoneCallModeEnabled(); // phone call GUI, only ear-friendly volume!!
6    boolean silentHeadset = HeadsetPlugReceiver.isHeadsetPlugged &&
7            !HeadsetPlugReceiver.forceSpeakerWhenHeadsetOn; // headset plugged, but "muted", force speaker
8    boolean silentBluetooth = BluetoothController.isAudioDeviceConnected() &&
9            !audioManager.isBluetoothScoOn(); // bt headset plugged, but "muted", force speaker
10
11    boolean loud = true; // by default
12    if (silentPhoneCallMode || silentHeadset || silentBluetooth) loud = false;
13
14    String log = String.format("resolveLoudState play loud: %s," +
15                    " silentPhoneCallMode: %s, silentHeadset: %s, silentBluetooth: %s",
16            loud, silentPhoneCallMode, silentHeadset, silentBluetooth);
17    Timber.i(log);
18
19    audioManager.setMode(forceAudioNormalState ?
20            AudioManager.MODE_NORMAL : AudioManager.MODE_IN_COMMUNICATION);
21    audioManager.setSpeakerphoneOn(loud);
22    // even if deprecated this still works! fake wired headset on even for bt
23    audioManager.setWiredHeadsetOn(!loud && (silentHeadset || silentBluetooth));
24    // not loud and any headset connected and "muted"
25}
26if (earpieceMode) {
27    audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
28    audioManager.setSpeakerphoneOn(false); // call AFTER setMode
29}
30

that won't work reliable on Android 12 (after multiple speakerphone state switches). Now I'm using below code (comprehensive snippet)

1audioManager.setMode(audioNormalState ?
2            AudioManager.MODE_NORMAL : AudioManager.MODE_IN_COMMUNICATION);
3// forceAudioNormalState = true only when app exit!
4public static void resolveLoudState(AudioManager audioManager, boolean forceAudioNormalState) {
5    boolean silentPhoneCallMode = isPhoneCallModeEnabled(); // phone call GUI, only ear-friendly volume!!
6    boolean silentHeadset = HeadsetPlugReceiver.isHeadsetPlugged &&
7            !HeadsetPlugReceiver.forceSpeakerWhenHeadsetOn; // headset plugged, but "muted", force speaker
8    boolean silentBluetooth = BluetoothController.isAudioDeviceConnected() &&
9            !audioManager.isBluetoothScoOn(); // bt headset plugged, but "muted", force speaker
10
11    boolean loud = true; // by default
12    if (silentPhoneCallMode || silentHeadset || silentBluetooth) loud = false;
13
14    String log = String.format("resolveLoudState play loud: %s," +
15                    " silentPhoneCallMode: %s, silentHeadset: %s, silentBluetooth: %s",
16            loud, silentPhoneCallMode, silentHeadset, silentBluetooth);
17    Timber.i(log);
18
19    audioManager.setMode(forceAudioNormalState ?
20            AudioManager.MODE_NORMAL : AudioManager.MODE_IN_COMMUNICATION);
21    audioManager.setSpeakerphoneOn(loud);
22    // even if deprecated this still works! fake wired headset on even for bt
23    audioManager.setWiredHeadsetOn(!loud && (silentHeadset || silentBluetooth));
24    // not loud and any headset connected and "muted"
25}
26if (earpieceMode) {
27    audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
28    audioManager.setSpeakerphoneOn(false); // call AFTER setMode
29}
30ArrayList<Integer> targetTypes = new ArrayList<>();
31//add types according to needs, may be few in order of importance
32if (bluetoothScoConnected) {
33    targetTypes.add(AudioDeviceInfo.TYPE_BLUETOOTH_SCO);
34} else if (wiredHeadsetConnected) {
35    if (isUsbHeadset) {
36        targetTypes.add(AudioDeviceInfo.TYPE_USB_HEADSET);
37        targetTypes.add(AudioDeviceInfo.TYPE_USB_DEVICE);
38        targetTypes.add(AudioDeviceInfo.TYPE_USB_ACCESSORY);
39    } else {
40        targetTypes.add(AudioDeviceInfo.TYPE_WIRED_HEADSET);
41        targetTypes.add(AudioDeviceInfo.TYPE_WIRED_HEADPHONES);
42    }
43} else if (earpieceMode) {
44    targetTypes.add(AudioDeviceInfo.TYPE_BUILTIN_EARPIECE);
45} else { // play out loud
46    targetTypes.add(AudioDeviceInfo.TYPE_BUILTIN_SPEAKER);
47}
48
49Boolean result = null;
50List<AudioDeviceInfo> devices = audioManager.getAvailableCommunicationDevices();
51
52outer:
53for (Integer targetType : targetTypes) {
54    for (AudioDeviceInfo device : devices) {
55        if (device.getType() == targetType) {
56            result = audioManager.setCommunicationDevice(device);
57            Log.i("AUDIO_MANAGER", "setCommunicationDevice type:" + targetType + " result:" + result);
58            break outer;
59        }
60    }
61}
62
63if (result == null) {
64    Log.i("AUDIO_MANAGER", "setCommunicationDevice targetType NOT FOUND!!");
65}
66

worth mentioning Bluetooth SCO headset case - when freshly connected/paired with device all my accessories are recognized as AudioDeviceInfo.TYPE_BLUETOOTH_A2DP type (getCommunicationDevice()). I do want SCO, which isn't listed in getAvailableCommunicationDevices() for few seconds after A2DP connection, so I'm leaving some countdown timer, which checks (interval 2s) and waits for AudioDeviceInfo.TYPE_BLUETOOTH_SCO for few secs (I've set 16), then I'm switching to this type when appear on list or just dismissing timer

Source https://stackoverflow.com/questions/70768622

QUESTION

Apple MusicKit play album by identifier doesn't work

Asked 2022-Jan-11 at 22:36

I've created a button which takes a selected album's store id and puts it in a queue for the music player, but for some reason, it does not play and returns the following error:

1Failed to prepareToPlay error: Error Domain=MPMusicPlayerControllerErrorDomain Code=6
2

Here is the code for the button (I put the player vars in there to be easier for here)

1Failed to prepareToPlay error: Error Domain=MPMusicPlayerControllerErrorDomain Code=6
2var storeIds: [String] = [ "ID" ]
3Button(action: {
4    let player = MPMusicPlayerController.applicationQueuePlayer
5    let queue  = MPMusicPlayerStoreQueueDescriptor(storeIDs: storeIds)
6    storeIds = ["\(album.id)".replacingOccurrences(of: "l.", with: "")]
7    
8    print("ID: ", storeIds) // Example ID:  ["Qn4Bnha"]
9    player.setQueue(with: storeIds)
10    player.play()
11})
12

Also, I remove the "l." from the id because every album starts with that which is not needed.

ANSWER

Answered 2022-Jan-11 at 22:36

If you're trying to play an album from the library, then I had problems with that as well.

From what I've noticed, the MusicItemID of a library song is different from an album song, and the player cannot play it. The same goes in the case of a library album. If I get the id of the library song and send another request to - https://api.music.apple.com/v1/me/library/albums/{id}/catalog, And then set it to the queue; it works fine.

You can get the album's local ID and then make another request to the catalog as a workaround. If there's an album on Apple Music, then it should work.

Here's an example that works fine for me:

1Failed to prepareToPlay error: Error Domain=MPMusicPlayerControllerErrorDomain Code=6
2var storeIds: [String] = [ "ID" ]
3Button(action: {
4    let player = MPMusicPlayerController.applicationQueuePlayer
5    let queue  = MPMusicPlayerStoreQueueDescriptor(storeIDs: storeIds)
6    storeIds = ["\(album.id)".replacingOccurrences(of: "l.", with: "")]
7    
8    print("ID: ", storeIds) // Example ID:  ["Qn4Bnha"]
9    player.setQueue(with: storeIds)
10    player.play()
11})
12do {
13  /// First request to get the heavy rotation albums
14  guard let url = URL(string: "https://api.music.apple.com/v1/me/history/heavy-rotation") else { return }
15  
16  let request = MusicDataRequest(urlRequest: URLRequest(url: url))
17  let response = try await request.response()
18  
19  let heavyRotationAlbums = try JSONDecoder().decode(MusicItemCollection<Album>.self, from: response.data)
20  
21  /// Get the first album
22  guard let album = heavyRotationAlbums.first else { return }
23  
24  /// Get the local album ID
25  let albumID = album.id
26
27  /// Another request to get the album from Apple Music Catalog
28  guard let catalogURL = URL(string: "https://api.music.apple.com/v1/me/library/albums/\(albumID)/catalog") else { return }
29
30  let catalogRequest = MusicDataRequest(urlRequest: URLRequest(url: catalogURL))
31  let catalogResponse = try await catalogRequest.response()
32
33  let albums = try JSONDecoder().decode(MusicItemCollection<Album>.self, from: catalogResponse.data)
34
35  /// Get the same album, but with the catalog ID
36  guard let catalogAlbum = albums.first else { return }
37
38  /// Encode the parameters 
39  let data = try JSONEncoder().encode(catalogAlbum.playParameters)
40
41  /// Decode the parameters to `MPMusicPlayerPlayParameters`
42  let playParameters = try JSONDecoder().decode(MPMusicPlayerPlayParameters.self, from: data)
43  
44  // Create the queue
45  let queue = MPMusicPlayerPlayParametersQueueDescriptor(playParametersQueue: [playParameters])
46  
47  let player = MPMusicPlayerController.applicationMusicPlayer
48
49  /// Set the queue
50  player.setQueue(with: queue)
51  try await player.prepareToPlay()
52
53  /// Finally, play the album!
54  player.play()
55} catch {
56  print(error)
57}
58

Source https://stackoverflow.com/questions/70407776

QUESTION

How to convert each row/cell values from a DataFrame to a list of dictionaries in pandas?

Asked 2021-Dec-15 at 23:09

I have a pandas DataFrame below:

1df_input = pd.DataFrame({
2         'Domain':['www.google.com','www.apple.com','www.amazon.com'],
3         'Description':['The company’s product portfolio includes Googl...','Apple is a multinational corporation that desi...','Amazon is an international e-commerce website ...'],
4         'About Us':['Google is a multinational corporation that spe...','Apple is a multinational corporation that desi...','Amazon is an e-commerce website for consumers,...'],
5         'Founded':[1998, 1976, 1994],
6         'Country':['United States','United States','United States']})
7

enter image description here

I want to transfer it as the following:

1df_input = pd.DataFrame({
2         'Domain':['www.google.com','www.apple.com','www.amazon.com'],
3         'Description':['The company’s product portfolio includes Googl...','Apple is a multinational corporation that desi...','Amazon is an international e-commerce website ...'],
4         'About Us':['Google is a multinational corporation that spe...','Apple is a multinational corporation that desi...','Amazon is an e-commerce website for consumers,...'],
5         'Founded':[1998, 1976, 1994],
6         'Country':['United States','United States','United States']})
7[{"properties": [{"name": "Description","value": "The company’s product portfolio includes Google Search, which provides users with access to information online; Knowledge Graph that allows users to search for things, people, or places as well as builds systems recognizing speech and understanding"},
8            {"name": "Domain","value": "www.google.com"},
9            {"name": "About Us", "value": "Google is a multinational corporation that specializes in Internet-related services and products."},
10            {"name": "Founded", "value": 1998},
11            {"name": "Country", "value":"United States"}]},
12
13{"properties": [{"name": "Description","value": "Apple is a multinational corporation that designs, manufactures, and markets mobile communication and media devices, personal computers, portable digital music players, and sells a variety of related software, services, peripherals, networking solutions, and third-party digital content and applications."},
14            {"name": "Domain","value": "www.apple.com"},
15            {"name": "About Us", "value": "Apple is a multinational corporation that designs, manufactures, and markets consumer electronics, personal computers, and software."},
16            {"name": "Founded", "value": 1976},
17            {"name": "Country", "value":"United States"}]},
18
19{"properties": [{"name": "Description","value": "Amazon is an international e-commerce website for consumers, sellers, and content creators. It offers users merchandise and content purchased for resale from vendors and those offered by third-party sellers."},
20            {"name": "Domain","value": "www.amazon.com"},
21            {"name": "About Us", "value": "Amazon is an e-commerce website for consumers, sellers, and content creators."},
22            {"name": "Founded", "value": 1994},
23            {"name": "Country", "value":"United States"}]}]
24

How can I write a loop to do this?

ANSWER

Answered 2021-Dec-15 at 23:09

You just iterate through the rows.

1df_input = pd.DataFrame({
2         'Domain':['www.google.com','www.apple.com','www.amazon.com'],
3         'Description':['The company’s product portfolio includes Googl...','Apple is a multinational corporation that desi...','Amazon is an international e-commerce website ...'],
4         'About Us':['Google is a multinational corporation that spe...','Apple is a multinational corporation that desi...','Amazon is an e-commerce website for consumers,...'],
5         'Founded':[1998, 1976, 1994],
6         'Country':['United States','United States','United States']})
7[{"properties": [{"name": "Description","value": "The company’s product portfolio includes Google Search, which provides users with access to information online; Knowledge Graph that allows users to search for things, people, or places as well as builds systems recognizing speech and understanding"},
8            {"name": "Domain","value": "www.google.com"},
9            {"name": "About Us", "value": "Google is a multinational corporation that specializes in Internet-related services and products."},
10            {"name": "Founded", "value": 1998},
11            {"name": "Country", "value":"United States"}]},
12
13{"properties": [{"name": "Description","value": "Apple is a multinational corporation that designs, manufactures, and markets mobile communication and media devices, personal computers, portable digital music players, and sells a variety of related software, services, peripherals, networking solutions, and third-party digital content and applications."},
14            {"name": "Domain","value": "www.apple.com"},
15            {"name": "About Us", "value": "Apple is a multinational corporation that designs, manufactures, and markets consumer electronics, personal computers, and software."},
16            {"name": "Founded", "value": 1976},
17            {"name": "Country", "value":"United States"}]},
18
19{"properties": [{"name": "Description","value": "Amazon is an international e-commerce website for consumers, sellers, and content creators. It offers users merchandise and content purchased for resale from vendors and those offered by third-party sellers."},
20            {"name": "Domain","value": "www.amazon.com"},
21            {"name": "About Us", "value": "Amazon is an e-commerce website for consumers, sellers, and content creators."},
22            {"name": "Founded", "value": 1994},
23            {"name": "Country", "value":"United States"}]}]
24import pandas as pd
25
26df_input = pd.DataFrame({
27         'Domain':['www.google.com','www.apple.com','www.amazon.com'],
28         'Description':['The companys product portfolio includes Googl...','Apple is a multinational corporation that desi...','Amazon is an international e-commerce website ...'],
29         'About Us':['Google is a multinational corporation that spe...','Apple is a multinational corporation that desi...','Amazon is an e-commerce website for consumers,...'],
30         'Founded':[1998, 1976, 1994],
31         'Country':['United States','United States','United States']})
32
33data = []
34for row in df_input.iterrows():
35    props = []
36    for key,val in zip(df_input.columns, row[1].values ):
37        props.append( {'name':key, 'value':val} )
38    data.append( {'properties': props} )
39from pprint import pprint
40pprint(data)
41

Output:

1df_input = pd.DataFrame({
2         'Domain':['www.google.com','www.apple.com','www.amazon.com'],
3         'Description':['The company’s product portfolio includes Googl...','Apple is a multinational corporation that desi...','Amazon is an international e-commerce website ...'],
4         'About Us':['Google is a multinational corporation that spe...','Apple is a multinational corporation that desi...','Amazon is an e-commerce website for consumers,...'],
5         'Founded':[1998, 1976, 1994],
6         'Country':['United States','United States','United States']})
7[{"properties": [{"name": "Description","value": "The company’s product portfolio includes Google Search, which provides users with access to information online; Knowledge Graph that allows users to search for things, people, or places as well as builds systems recognizing speech and understanding"},
8            {"name": "Domain","value": "www.google.com"},
9            {"name": "About Us", "value": "Google is a multinational corporation that specializes in Internet-related services and products."},
10            {"name": "Founded", "value": 1998},
11            {"name": "Country", "value":"United States"}]},
12
13{"properties": [{"name": "Description","value": "Apple is a multinational corporation that designs, manufactures, and markets mobile communication and media devices, personal computers, portable digital music players, and sells a variety of related software, services, peripherals, networking solutions, and third-party digital content and applications."},
14            {"name": "Domain","value": "www.apple.com"},
15            {"name": "About Us", "value": "Apple is a multinational corporation that designs, manufactures, and markets consumer electronics, personal computers, and software."},
16            {"name": "Founded", "value": 1976},
17            {"name": "Country", "value":"United States"}]},
18
19{"properties": [{"name": "Description","value": "Amazon is an international e-commerce website for consumers, sellers, and content creators. It offers users merchandise and content purchased for resale from vendors and those offered by third-party sellers."},
20            {"name": "Domain","value": "www.amazon.com"},
21            {"name": "About Us", "value": "Amazon is an e-commerce website for consumers, sellers, and content creators."},
22            {"name": "Founded", "value": 1994},
23            {"name": "Country", "value":"United States"}]}]
24import pandas as pd
25
26df_input = pd.DataFrame({
27         'Domain':['www.google.com','www.apple.com','www.amazon.com'],
28         'Description':['The companys product portfolio includes Googl...','Apple is a multinational corporation that desi...','Amazon is an international e-commerce website ...'],
29         'About Us':['Google is a multinational corporation that spe...','Apple is a multinational corporation that desi...','Amazon is an e-commerce website for consumers,...'],
30         'Founded':[1998, 1976, 1994],
31         'Country':['United States','United States','United States']})
32
33data = []
34for row in df_input.iterrows():
35    props = []
36    for key,val in zip(df_input.columns, row[1].values ):
37        props.append( {'name':key, 'value':val} )
38    data.append( {'properties': props} )
39from pprint import pprint
40pprint(data)
41[{'properties': [{'name': 'Domain', 'value': 'www.google.com'},
42                 {'name': 'Description',
43                  'value': 'The companys product portfolio includes Googl...'},
44                 {'name': 'About Us',
45                  'value': 'Google is a multinational corporation that spe...'},
46                 {'name': 'Founded', 'value': 1998},
47                 {'name': 'Country', 'value': 'United States'}]},
48 {'properties': [{'name': 'Domain', 'value': 'www.apple.com'},
49                 {'name': 'Description',
50                  'value': 'Apple is a multinational corporation that desi...'},
51                 {'name': 'About Us',
52                  'value': 'Apple is a multinational corporation that desi...'},
53                 {'name': 'Founded', 'value': 1976},
54                 {'name': 'Country', 'value': 'United States'}]},
55 {'properties': [{'name': 'Domain', 'value': 'www.amazon.com'},
56                 {'name': 'Description',
57                  'value': 'Amazon is an international e-commerce website ...'},
58                 {'name': 'About Us',
59                  'value': 'Amazon is an e-commerce website for consumers,...'},
60                 {'name': 'Founded', 'value': 1994},
61                 {'name': 'Country', 'value': 'United States'}]}]
62

Source https://stackoverflow.com/questions/70371264

QUESTION

Tkinter animation goes faster and faster

Asked 2021-Dec-01 at 22:02

On my tkinter music player project , where I am working with a marquee label.

To that i use a function named marquee.

So when i run my script, marquee speed is normal. After i advance to next song it speeds up and so on.

I cannot figure how to stop it from speeding. Iam playing my animation about 30fps

Can anybody suggest any method ?

1def marquee(song_name,fs) :
2    global canvas,fps
3    fps = fs
4    canvas=Canvas(Frame1)
5    canvas.grid(row=1)
6    text_var= song_name
7    text=canvas.create_text(0,-2000,text=text_var,font=('calibri',20,'bold'),fill='black',tags=("marquee",),anchor='w')
8    x1,y1,x2,y2 = canvas.bbox("marquee")
9    width = x2-x1
10    height = y2-y1
11    canvas['width']='440'
12    canvas['height']=height
13    shift()
14
15def shift():
16    global canvas,fps
17
18    x1,y1,x2,y2 = canvas.bbox("marquee")
19    if(x2<0 or y1<0): 
20        x1 = canvas.winfo_width()
21        y1 = canvas.winfo_height()//2
22        canvas.coords("marquee",x1,y1)
23    else:
24        canvas.move("marquee", -2, 0)
25    canvas.after(1000//fps,shift)
26

ANSWER

Answered 2021-Dec-01 at 22:02

The problem is that each time you call marquee you are starting a new loop. So, the first loop moves the marquee by -2 pixels each frame. The next time you call marquee it starts another loop, also moving the text by -2 pixels each frame. So now the text moves -4 pixels each frame. And so on.

There are a couple of ways to solve this. One is to keep track of the id of the call to after, and cancel it before starting a new loop. That will terminate the old loop and start a new loop.

The second solution is to only call marquee a single time to start a single loop that runs for the life of the program. Whenever a song changes, instead of creating a new marquee with a new loop you just update the existing marquee with the new song title.

The second solution is what I recommend. Since you're adding a unique tag to the marquee text, you can use that tag to change the text. You just need a new function for changing the text.

For example:

1def marquee(song_name,fs) :
2    global canvas,fps
3    fps = fs
4    canvas=Canvas(Frame1)
5    canvas.grid(row=1)
6    text_var= song_name
7    text=canvas.create_text(0,-2000,text=text_var,font=('calibri',20,'bold'),fill='black',tags=("marquee",),anchor='w')
8    x1,y1,x2,y2 = canvas.bbox("marquee")
9    width = x2-x1
10    height = y2-y1
11    canvas['width']='440'
12    canvas['height']=height
13    shift()
14
15def shift():
16    global canvas,fps
17
18    x1,y1,x2,y2 = canvas.bbox("marquee")
19    if(x2<0 or y1<0): 
20        x1 = canvas.winfo_width()
21        y1 = canvas.winfo_height()//2
22        canvas.coords("marquee",x1,y1)
23    else:
24        canvas.move("marquee", -2, 0)
25    canvas.after(1000//fps,shift)
26def new_song(song_title):
27    canvas.itemconfigure("marquee", text=song_title)
28

With that, you just need to call new_song instead of marquee each time the song changes.

1def marquee(song_name,fs) :
2    global canvas,fps
3    fps = fs
4    canvas=Canvas(Frame1)
5    canvas.grid(row=1)
6    text_var= song_name
7    text=canvas.create_text(0,-2000,text=text_var,font=('calibri',20,'bold'),fill='black',tags=("marquee",),anchor='w')
8    x1,y1,x2,y2 = canvas.bbox("marquee")
9    width = x2-x1
10    height = y2-y1
11    canvas['width']='440'
12    canvas['height']=height
13    shift()
14
15def shift():
16    global canvas,fps
17
18    x1,y1,x2,y2 = canvas.bbox("marquee")
19    if(x2<0 or y1<0): 
20        x1 = canvas.winfo_width()
21        y1 = canvas.winfo_height()//2
22        canvas.coords("marquee",x1,y1)
23    else:
24        canvas.move("marquee", -2, 0)
25    canvas.after(1000//fps,shift)
26def new_song(song_title):
27    canvas.itemconfigure("marquee", text=song_title)
28new_song("This is a new song")
29

Source https://stackoverflow.com/questions/70188393

QUESTION

how to make a loop for a play/pause button using javascript/jquery

Asked 2021-Nov-30 at 09:56

so i have been trying to make a music player website and i`m stuck at trying to loop the play/pause script, i kept trying but i reached nothing this is the javascript that i have been using, it does work for the first song but not the others

1<pre>
2var mySong = document.getElementById("mySong");
3var icon = document.getElementById("icon");
4icon.onclick = function () {
5  if (mySong.paused) {
6    mySong.play();
7    icon.src = "/images/pause.png";
8  } else {
9    mySong.pause();
10    icon.src = "/images/play.png";
11  }
12};
13</pre>
14

and here is the html part that i`m trying to loop

1<pre>
2var mySong = document.getElementById("mySong");
3var icon = document.getElementById("icon");
4icon.onclick = function () {
5  if (mySong.paused) {
6    mySong.play();
7    icon.src = "/images/pause.png";
8  } else {
9    mySong.pause();
10    icon.src = "/images/play.png";
11  }
12};
13</pre>
14<pre>
15<div class="music-box">
16          <div class="music-info">
17            <div class="music-img">
18              <img src="images/Filosofem.jpg" alt="" />
19            </div>
20            <div class="music-name">
21              <h6>Single Song Title</h6>
22              <audio id="mySong">
23                <source src="/music/b.mp3" type="audio/mp3" />
24              </audio>
25              <p>Single name and music director</p>
26            </div>
27            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
28          </div>
29          <hr />
30          <div class="music-info">
31            <div class="music-img">
32              <img src="images/Filosofem.jpg" alt="" />
33            </div>
34            <div class="music-name">
35              <h6>Single Song Title</h6>
36              <audio id="mySong">
37                <source src="/music/a.mp3" type="audio/mp3" />
38              </audio>
39              <p>Single name and music director</p>
40            </div>
41            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
42          </div>
43          <hr />
44          <div class="music-info">
45            <div class="music-img">
46              <img src="images/Filosofem.jpg" alt="" />
47            </div>
48            <div class="music-name">
49              <h6>Single Song Title</h6>
50              <audio id="mySong">
51                <source src="/music/b.mp3" type="audio/mp3" />
52              </audio>
53              <p>Single name and music director</p>
54            </div>
55            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
56          </div>
57          <hr />
58          <div class="music-info">
59            <div class="music-img">
60              <img src="images/Filosofem.jpg" alt="" />
61            </div>
62            <div class="music-name">
63              <h6>Single Song Title</h6>
64              <audio id="mySong">
65                <source src="/music/b.mp3" type="audio/mp3" />
66              </audio>
67              <p>Single name and music director</p>
68            </div>
69            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
70          </div>
71          <hr />
72          <div class="music-info">
73            <div class="music-img">
74              <img src="images/Filosofem.jpg" alt="" />
75            </div>
76            <div class="music-name">
77              <h6>Single Song Title</h6>
78              <audio id="mySong">
79                <source src="/music/b.mp3" type="audio/mp3" />
80              </audio>
81              <p>Single name and music director</p>
82            </div>
83            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
84          </div>
85          <hr />
86          <div class="music-info">
87            <div class="music-img">
88              <img src="images/Filosofem.jpg" alt="" />
89            </div>
90            <div class="music-name">
91              <h6>Single Song Title</h6>
92              <audio id="mySong">
93                <source src="/music/b.mp3" type="audio/mp3" />
94              </audio>
95              <p>Single name and music director</p>
96            </div>
97            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
98          </div>
99          <hr />
100          <div class="music-info">
101            <div class="music-img">
102              <img src="images/Filosofem.jpg" alt="" />
103            </div>
104            <div class="music-name">
105              <h6>Single Song Title</h6>
106              <audio id="mySong">
107                <source src="/music/b.mp3" type="audio/mp3" />
108              </audio>
109              <p>Single name and music director</p>
110            </div>
111            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
112          </div>
113          <hr />
114          <div class="music-info">
115            <div class="music-img">
116              <img src="images/Filosofem.jpg" alt="" />
117            </div>
118            <div class="music-name">
119              <h6>Single Song Title</h6>
120              <audio id="mySong">
121                <source src="/music/b.mp3" type="audio/mp3" />
122              </audio>
123              <p>Single name and music director</p>
124            </div>
125            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
126          </div>
127          <hr />
128          <div class="music-info">
129            <div class="music-img">
130              <img src="images/Filosofem.jpg" alt="" />
131            </div>
132            <div class="music-name">
133              <h6>Single Song Title</h6>
134              <audio id="mySong">
135                <source src="/music/b.mp3" type="audio/mp3" />
136              </audio>
137              <p>Single name and music director</p>
138            </div>
139            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
140          </div>
141          <hr />
142          <div class="music-info">
143            <div class="music-img">
144              <img src="images/Filosofem.jpg" alt="" />
145            </div>
146            <div class="music-name">
147              <h6>Single Song Title</h6>
148              <audio id="mySong">
149                <source src="/music/b.mp3" type="audio/mp3" />
150              </audio>
151              <p>Single name and music director</p>
152            </div>
153            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
154          </div>
155          <hr />
156          <div class="music-info">
157            <div class="music-img">
158              <img src="images/Filosofem.jpg" alt="" />
159            </div>
160            <div class="music-name">
161              <h6>Single Song Title</h6>
162              <audio id="mySong">
163                <source src="/music/b.mp3" type="audio/mp3" />
164              </audio>
165              <p>Single name and music director</p>
166            </div>
167            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
168          </div>
169          <hr />
170          <div class="music-info">
171            <div class="music-img">
172              <img src="images/Filosofem.jpg" alt="" />
173            </div>
174            <div class="music-name">
175              <h6>Single Song Title</h6>
176              <audio id="mySong">
177                <source src="/music/b.mp3" type="audio/mp3" />
178              </audio>
179              <p>Single name and music director</p>
180            </div>
181            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
182          </div>
183        </div>
184      </div>
185      <div class="music-play">
186        <div class="play-image">
187          <img src="images/Filosofem.jpg" alt="" />
188        </div>
189        <div class="play-controls">
190          <div class="controls">
191            <div class="song-name">
192              <h5>Dunkelheit</h5>
193              <p>Burzum</p>
194            </div>
195            <div class="play-icon">
196              <i class="fa fa-step-backward"> </i>
197              <i class="fa fa-play"> </i>
198              <i class="fa fa-step-forward"> </i>
199            </div>
200          </div>
201          <div class="music-progress">
202            <div class="progress">
203              <div class="progress-bar"></div>
204            </div>
205          </div>
206        </div>
207      </div>
208    </div>
209</pre>
210

this is my first time using stackoverflow so sorry for my poor documentation,hope you can provide me with solutions or tutorials as this is my first month of learning Front-end. p.s:- sorry for my poor english as i`m not a native speaker.

ANSWER

Answered 2021-Nov-29 at 14:19

I think the problem you have is that you created a EventHandler with jQuery and it looks for some element which have the id of "icon". But it is not how HTML works. You have more than one element having same id. It's incorrect.

The correct way of doing this is creating the EventHandler with class of "icon" NOT id of "icon". When the handler is triggered, you should change the "src" attribute of this element.


After I runned your HTML and JS I realized that you used Object.onclick attribute on your script to trig the function which changes the src attribute. You could not achieved what you wanted because you are trying to DOM your element with id's. Firstly, convert all id's to class. And then you should do something like below to set all of the image's onclick attributes to your function. You can not do it on collection of elements. You can do it one-by-one with for loop. (You better use jQuery for this but since you are new to JS, try this usage and see what happens.)

1<pre>
2var mySong = document.getElementById("mySong");
3var icon = document.getElementById("icon");
4icon.onclick = function () {
5  if (mySong.paused) {
6    mySong.play();
7    icon.src = "/images/pause.png";
8  } else {
9    mySong.pause();
10    icon.src = "/images/play.png";
11  }
12};
13</pre>
14<pre>
15<div class="music-box">
16          <div class="music-info">
17            <div class="music-img">
18              <img src="images/Filosofem.jpg" alt="" />
19            </div>
20            <div class="music-name">
21              <h6>Single Song Title</h6>
22              <audio id="mySong">
23                <source src="/music/b.mp3" type="audio/mp3" />
24              </audio>
25              <p>Single name and music director</p>
26            </div>
27            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
28          </div>
29          <hr />
30          <div class="music-info">
31            <div class="music-img">
32              <img src="images/Filosofem.jpg" alt="" />
33            </div>
34            <div class="music-name">
35              <h6>Single Song Title</h6>
36              <audio id="mySong">
37                <source src="/music/a.mp3" type="audio/mp3" />
38              </audio>
39              <p>Single name and music director</p>
40            </div>
41            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
42          </div>
43          <hr />
44          <div class="music-info">
45            <div class="music-img">
46              <img src="images/Filosofem.jpg" alt="" />
47            </div>
48            <div class="music-name">
49              <h6>Single Song Title</h6>
50              <audio id="mySong">
51                <source src="/music/b.mp3" type="audio/mp3" />
52              </audio>
53              <p>Single name and music director</p>
54            </div>
55            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
56          </div>
57          <hr />
58          <div class="music-info">
59            <div class="music-img">
60              <img src="images/Filosofem.jpg" alt="" />
61            </div>
62            <div class="music-name">
63              <h6>Single Song Title</h6>
64              <audio id="mySong">
65                <source src="/music/b.mp3" type="audio/mp3" />
66              </audio>
67              <p>Single name and music director</p>
68            </div>
69            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
70          </div>
71          <hr />
72          <div class="music-info">
73            <div class="music-img">
74              <img src="images/Filosofem.jpg" alt="" />
75            </div>
76            <div class="music-name">
77              <h6>Single Song Title</h6>
78              <audio id="mySong">
79                <source src="/music/b.mp3" type="audio/mp3" />
80              </audio>
81              <p>Single name and music director</p>
82            </div>
83            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
84          </div>
85          <hr />
86          <div class="music-info">
87            <div class="music-img">
88              <img src="images/Filosofem.jpg" alt="" />
89            </div>
90            <div class="music-name">
91              <h6>Single Song Title</h6>
92              <audio id="mySong">
93                <source src="/music/b.mp3" type="audio/mp3" />
94              </audio>
95              <p>Single name and music director</p>
96            </div>
97            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
98          </div>
99          <hr />
100          <div class="music-info">
101            <div class="music-img">
102              <img src="images/Filosofem.jpg" alt="" />
103            </div>
104            <div class="music-name">
105              <h6>Single Song Title</h6>
106              <audio id="mySong">
107                <source src="/music/b.mp3" type="audio/mp3" />
108              </audio>
109              <p>Single name and music director</p>
110            </div>
111            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
112          </div>
113          <hr />
114          <div class="music-info">
115            <div class="music-img">
116              <img src="images/Filosofem.jpg" alt="" />
117            </div>
118            <div class="music-name">
119              <h6>Single Song Title</h6>
120              <audio id="mySong">
121                <source src="/music/b.mp3" type="audio/mp3" />
122              </audio>
123              <p>Single name and music director</p>
124            </div>
125            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
126          </div>
127          <hr />
128          <div class="music-info">
129            <div class="music-img">
130              <img src="images/Filosofem.jpg" alt="" />
131            </div>
132            <div class="music-name">
133              <h6>Single Song Title</h6>
134              <audio id="mySong">
135                <source src="/music/b.mp3" type="audio/mp3" />
136              </audio>
137              <p>Single name and music director</p>
138            </div>
139            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
140          </div>
141          <hr />
142          <div class="music-info">
143            <div class="music-img">
144              <img src="images/Filosofem.jpg" alt="" />
145            </div>
146            <div class="music-name">
147              <h6>Single Song Title</h6>
148              <audio id="mySong">
149                <source src="/music/b.mp3" type="audio/mp3" />
150              </audio>
151              <p>Single name and music director</p>
152            </div>
153            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
154          </div>
155          <hr />
156          <div class="music-info">
157            <div class="music-img">
158              <img src="images/Filosofem.jpg" alt="" />
159            </div>
160            <div class="music-name">
161              <h6>Single Song Title</h6>
162              <audio id="mySong">
163                <source src="/music/b.mp3" type="audio/mp3" />
164              </audio>
165              <p>Single name and music director</p>
166            </div>
167            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
168          </div>
169          <hr />
170          <div class="music-info">
171            <div class="music-img">
172              <img src="images/Filosofem.jpg" alt="" />
173            </div>
174            <div class="music-name">
175              <h6>Single Song Title</h6>
176              <audio id="mySong">
177                <source src="/music/b.mp3" type="audio/mp3" />
178              </audio>
179              <p>Single name and music director</p>
180            </div>
181            <img src="/images/play.png" id="icon" style="padding-right: 20px" />
182          </div>
183        </div>
184      </div>
185      <div class="music-play">
186        <div class="play-image">
187          <img src="images/Filosofem.jpg" alt="" />
188        </div>
189        <div class="play-controls">
190          <div class="controls">
191            <div class="song-name">
192              <h5>Dunkelheit</h5>
193              <p>Burzum</p>
194            </div>
195            <div class="play-icon">
196              <i class="fa fa-step-backward"> </i>
197              <i class="fa fa-play"> </i>
198              <i class="fa fa-step-forward"> </i>
199            </div>
200          </div>
201          <div class="music-progress">
202            <div class="progress">
203              <div class="progress-bar"></div>
204            </div>
205          </div>
206        </div>
207      </div>
208    </div>
209</pre>
210var mySong = document.getElementById("mySong");
211var icons = document.getElementsByClassName("icon");
212
213var clickFunction = function () {
214  alert("kkk");
215  if (mySong.paused) {
216    mySong.play();
217    icon.src = "/images/pause.png";
218  } else {
219    mySong.pause();
220    icon.src = "/images/play.png";
221  }
222};
223
224
225for (var i=0; i < icons.length; i++) {
226    icons[i].onclick = clickFunction;
227};
228

Source https://stackoverflow.com/questions/70155774

QUESTION

Using Eel calling JavaScript function in python only when a condition is True

Asked 2021-Oct-27 at 08:29

Describe the problem I am trying to call a JavaScript function but only when a if condition evaluates to True in Python. I'm working on a Music player project with Pygame and Eel, I want to call the JS function to change Song cover image automatically without a button click as the previous song ends, which am finding using pygame.mixer.music.get_busy() in python, during when I want to call the 'eel.fine()' but I'm sure why it's not working or how to get this done as am new to Eel

Expected When if condition becomes True function find should be called from python code i.e just want to change cover image when one song ends Code snippet(s) Here is some code that can be easily used to reproduce the problem or understand what I need help with. Note: I have removed most part of the code just to make to understand and have only added the portions that relate to the flow of the code what I need help with.

1import eel
2from pygame import mixer
3
4eel.init('web')
5
6
7js='function $fine(){document.getElementById("spl").live("click");}'
8def my_update():
9    if pausev and not fine:
10        if not start and not mixer.music.get_busy():
11            #ok=js2py.eval_js(js)
12            # ok()
13            print("booom")
14            eel.fine()  # This is the part I need help with
15            play()
16            print('new song up')
17        else:
18            print('old playing still')
19    else:
20        print('strictly paused')
21
22
23
1import eel
2from pygame import mixer
3
4eel.init('web')
5
6
7js='function $fine(){document.getElementById("spl").live("click");}'
8def my_update():
9    if pausev and not fine:
10        if not start and not mixer.music.get_busy():
11            #ok=js2py.eval_js(js)
12            # ok()
13            print("booom")
14            eel.fine()  # This is the part I need help with
15            play()
16            print('new song up')
17        else:
18            print('old playing still')
19    else:
20        print('strictly paused')
21
22
23<!DOCTYPE html>
24<html lang="en">
25
26<head>
27    <meta charset="UTF-8">
28    <meta name="description" content="">
29    <meta http-equiv="X-UA-Compatible" content="IE=edge">
30    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
31    <title>Aishu's Magic-Music</title>
32    <link href="style.css" rel="stylesheet">
33    <script type="text/javascript" src="/eel.js"></script>
34    <script type="text/javascript" src="main.js"></script>
35    <script type="text/javascript">
36        eel.expose(fine);
37      function fine(){
38      document.getElementById("spl").live("click");
39
40      }
41    </script>
42    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js" type="text/javascript"></script>
43    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
44    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
45</head>
46
47<body>
48    <section class="wellcome_area clearfix" id="home">
49      <div class="container h-100">
50            <div class="row h-100 align-items-center">
51                <div class="col-12 col-md">
52                    <div class="get-start-area">
53                        <form class="form-inline">
54                            <input type="button" id="repeat" class="submit" value="▶ Shower" onclick="generateQRCode(7)">
55                            <input type="button" id="spl" class="submit" value="▶ Play" onclick="generateQRCode(2)">
56                            <input type="button" class="submit" value=">> Skip" onclick="generateQRCode(3)">
57                        </form>
58                    </div>
59                </div>
60            </div>
61        </div>
62        <div class="welcome-thumb ">
63            <img id="qr" class="headshot headshot-1" src="img/bg-img/play.jpg" width="50%">
64        </div>
65    </section>
66
67</body>
68</html>
69
70
1import eel
2from pygame import mixer
3
4eel.init('web')
5
6
7js='function $fine(){document.getElementById("spl").live("click");}'
8def my_update():
9    if pausev and not fine:
10        if not start and not mixer.music.get_busy():
11            #ok=js2py.eval_js(js)
12            # ok()
13            print("booom")
14            eel.fine()  # This is the part I need help with
15            play()
16            print('new song up')
17        else:
18            print('old playing still')
19    else:
20        print('strictly paused')
21
22
23<!DOCTYPE html>
24<html lang="en">
25
26<head>
27    <meta charset="UTF-8">
28    <meta name="description" content="">
29    <meta http-equiv="X-UA-Compatible" content="IE=edge">
30    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
31    <title>Aishu's Magic-Music</title>
32    <link href="style.css" rel="stylesheet">
33    <script type="text/javascript" src="/eel.js"></script>
34    <script type="text/javascript" src="main.js"></script>
35    <script type="text/javascript">
36        eel.expose(fine);
37      function fine(){
38      document.getElementById("spl").live("click");
39
40      }
41    </script>
42    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js" type="text/javascript"></script>
43    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
44    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
45</head>
46
47<body>
48    <section class="wellcome_area clearfix" id="home">
49      <div class="container h-100">
50            <div class="row h-100 align-items-center">
51                <div class="col-12 col-md">
52                    <div class="get-start-area">
53                        <form class="form-inline">
54                            <input type="button" id="repeat" class="submit" value="▶ Shower" onclick="generateQRCode(7)">
55                            <input type="button" id="spl" class="submit" value="▶ Play" onclick="generateQRCode(2)">
56                            <input type="button" class="submit" value=">> Skip" onclick="generateQRCode(3)">
57                        </form>
58                    </div>
59                </div>
60            </div>
61        </div>
62        <div class="welcome-thumb ">
63            <img id="qr" class="headshot headshot-1" src="img/bg-img/play.jpg" width="50%">
64        </div>
65    </section>
66
67</body>
68</html>
69
70// main.js
71var whatever=1;
72var loop_check=1;
73function generateQRCode(data) {
74    if(data==2){
75    change()
76     if(whatever==1){
77        eel.generate_qr(1)(setImage);
78        whatever=0;
79    }
80    else
81    {
82        eel.generate_qr(data)(setImage)
83
84    }
85    }
86    else if(data==7){
87    change_loop()
88    eel.generate_qr(data)(setImage)
89    }
90    else{
91    eel.generate_qr(data)(setImage)
92    }
93}
94function change() 
95{
96    var elem = document.getElementById("spl");
97    if (elem.value=="|| Pause") elem.value = "▶ Play";
98    else elem.value = "|| Pause";
99
100}
101function setImage(base64) {
102    document.getElementById("qr").src = base64
103}
104

UPDATE It partially works and does not work as expected image is the Error that I get during running normally

Whereas the Output when I open inspect - console image

Desktop :

  • OS: Windows
  • Browser chrome
  • Version 94

ANSWER

Answered 2021-Oct-27 at 08:29

I've solved it after lots of trail and error, since I'm new to JavaScript, Eel and connecting both with Python, I only later realised that in my code, I have tried using

1import eel
2from pygame import mixer
3
4eel.init('web')
5
6
7js='function $fine(){document.getElementById("spl").live("click");}'
8def my_update():
9    if pausev and not fine:
10        if not start and not mixer.music.get_busy():
11            #ok=js2py.eval_js(js)
12            # ok()
13            print("booom")
14            eel.fine()  # This is the part I need help with
15            play()
16            print('new song up')
17        else:
18            print('old playing still')
19    else:
20        print('strictly paused')
21
22
23<!DOCTYPE html>
24<html lang="en">
25
26<head>
27    <meta charset="UTF-8">
28    <meta name="description" content="">
29    <meta http-equiv="X-UA-Compatible" content="IE=edge">
30    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
31    <title>Aishu's Magic-Music</title>
32    <link href="style.css" rel="stylesheet">
33    <script type="text/javascript" src="/eel.js"></script>
34    <script type="text/javascript" src="main.js"></script>
35    <script type="text/javascript">
36        eel.expose(fine);
37      function fine(){
38      document.getElementById("spl").live("click");
39
40      }
41    </script>
42    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js" type="text/javascript"></script>
43    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
44    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
45</head>
46
47<body>
48    <section class="wellcome_area clearfix" id="home">
49      <div class="container h-100">
50            <div class="row h-100 align-items-center">
51                <div class="col-12 col-md">
52                    <div class="get-start-area">
53                        <form class="form-inline">
54                            <input type="button" id="repeat" class="submit" value="▶ Shower" onclick="generateQRCode(7)">
55                            <input type="button" id="spl" class="submit" value="▶ Play" onclick="generateQRCode(2)">
56                            <input type="button" class="submit" value=">> Skip" onclick="generateQRCode(3)">
57                        </form>
58                    </div>
59                </div>
60            </div>
61        </div>
62        <div class="welcome-thumb ">
63            <img id="qr" class="headshot headshot-1" src="img/bg-img/play.jpg" width="50%">
64        </div>
65    </section>
66
67</body>
68</html>
69
70// main.js
71var whatever=1;
72var loop_check=1;
73function generateQRCode(data) {
74    if(data==2){
75    change()
76     if(whatever==1){
77        eel.generate_qr(1)(setImage);
78        whatever=0;
79    }
80    else
81    {
82        eel.generate_qr(data)(setImage)
83
84    }
85    }
86    else if(data==7){
87    change_loop()
88    eel.generate_qr(data)(setImage)
89    }
90    else{
91    eel.generate_qr(data)(setImage)
92    }
93}
94function change() 
95{
96    var elem = document.getElementById("spl");
97    if (elem.value=="|| Pause") elem.value = "▶ Play";
98    else elem.value = "|| Pause";
99
100}
101function setImage(base64) {
102    document.getElementById("qr").src = base64
103}
104document.getElementById("spl").live("click");
105

and

1import eel
2from pygame import mixer
3
4eel.init('web')
5
6
7js='function $fine(){document.getElementById("spl").live("click");}'
8def my_update():
9    if pausev and not fine:
10        if not start and not mixer.music.get_busy():
11            #ok=js2py.eval_js(js)
12            # ok()
13            print("booom")
14            eel.fine()  # This is the part I need help with
15            play()
16            print('new song up')
17        else:
18            print('old playing still')
19    else:
20        print('strictly paused')
21
22
23<!DOCTYPE html>
24<html lang="en">
25
26<head>
27    <meta charset="UTF-8">
28    <meta name="description" content="">
29    <meta http-equiv="X-UA-Compatible" content="IE=edge">
30    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
31    <title>Aishu's Magic-Music</title>
32    <link href="style.css" rel="stylesheet">
33    <script type="text/javascript" src="/eel.js"></script>
34    <script type="text/javascript" src="main.js"></script>
35    <script type="text/javascript">
36        eel.expose(fine);
37      function fine(){
38      document.getElementById("spl").live("click");
39
40      }
41    </script>
42    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js" type="text/javascript"></script>
43    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
44    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
45</head>
46
47<body>
48    <section class="wellcome_area clearfix" id="home">
49      <div class="container h-100">
50            <div class="row h-100 align-items-center">
51                <div class="col-12 col-md">
52                    <div class="get-start-area">
53                        <form class="form-inline">
54                            <input type="button" id="repeat" class="submit" value="▶ Shower" onclick="generateQRCode(7)">
55                            <input type="button" id="spl" class="submit" value="▶ Play" onclick="generateQRCode(2)">
56                            <input type="button" class="submit" value=">> Skip" onclick="generateQRCode(3)">
57                        </form>
58                    </div>
59                </div>
60            </div>
61        </div>
62        <div class="welcome-thumb ">
63            <img id="qr" class="headshot headshot-1" src="img/bg-img/play.jpg" width="50%">
64        </div>
65    </section>
66
67</body>
68</html>
69
70// main.js
71var whatever=1;
72var loop_check=1;
73function generateQRCode(data) {
74    if(data==2){
75    change()
76     if(whatever==1){
77        eel.generate_qr(1)(setImage);
78        whatever=0;
79    }
80    else
81    {
82        eel.generate_qr(data)(setImage)
83
84    }
85    }
86    else if(data==7){
87    change_loop()
88    eel.generate_qr(data)(setImage)
89    }
90    else{
91    eel.generate_qr(data)(setImage)
92    }
93}
94function change() 
95{
96    var elem = document.getElementById("spl");
97    if (elem.value=="|| Pause") elem.value = "▶ Play";
98    else elem.value = "|| Pause";
99
100}
101function setImage(base64) {
102    document.getElementById("qr").src = base64
103}
104document.getElementById("spl").live("click");
105document.getElementById("spl").trigger("click");
106

and while I used

1import eel
2from pygame import mixer
3
4eel.init('web')
5
6
7js='function $fine(){document.getElementById("spl").live("click");}'
8def my_update():
9    if pausev and not fine:
10        if not start and not mixer.music.get_busy():
11            #ok=js2py.eval_js(js)
12            # ok()
13            print("booom")
14            eel.fine()  # This is the part I need help with
15            play()
16            print('new song up')
17        else:
18            print('old playing still')
19    else:
20        print('strictly paused')
21
22
23<!DOCTYPE html>
24<html lang="en">
25
26<head>
27    <meta charset="UTF-8">
28    <meta name="description" content="">
29    <meta http-equiv="X-UA-Compatible" content="IE=edge">
30    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
31    <title>Aishu's Magic-Music</title>
32    <link href="style.css" rel="stylesheet">
33    <script type="text/javascript" src="/eel.js"></script>
34    <script type="text/javascript" src="main.js"></script>
35    <script type="text/javascript">
36        eel.expose(fine);
37      function fine(){
38      document.getElementById("spl").live("click");
39
40      }
41    </script>
42    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js" type="text/javascript"></script>
43    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
44    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
45</head>
46
47<body>
48    <section class="wellcome_area clearfix" id="home">
49      <div class="container h-100">
50            <div class="row h-100 align-items-center">
51                <div class="col-12 col-md">
52                    <div class="get-start-area">
53                        <form class="form-inline">
54                            <input type="button" id="repeat" class="submit" value="▶ Shower" onclick="generateQRCode(7)">
55                            <input type="button" id="spl" class="submit" value="▶ Play" onclick="generateQRCode(2)">
56                            <input type="button" class="submit" value=">> Skip" onclick="generateQRCode(3)">
57                        </form>
58                    </div>
59                </div>
60            </div>
61        </div>
62        <div class="welcome-thumb ">
63            <img id="qr" class="headshot headshot-1" src="img/bg-img/play.jpg" width="50%">
64        </div>
65    </section>
66
67</body>
68</html>
69
70// main.js
71var whatever=1;
72var loop_check=1;
73function generateQRCode(data) {
74    if(data==2){
75    change()
76     if(whatever==1){
77        eel.generate_qr(1)(setImage);
78        whatever=0;
79    }
80    else
81    {
82        eel.generate_qr(data)(setImage)
83
84    }
85    }
86    else if(data==7){
87    change_loop()
88    eel.generate_qr(data)(setImage)
89    }
90    else{
91    eel.generate_qr(data)(setImage)
92    }
93}
94function change() 
95{
96    var elem = document.getElementById("spl");
97    if (elem.value=="|| Pause") elem.value = "▶ Play";
98    else elem.value = "|| Pause";
99
100}
101function setImage(base64) {
102    document.getElementById("qr").src = base64
103}
104document.getElementById("spl").live("click");
105document.getElementById("spl").trigger("click");
106document.getElementById("spl").click();
107

earlier had missed to expose the JavaScript function, hence when I tried using .click() again after exposing I realise this is what I've been missing the whole time. Although in JavaScript without Eel, as stated here and here works more or less the same, but for some reason when used with Eel creates this weird pausing thing to cause in debugger only and create a websocket error if not.

Glad that I was finally able to find a way that actually works.

Source https://stackoverflow.com/questions/69732918

QUESTION

Icon not aligning in the center of FloatingActionButton

Asked 2021-Oct-20 at 06:51

I am designing this activity for my Music Player App. I have three Floating Action Buttons to perform the Play, Next and Previous actions.

However, I want the Next and Previous buttons to be slightly smaller then the Play button. To do this I adjusted the height and width of both buttons in this activity's xml file.

1<!-- Prev. Button -->
2<com.google.android.material.floatingactionbutton.FloatingActionButton
3    android:layout_width="45dp"
4    android:layout_height="45dp"
5    android:id="@+id/id_prev"
6    android:layout_centerVertical="true"
7    android:layout_marginEnd="22dp"
8    android:layout_toStartOf="@+id/play_pause"
9    android:src="@drawable/ic_skip_previous"/>    
10
11<!-- Play. Button -->
12<com.google.android.material.floatingactionbutton.FloatingActionButton
13    android:layout_width="wrap_content"
14    android:layout_height="wrap_content"
15    android:layout_centerHorizontal="true"
16    android:layout_centerVertical="true"
17    android:focusable="true"
18    android:clickable="true"
19    android:id="@+id/play_pause"
20    android:src="@drawable/ic_play"/>
21
22<!-- Next. Button -->
23<com.google.android.material.floatingactionbutton.FloatingActionButton
24    android:id="@+id/id_next"
25    android:layout_width="45dp"
26    android:layout_height="45dp"
27    android:layout_centerHorizontal="true"
28    android:layout_centerVertical="true"
29    android:layout_marginStart="22dp"
30    android:layout_toEndOf="@+id/play_pause"
31    android:clickable="true"
32    android:focusable="true"
33    android:src="@drawable/ic_skip_next" /> 
34

The problem I am facing is that every time I change the height and width of the floating action buttons to 45dp or any other size, the icons inside the buttons get pushed down to the bottom-right corner. This next image shows what I'm talking about.

How do I get the Next and Prev icons inside the floating action buttons to stay perfectly in the center and still maintain the size of both buttons at 45dp?

ANSWER

Answered 2021-Oct-19 at 14:20

You should add fabSize="mini" attribute instead of setting 45dp to layout_width and layout_height other than wrap_content.

1<!-- Prev. Button -->
2<com.google.android.material.floatingactionbutton.FloatingActionButton
3    android:layout_width="45dp"
4    android:layout_height="45dp"
5    android:id="@+id/id_prev"
6    android:layout_centerVertical="true"
7    android:layout_marginEnd="22dp"
8    android:layout_toStartOf="@+id/play_pause"
9    android:src="@drawable/ic_skip_previous"/>    
10
11<!-- Play. Button -->
12<com.google.android.material.floatingactionbutton.FloatingActionButton
13    android:layout_width="wrap_content"
14    android:layout_height="wrap_content"
15    android:layout_centerHorizontal="true"
16    android:layout_centerVertical="true"
17    android:focusable="true"
18    android:clickable="true"
19    android:id="@+id/play_pause"
20    android:src="@drawable/ic_play"/>
21
22<!-- Next. Button -->
23<com.google.android.material.floatingactionbutton.FloatingActionButton
24    android:id="@+id/id_next"
25    android:layout_width="45dp"
26    android:layout_height="45dp"
27    android:layout_centerHorizontal="true"
28    android:layout_centerVertical="true"
29    android:layout_marginStart="22dp"
30    android:layout_toEndOf="@+id/play_pause"
31    android:clickable="true"
32    android:focusable="true"
33    android:src="@drawable/ic_skip_next" /> 
34<!-- Prev. Button -->
35<com.google.android.material.floatingactionbutton.FloatingActionButton
36    android:layout_width="wrap_content"
37    android:layout_height="wrap_content"
38    android:id="@+id/id_prev"
39    android:layout_centerVertical="true"
40    android:layout_marginEnd="22dp"
41    android:layout_toStartOf="@+id/play_pause"
42    android:src="@drawable/ic_skip_previous"
43    app:fabSize="mini" />    
44

Source https://stackoverflow.com/questions/69631777

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in Music Player

Tutorials and Learning Resources are not available at this moment for Music Player

Share this Page

share link

Get latest updates on Music Player