How can I increase volume mediaplayer sound in kotlin compose? - kotlin

I've been doing for a while dictionary app and I want the word to be heard aloud, so I made the word listen button. It's working properly but for some reason it sounds a bit low when I'm listening so I want to turn the volume up a bit how can I do that? I am sharing my codes below
I am making the dictionary application in kotlin and using compose.
phoneticSound function
fun phoneticSound(_audioUrl:String){
val mediaPlayer = MediaPlayer()
var audioUrl = _audioUrl
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)
try {
mediaPlayer.setDataSource(audioUrl)
mediaPlayer.prepare()
mediaPlayer.start()
} catch (e: Exception) {
e.printStackTrace()
}
}
This function receives a string. This string is the url of the audio source. I am playing the audio with mediaPlayer using this url.
How can I adjust the sound by adding an add-on to the codes I've made?

MediaPlayer has the 'setVolume()' function, which you can use to set the volume. You can set values from 0.0 - 1.0 (0-100%).
source: https://developer.android.com/reference/android/media/MediaPlayer#setVolume(float,%20float)

Related

vlcj - How to change the volume of audio before playing it?

I tried this
val player: MediaPlayer = MediaPlayerFactory("-vvv").mediaPlayers().newMediaPlayer()
val result0: Boolean = player.audio().setVolume(50) // result0: true
player.media().play("/path/to/audio.ogg")
val result1: Boolean = player.audio().setVolume(50) // result1: false
and this
val player: MediaPlayer = MediaPlayerFactory("-vvv").mediaPlayers().newMediaPlayer()
val result0 = player.audio().setVolume(50) // result0: true
player.media().prepare("/path/to/audio.ogg")
val result1: Boolean = player.audio().setVolume(50) // result1: false
player.controls().play()
val result2: Boolean = player.audio().setVolume(50) // result2: false
but the volume remains at 100%.
The only way I found is to make something like this
val player: MediaPlayer = MediaPlayerFactory("-vvv").mediaPlayers().newMediaPlayer()
player.events().addMediaPlayerEventListener(object : MediaPlayerEventAdapter() {
override fun mediaPlayerReady(mediaPlayer: MediaPlayer) {
mediaPlayer.submit {
mediaPlayer.audio().setVolume(50)
}
}
})
player.media().play("/path/to/audio.ogg")
But the solution is a bit far from ideal. Because it starts to play, plays a bit, and then whoosh, the volume has changed.
I tried vlcj 4.4.0 and 4.5.2, VLC 3.0.8 and 3.0.10, jdk8 and 14, but it works in the same way.
This is something that unfortunately does not work in VLC 3.x, but does work in the upcoming VLC 4.x (at the time of writing this answer, VLC 4 is still in development).
The following code works for me using the latest VLC 4 built from source, and the latest vlcj-5 snapshot:
import uk.co.caprica.vlcj.player.component.AudioPlayerComponent;
import uk.co.caprica.vlcj.test.VlcjTest;
public class AudioMediaPlayerComponentTest extends VlcjTest {
public static void main(String[] args) throws Exception {
String mrl = "/home/music/some-cool-synthwave-tune.mp3";
AudioPlayerComponent audioMediaPlayerComponent = new AudioPlayerComponent();
audioMediaPlayerComponent.mediaPlayer().audio().setVolume(5);
audioMediaPlayerComponent.mediaPlayer().media().play(mrl);
Thread.currentThread().join();
}
}
The initial volume for the media player comes from the OS volume settings, and in fact the OS volume setting is linked both ways to the media player. Changing the volume in one place is reflected in the other.
Volume handling through LibVLC generally just seems much better in VLC 4.
If you're stuck on VLC 3, which is reasonable at the present time, then unfortunately you're also stuck with some sort of compromise solution like using the "ready" event that you've already found.
All the ready event does is to wait for the first position-changed event, and that event was created specifically as a compromise for purposes like this.
I tested all the native event callbacks available for the media player, and nothing worked to set the volume before playback had actually started.
This leaves you with the following, as you already found:
import uk.co.caprica.vlcj.player.base.MediaPlayer;
import uk.co.caprica.vlcj.player.component.AudioPlayerComponent;
import uk.co.caprica.vlcj.test.VlcjTest;
public class AudioMediaPlayerComponentTest extends VlcjTest {
public static void main(String[] args) throws Exception {
String mrl = "/home/music/some-cool-synthwave-tune.mp3";
AudioPlayerComponent audioMediaPlayerComponent = new AudioPlayerComponent() {
#Override
public void mediaPlayerReady(MediaPlayer mediaPlayer) {
mediaPlayer.audio().setVolume(30);
}
};
audioMediaPlayerComponent.mediaPlayer().media().play(mrl);
Thread.currentThread().join();
}
}
A completely sideways alternative might be to play the shortest possible silent media as a kind of pre-roll - when that media is finished (there's a finished or stopped event you can listen for) you should then be able to set the volume and play your actual media. I did not try this.

How do I rate Google Play application directly in my app on Kotlin language?

I need to make rate option in my app.
I want to just provide ability for users to rate my app on Google Play.
I found solution (Kotlin):
fun rateApp() {
val uri = Uri.parse("market://details?id=$packageName")
val myAppLinkToMarket = Intent(Intent.ACTION_VIEW, uri)
try {
startActivity(myAppLinkToMarket)
} catch (e: ActivityNotFoundException) {
Toast.makeText(this, "Impossible to find an application for the market", Toast.LENGTH_LONG).show()
}
}
P.S. This code does not work on the simulator, use a real device.

How to replace blocking code for reading bytes in Kotlin

I have ktor application which expects file from multipart in code like this:
multipart.forEachPart { part ->
when (part) {
is PartData.FileItem -> {
image = part.streamProvider().readAllBytes()
}
else -> // irrelevant
}
}
The Intellij IDEA marks readAllBytes() as inappropriate blocking call since ktor operates on top of coroutines. How to replace this blocking call to the appropriate one?
Given the reputation of Ktor as a non-blocking, suspending IO framework, I was surprised that apparently for FileItem there is nothing else but the blocking InputStream API to retrieve it. Given that, your only option seems to be delegating to the IO dispatcher:
image = withContext(Dispatchers.IO) { part.streamProvider().readBytes() }

C# Audio File is played in a loop although it is stopped

I have an older implementation using NAudio 1.6 to play a ring tone signalling an incoming call in an application. As soon as the user acceptes the call, I stop the playback.
Basically the follwing is done:
1. As soon as the I get an event that a call must be signalled, a timer is started
2. Inside this timer Play() on the player
3. When the timer starts again, a check is performed if the file is played by checking the CurrentTime property against the TotalTime propery of the WaveStream
4. When the user accepts the call, Stop() is called on the player and also stop the timer
The point is, that we run sometimes in cases where the playback is still repeated although the timer is stopped and the Stop() was called on the player.
In the following link I read that the classes BufferedWaveProvider and WaveChannel32 which are used in the code are always padding the buffer with zero.
http://mark-dot-net.blogspot.com/2011/05/naudio-and-playbackstopped-problem.html
Is it possible that the non-stopping playback is due to usage of the classes BufferedWaveProvider and WaveChannel32?
In NAudio 1.7 the AudioFileReader class is there. Is this class also padding with zeros? I did not find a property like PadWithZeroes in this class. Does it make to use AudioFileReader in this case of looped playback?
Below the code of the current implementation of the TimerElapsed
void TimerElapsed(object sender, ElapsedEventArgs e)
{
try
{
WaveStream stream = _audioStream as WaveStream;
if (stream != null && stream.CurrentTime >= stream.TotalTime )
{
StartPlayback();
}
}
catch (Exception ex)
{
//do some actions here
}
}
The following code creates the input stream:
private WaveStream CreateWavInputStream(string path)
{
WaveStream readerStream = new WaveFileReader(path);
if (readerStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm)
{
readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream);
readerStream = new BlockAlignReductionStream(readerStream);
}
if (readerStream.WaveFormat.BitsPerSample != 16)
{
var format = new WaveFormat(readerStream.WaveFormat.SampleRate, 16, readerStream.WaveFormat.Channels);
readerStream = new WaveFormatConversionStream(format, readerStream);
}
WaveChannel32 inputStream = new WaveChannel32(readerStream);
return inputStream;
}

