When my character crosses a finish line, I play a "win" sound. I have an AudioSource object to which I simply call PlayOneShot and pass it my AudioClip as:
public void PlayWon() {
if (GameData.Data.Settings.SoundsOn) {
AudioSource audio = GetComponent<AudioSource>();
audio.Stop();
audio.PlayOneShot(WinSound);
}
}
My settings for the AudioSource are this:
and the object where this is attached to is loaded in a Loader scene which is never destroyed. I ensure this by calling:
DontDestroyOnLoad(this);
on Awake.
My sound plays fine on iOS, iPhone and iPads. But when testing on my Samsung Galaxy Tab S, the sound plays and then pauses whilst the interstitial advert is displayed and then when dismissed, the sound carries on. I am using Chartboost and Admob and use the basic invoke:
if (Chartboost.hasInterstitial(CBLocation.LevelComplete)) {
Debug.Log("Showing CB Ad");
Chartboost.showInterstitial(CBLocation.LevelComplete);
}
else if (_admobInterstitial.IsLoaded()) {
Debug.Log("Showing Admob Ad");
_admobInterstitial.Show();
}
else {
Debug.Log("Neither cached, trying CB again");
Chartboost.cacheInterstitial(CBLocation.LevelComplete);
Chartboost.showInterstitial(CBLocation.LevelComplete);
}
Any ideas why my sounds cut out on this device? I don't have another Android device to test it on but I'm assuming it's an Android related problem. The sound cuts out on both Chartboost and Admob.
Thanks
You can use a coroutine for playing the sound. When the coroutine is finished, you can show ads.
private IEnumerator PlaySoundAndShowAd()
{
//play sound
yield return new WaitForSeconds(1.0f)
//show ads or do something.
}
Related
My website plays a background song and some audio effects at the same time. Although the song loads fine (I can see its duration via Audio.duration property), it doesn't play, while the audio effects play (I have already clicked on the screen to activate audio playing). On Firefox in my PC it plays without problem. The audio file is a 10 MB mp3 (but my Android is at home wi-fi). Below is part of my code.
var music,clicked=false,downloaded=false;
function play() {
music.play();
}
function canPlay() {
downloaded = true;
if (clicked) {
play();
}
}
function touchStart(e) {
if (!clicked) {
clicked = true;
if (downloaded) {
play();
}
}
}
function load() {
music = new Audio('mp3/music.mp3');
music.addEventListener('canplaythrough',canPlay,false);
window.addEventListener('touchstart',touchStart,false);
}
The load function is called in the onload of body. The clicked and downloaded variables are required because I never know what happens first: the user click or the audio finish downloading.
On Google mobile-friendly test, it says the audio file couldn’t be loaded (Status: Other error). I've read this test doesn't wait for more than 3 seconds. However, reading the time of the song in seconds doesn't prove it has downloaded?
Why won't the song play on mobile?
EDIT
I created a timer interval that tells me the position (music.currentTime) of the song once every minute. On desktop, it gives the right time. On mobile, it always gives 0, meaning that the song, although loaded (?), isn't really being played.
EDIT 2
I investigated the promise returned by music.play(), and noticed it was giving the error: "(NotAllowedError: play() failed because the user didn't interact with the document first)". It seems that touchStart doesn't count as a "user interaction" the way that mouseDown does...
In the end, I removed both touchStart and touchEnd (each with his own preventDefault), leaving the song to be played after the resulting mouseDown. I've kept the touchMove, however, because it's different from the mouseMove, and required for my site.
I'm developing a Voip-Application and i have an edge case where i want to play two raw files at the same time.
When i have an incoming call from my application i am creating a new Mediaplayer and play a custom ringtone. When i get shortly after also an incoming GSM-call i create a new mediaplayer and play a knocking sound to give the user feedback that there is also a GSM-Call incoming. At the same time i want the custom ringtone to continue playing.
private fun setAudioAttributesForFile(audioUsage: Int): AudioAttributes {
return AudioAttributes.Builder()
.setUsage(audioUsage)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build()
}
private fun startRingtone(fileToPlay: Int): MediaPlayer {
return MediaPlayer().apply {
reset()
if (fileToPlay == R.raw.ring {
setAudioAttributes(setAudioAttributesForFile(AudioAttributes.USAGE_NOTIFICATION_RINGTONE))
} else {
setAudioAttributes(setAudioAttributesForFile(AudioAttributes.USAGE_MEDIA))
}
isLooping = true
Main.get().resources.openRawResourceFd(fileToPlay).use {
setDataSource(
it.fileDescriptor,
it.startOffset,
it.length
)
}
setOnPreparedListener { start() }
prepareAsync()
}
}
The problem that i have with this code is that as soon as the knocking sound is playing the ringtone gets muted by the system and as soon as the knocking sound is stopping the ringtone continues.
What i also tried:
Using only
AudioAttributes.USAGE_NOTIFICATION_RINGTONE. As soon as the knocking sound starts to play both mediaPlayers are getting muted.
If i leave the setAudioAttributes() call away and replace these four lines to
if (fileToPlay == R.raw.ring) {
setAudioAttributesForFile(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
} else {
setAudioAttributesForFile(AudioAttributes.USAGE_MEDIA)
}
then i can play those two files at the same time. The problem then is that the ringtone file is not shown as a ringtone instead it is only shown as a media file. So when i increase and decrease the volume of the ringtone the flag does not show that it is a ringtone.
Is there a way to play one sound as a Ringtone and another sound over it as a normal Media Sound?
Thanks in advance. Any help is appreciated.
Use sound pool if you want to play both sounds at the same time.
I'm developing a game. I need a button to turn on and off game sounds.
In my app, I play background music which I want to be muted upon clicking a button. Here's my code:
AudioManager aManager = (AudioManager)getSystemService(AUDIO_SERVICE);
if (aManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) {
aManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
} else {
aManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
When I debug, the conditions are right but nothing happens! The sound is never turned off!
Check for method "isVolumeFixed()". If true, your device can't have it's sound changed. Some devices have a policy about that.
I had a media player, when user connect to chromecast in the middle of the video, I would like to cast the video to chromecast at the same position in the video where the user left off.
mediaProtocolCommand.setListener(new MediaProtocolCommand.Listener() {
public void onCompleted(MediaProtocolCommand mPCommand) {
messageStream.playFrom(currentVideoPosition);
}
});
Using the code snippet above I manage to get the video playing but it always start at the beginning of the video
Works fine for me using the Cast Android sample app. Make sure the parameter value for playFrom is the time in seconds.
Good day,
I'm currently building a website for myself (I'm a composer/producer), and I'm using Media Element for the main demo page. The page is under construction at the following link:
http://www.vincentrubinetti.com/listen.html
http://www.vincentrubinetti.com/listen.js
Below are what I think are the relevant functions and code:
function initPlayer()
{
player = new MediaElementPlayer('#listen_player',{
success: function (mediaElement, domObject)
{
mediaElement.addEventListener('play', resumeSong, false);
mediaElement.addEventListener('ended', playNextSong, false);
mediaElement.addEventListener('pause', pauseSong, false);
}
});
[omitted]
}
function setSong(element)
{
if (element != "")
{
unselectAllSongs();
document.getElementById(element).className = "listen_song_highlight";
[omitted]
var newSrc = document.querySelector("#"+element+" .listen_song_source").title;
player.pause();
player.setSrc(newSrc);
player.load();
}
}
function playSong(element)
{
document.querySelector("#"+element+" .listen_song_status").innerHTML = "playing";
player.play();
}
function playNextSong()
{
var newSong = document.querySelector(".listen_song_highlight + div.listen_song");
if (autoplay && newSong != null)
{
setSong(newSong.id);
playSong(newSong.id);
}
else
{
document.querySelector(".listen_song_highlight .listen_song_status").innerHTML = "stopped";
}
}
All the CSS end of this seems to be fine. It finds the next song on the list and sets the new source; I've verified it does this properly via alert and other debugging. However, on the Android default browser and the Dolphin browser, it seems to not be able to load the mp3 sometimes, and prematurely triggers the "ended" event to go to the next song. The result is that it appears to skip 2-3 songs after one is done playing. And it takes some finagling even to get it to play one, clicking on the song divs and the player play button. I can type in the same url that's in the html, and the browser will play/download it just fine, no problems accessing or loading it.
Here are the 3 mp3 files that repeat down the playlist, for reference. They are by me, but are placeholders for the real music.
NEW/music/creation.mp3
NEW/music/startup.mp3
NEW/music/win.mp3
Note that all of this works properly on Chrome, Firefox, IE8+, and Android Chrome (I haven't tested iPhone or iPad yet).
Is my diagnosis correct? Can anyone point me in the right direction? Is there any experience where MediaElement doesn't work properly on the Android default and Dolphin browsers?
I have the same problem in android (but with video...)
I was told that this is an issue with the file not being downloaded in time -- i.e. the browser starts the download, but since the file isn't downloaded it is 0:00 long, so the ended event is triggered.
If there is someway to make it so that the video / audio can be downloaded faster it solves the problem.
Strangely enough, if the device has good WiFi then this problem basically disappears.
See what John Dyer said about it here:
https://github.com/johndyer/mediaelement/issues/543