actionscript 3 - Play sound once then delay - android

I am a complete newcomer to as3, having started about 3 months ago as part of a university project, so apologies if I am asking an obvious question or I provide the wrong information.
I am creating a game where a 'monster' from an array collides with a static movie clip which the user has to avoid by killing the monster before they get there.
When the monster reaches the movie clip, I want it to play a 'munch' sound once, then not play it again for a few seconds, but the code as it is means that the sound plays over and over again while the array item and movie clip collide, which does not sound right.
I tried to correct this by adding a timer which allows the sound to continue for half a second and then stops the sound channel, but this does not seem to have worked.
How can I make the sound play once, not play again for the next few seconds and then play again if the objects are still colliding?
Thanks in advance.
Heres my code:
var sc: SoundChannel;
var munch: Sound = new Sound(new URLRequest("audio/munch.mp3"));
var muteTest: Boolean = false;
var munchStop:Timer = new Timer (500, 1);
munchStop.addEventListener(TimerEvent.TIMER, afterMunchStop);
function afterMunchStop(event: TimerEvent): void {
sc.stop();
}
if (monster1Array[i].hitTestObject(centre_mc)) {
if (muteTest == false) {
sc = munch.play();
munchStop.start();
}

var sc: SoundChannel;
var munch: Sound = new Sound(new URLRequest("audio/munch.mp3"));
var soundIsPlaying: Boolean = false;
//sound should loop until objects no longer collide
var munchStop:Timer = new Timer(500);
munchStop.addEventListener(TimerEvent.TIMER, afterMunchStop);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
function onEnterFrame(event:Event):void
{
//play sound if monsters collide and sound is not already playing
if (monster1Array[i].hitTestObject(centre_mc) && !soundIsPlaying)
{
sc = munch.play();
soundIsPlaying = true;
//start the timer if it's not running
if(!munchStop.running)
munchStop.start();
} else {
//stop the sound if it's playing
if(sc)
sc.stop();
soundIsPlaying = false;
//reset the timer when the objects are no longer colliding
if(munchStop.running)
munchStop.reset();
}
}
function afterMunchStop(event: TimerEvent): void {
soundIsPlaying = false;
}

Related

How to loop background audio without gap?

The app plays some background audio (wav) in an endless loop. Audio playback was flawless using just_audio package, but after switching to audioplayers, all looped audio now contain a short gap of silence before they restart at the beginning. Question now is: How to get rid of the gap?
The code to load and play the files is quite simple:
Future<void> loadAmbient() async {
_audioAmbient = AudioPlayer();
await _audioAmbient!.setSource(AssetSource('audio/ambient.wav'));
await _audioAmbient!.setReleaseMode(ReleaseMode.loop);
}
void playAmbient() async {
if (PlayerState.playing != _audioAmbient?.state) {
await _audioAmbient?.seek(Duration.zero);
_audioAmbient?.resume();
}
}
According to the audioplayers docs, this seems to be a known issue:
The Getting Started docs state:
Note: there are caveats when looping audio without gaps. Depending on the file format and platform, when audioplayers uses the native implementation of the "looping" feature, there will be gaps between plays, witch might not be noticeable for non-continuous SFX but will definitely be noticeable for looping songs. Please check out the Gapless Loop section on our Troubleshooting Guide for more details.
Following the link to the [Trouble Shooting Guide] (https://github.com/bluefireteam/audioplayers/blob/main/troubleshooting.md) reveals:
Gapless Looping
Depending on the file format and platform, when audioplayers uses the native implementation of the "looping" feature, there will be gaps between plays, witch might not be noticeable for non-continuous SFX but will definitely be noticeable for looping songs.
TODO(luan): break down alternatives here, low latency mode, audio pool, gapless_audioplayer, ocarina, etc
Interesting is the Depending on the file format and platform, ... part, which sounds as if gap-less loops could somehow be doable. Question is, how?
Any ideas how to get audio to loop flawless (i.e. without gap) are very much appreciated. Thank you.
You can pass this parameter
_audioAmbient = AudioPlayer(mode: PlayerMode.LOW_LATENCY);
if not solved u can try something new like https://pub.dev/packages/ocarina
I fixed it this way:
Created 2 players, set asset path to both of them and created the method that starts second player before first is completed
import 'package:just_audio/just_audio.dart' as audio;
audio.AudioPlayer player1 = audio.AudioPlayer();
audio.AudioPlayer player2 = audio.AudioPlayer();
bool isFirstPlayerActive = true;
StreamSubscription? subscription;
audio.AudioPlayer getActivePlayer() {
return isFirstPlayerActive ? player1 : player2;
}
void setPlayerAsset(String asset) async {
if (isFirstPlayerActive) {
await player1.setAsset("assets/$asset");
await player2.setAsset("assets/$asset");
} else {
await player2.setAsset("assets/$asset");
await player1.setAsset("assets/$asset");
}
subscription?.cancel();
_loopPlayer(getActivePlayer(), isFirstPlayerActive ? player2 : player1);
}
audio.AudioPlayer getActivePlayer() {
return isFirstPlayerActive ? player1 : player2;
}
void _loopPlayer(audio.AudioPlayer player1, audio.AudioPlayer player2) async {
Duration? duration = await player1.durationFuture;
subscription = player1.positionStream.listen((event) {
if (duration != null &&
event.inMilliseconds >= duration.inMilliseconds - 110) {
log('finished');
player2.play();
isFirstPlayerActive = !isFirstPlayerActive;
StreamSubscription? tempSubscription;
tempSubscription = player1.playerStateStream.listen((event) {
if (event.processingState == audio.ProcessingState.completed) {
log('completed');
player1.seek(const Duration(seconds: 0));
player1.pause();
tempSubscription?.cancel();
}
});
subscription?.cancel();
_loopPlayer(player2, player1);
}
});
}

Use AudioRecord to record but the sound has changed

This is an issue related to Android AudioRecord and Exoplayer.
The required scene is to record while playing the accompaniment (note: the sound of the accompaniment file is fluctuatingly large and small);
The problem found so far: When the earphone is inserted into the recording and playback, the recorded sound is normal, but the sound played through the speaker gradually becomes flat (no longer loud and small)
And I tried these parameters, but nothing works:
val canceler = AcousticEchoCanceler.create(record.audioSessionId)
val suppressor = NoiseSuppressor.create(record.audioSessionId)
if (suppressor != null) {
suppressor.enabled = false
}
if (canceler != null) {
canceler.enabled = false
}
if (AutomaticGainControl.isAvailable()) {
val gainControl = AutomaticGainControl.create(record.audioSessionId)
gainControl.enabled = false
}

How to play a sound when a user clicks the right answer

I'm creating a quiz in flash using AS3. I'm having trouble trying to include sound when a user clicks a right or wrong answer.
How can I correctly play sound?
This is the code below
import flash.media.Sound;
//button 1, see if the first text field equals the answer, if it does it plays the correct scene, if it doesnt it plays incorrect scene
myTextField11.addEventListener(MouseEvent.MOUSE_UP,state11);
function state11(evt:MouseEvent)
{
if (myTextField11.text == answer1){
trace("Correct answer!!");
gotoAndPlay(2,"quiz1");
count = count + 10;
scoreBox.text = (count).toString();
setTimeout(gotoAndPlay, 1250, 1, "quiz2");
} else {
trace(myTextField11);
gotoAndPlay(3,"quiz1");
var mySound:Sound = new WrongAnswer();
WrongAnswer.play();
setTimeout(gotoAndPlay, 1250, 1,"quiz2");
}
}
I've now done this but no luck:
import flash.media.Sound;
//button 1, see if the first text field equals the answer, if it does it plays the correct scene, if it doesnt it plays incorrect scene
myTextField11.addEventListener(MouseEvent.MOUSE_UP,state11);
function state11(evt:MouseEvent)
{
if (myTextField11.text == answer1){
trace("Correct answer!!");
gotoAndPlay(2,"quiz1");
count = count + 10;
scoreBox.text = (count).toString();
setTimeout(gotoAndPlay, 1250, 1, "quiz2");
} else {
trace(myTextField11);
gotoAndPlay(3,"quiz1");
MediaPlayer player = MediaPlayer player=MediaPlayer.create(YourActivity.this,R.raw.WrongAnswer);
player.start();
setTimeout(gotoAndPlay, 1250, 1,"quiz2");
}
MediaPlayer player=MediaPlayer.create(YourActivity.this,R.raw.nameofile);
player.start();
This code helps to play the music.
Place the code inside the Onclick() method.
If you declared mySound as variable name for the WrongAnswer(); sound then use that exact same name when accessing by code.
import flash.media.Sound;
//button 1, see if the first text field equals the answer, if it does it plays the correct scene, if it doesnt it plays incorrect scene
myTextField11.addEventListener(MouseEvent.MOUSE_UP,state11);
function state11(evt:MouseEvent)
{
if (myTextField11.text == answer1)
{
trace("Correct answer!!");
gotoAndPlay(2,"quiz1");
count = count + 10;
scoreBox.text = (count).toString();
setTimeout(gotoAndPlay, 1250, 1, "quiz2");
}
else
{
trace(myTextField11);
gotoAndPlay(3,"quiz1");
var mySound:Sound = new WrongAnswer();
//WrongAnswer.play();
mySound.play();
setTimeout(gotoAndPlay, 1250, 1,"quiz2");
}
}
If there's still issues then let me know. The alternative I was going to give was to just embed sound by code but that may not be necessary here...

How to add Music in AS3 Android App

I am a noob in Adobe Flash Action Script 3..
I want a music player (with start, pause buttons) code in AS3, I have imported the music in the library and I have added the following code
var qMySound:Sound = new mySound1();
qMySound.play(0, 9999);
mySound1 is the AS Linkage
and it works.
I made a stop button using the code snippet's code
button_7.addEventListener(MouseEvent.CLICK, fl_ClickToStopAllSounds_6);
function fl_ClickToStopAllSounds_6(event:MouseEvent):void
{
SoundMixer.stopAll();
}
And it works too, but now i want to start it again, I tried to use this code:
button_1.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndStopAtFrame_28);
function fl_ClickToGoToAndStopAtFrame_28(event:MouseEvent):void
{
gotoAndStop(1);
}
The music AS3 code is in Frame 1 btw.
And that doesn't work.. so any ideas?
edit:
This is my code:
var mySound:Sound = new Sound();
var myChannel:SoundChannel = new SoundChannel();
var myTransform:SoundTransform = new SoundTransform();
var lastPosition:Number = 0;
var mySound:Sound = new mySound1(0,999);
myChannel = mySound.play();
// here is to learn how to deal with volume as well (between 0 and 1)
myTransform.volume = .5;
// setting the SoundTransform instance to the myChannel object
myChannel.soundTransform = myTransform;
pause_btn.addEventListener(MouseEvent.CLICK, onClickPauseHandler, false, 0, true);
play_btn.addEventListener(MouseEvent.CLICK, onClickPlayHandler, false, 0, true);
function onClickPauseHandler(event:MouseEvent):void
{
// getting the current position of the sound
lastPosition = myChannel.position;
// stopping the current sound
myChannel.stop();
}
function onClickPlayHandler(event:MouseEvent):void
{
// playing from the saved position
myChannel = mySound.play(0,999);
}
And this error pops out.
Line 8 | 1151: A conflict exists with definition of mySound in namespace internal.
You need to use the classes SoundChannel/SoundTransform to have more functionalities. When you stop all sounds using SoundMixer.stopAll(), you are not stopping that respective sound.
Follow some example code, that you guide you to achieve what you are expecting, plus, give you some extra knowledge about how to deal with sound.
var mySound:Sound = new Sound();
var myChannel:SoundChannel = new SoundChannel();
var myTransform:SoundTransform = new SoundTransform();
var lastPosition:Number = 0;
mySound.load(new URLRequest('yourMp3FileName.mp3'));
myChannel = mySound.play();
// here is to learn how to deal with volume as well (between 0 and 1)
myTransform.volume = .5;
// setting the SoundTransform instance to the myChannel object
myChannel.soundTransform = myTransform;
pause_btn.addEventListener(MouseEvent.CLICK, onClickPauseHandler, false, 0, true);
play_btn.addEventListener(MouseEvent.CLICK, onClickPlayHandler, false, 0, true);
function onClickPauseHandler(event:MouseEvent):void
{
// getting the current position of the sound
lastPosition = myChannel.position;
// stopping the current sound
myChannel.stop();
}
function onClickPlayHandler(event:MouseEvent):void
{
// playing from the saved position
myChannel = mySound.play(lastPosition);
}

phonegap media sound stop playing after 5 times

I need to play the "correct" sound if user answer the question correctly and "wrong" if incorrect. The sound is playing at first but after at the fifth time I answer correctly which output the fourth time "correct" sound already the fifth time, no sound can be heard. It seems the music can only played at most 4th times.
What is the possible reason that cause this?
updated*
I added media.release in my stopAudio() but so far the sound can be heard for 6th (improved) but it is still not suits my case. (Many questions that need the same sound effect)
Js.file
// Audio player
var my_media = null;
var mediaTimer = null;
// Play audio
function playAudio(src) {
// Create Media object from src
my_media = new Media(src, null, soundCB);
my_media.play();
}
function soundCB(err){
console.log("playAudio():Audio Error: "+err);
}
// Stop audio
//
function stopAudio() {
if (my_media) {
alert("AQA");
my_media.stop();
my_media.release();
}
clearInterval(mediaTimer);
mediaTimer = null;
}
/////question part//////
$("#answer").live('tap', function(event){
if(buttonAns==true) {
$this= $(this);
buttonAns = false;
var choice = $this.attr("class");
if((correctAnsNo == 0 && choice =="answer0")||(correctAnsNo == 1 && choice =="answer1")||(correctAnsNo == 2 && choice =="answer2")){
playAudio('/android_asset/www/audio/fall.mp3'); //falling sound
correct = parseInt(correct)+2;
playAudio('/android_asset/www/audio/correct.mp3'); //dingdong
}else{
playAudio('/android_asset/www/audio/wrong1.wav');
}
if(quesNo < wordsNo ){
setTimeout(function() {
buttonAns = true;
db.transaction(queryQuesDB, errorCB);
},1800);
}else{
endLevel();
}
} else {
event.preventDefault();
}
});
Android has a finite amount of resources in order to play sounds. You keep creating a new Media object each time you want to play a file. You need to release the sounds you are not using. If you need to play those sounds multiple times each then consider creating separate media objects to hold a reference to those sounds.
Read up on media.release.
I had the same problem.
The solution I did.:
if(media){
media.stop();
media.release();
}
media = new Media(...);
Here's my trick: I released it upon it finished playing or an error occurred.
function playAudio(url) {
try {
var my_media = new Media(url,
// success callback
function () {
**my_media.release();**
},
// error callback
function (err) {
**my_media.release();**
});
// Play audio
my_media.play();
} catch (e) {
alert(e.message);
}
}

Categories

Resources