change pitch of .3gp file while playing

In my project i have recorded sound using mediaplayer and save as .3gp file but when i want to play it using some audio effect or fast forwarding or change pitch of audio while playing. i have used mediaplayer but not working.then i used audiotrack but audiotrack takes only bytestream as input to play. i just want to play .3gp file and change pitch while playing.. i use this one below.
Help me...thanks in advance...
public void play() {
File path = new File(
Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/sdcard/meditest/");
File[] f=path.listFiles();
isPlaying=true;
int bufferSize = AudioTrack.getMinBufferSize(outfrequency,
channelConfigurationout, audioEncoding);
short[] audiodata = new short[bufferSize];
try {
DataInputStream dis = new DataInputStream(
new BufferedInputStream(new FileInputStream(
f[0])));
audioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC, outfrequency,
channelConfigurationout, audioEncoding, bufferSize,
AudioTrack.MODE_STREAM);
audioTrack.setPlaybackRate((int) (frequency*1.5));
AudioManager audioManager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
// Set the volume of played media to maximum.
audioTrack.setStereoVolume(1.0f,1.0f);
Log.d("Clapper","player start");
audioTrack.play();
while (isPlaying && dis.available() > 0) {
int i = 0;
while (dis.available() > 0 && i < audiodata.length) {
audiodata[i] = dis.readShort();
i++;
if(i/50==0)
Log.d("Clapper", "playing now"+i);
}
audioTrack.write(audiodata, 0, audiodata.length);
}
Log.d("Clapper","AUDIO LENGTH: "+String.valueOf(audiodata));
dis.close();
audioTrack.stop();
} catch (Throwable t) {
Log.e("AudioTrack", "Playback Failed");
}
Log.d("Clapper","AUDIO state: "+String.valueOf(audioTrack.getPlayState()));
talkAnimation.stop();
if(audioTrack.getPlayState()!=AudioTrack.PLAYSTATE_PLAYING)
{
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
imgtalk.setBackgroundResource(R.drawable.talk1);
}
});
}
}
I tried library called Sonic. Its basically for Speech as it use PSOLA algo to change pitch and tempo.
Sonic Library
i got your problem .Media player does not support cha
Consider using a SoundPool
http://developer.android.com/reference/android/media/SoundPool.html
It supports changing the pitch in realtime while playing
The playback rate can also be changed. A playback rate of 1.0 causes the sound to play at its original frequency (resampled, if necessary, to the hardware output frequency). A playback rate of 2.0 causes the sound to play at twice its original frequency, and a playback rate of 0.5 causes it to play at half its original frequency. The playback rate range is 0.5 to 2.0.
Once the sounds are loaded and play has started, the application can trigger sounds by calling SoundPool.play(). Playing streams can be paused or resumed, and the application can also alter the pitch by adjusting the playback rate in real-time for doppler or synthesis effects.
http://developer.android.com/reference/android/media/SoundPool.html#setRate(int, float)
IF you want to change pitch while playing sound you have to use sound pool .this is the best way to do this.you can fast forward your playing by some amount and see you feel that pitch has been changed.