How to play a sound within a view
I need to play a sound file from inside a view. I can use "sound.play();" to play the sound in the window, but I need it to play from the view. I hope someone will be able to help with this. My code is below…
var imageView = Titanium.UI.createImageView({
image:myImage,
top:20,
width:300,
height:300
});
sound = Titanium.Media.createSound({url:mySound});
var view = Titanium.UI.createView({
top:20,
width:300,
height:300
});
view.add(imageView);
view.play(sound);
win.add(view);
7 Answers
-
I think you should be able to fire an event easily from within the view, and then his event will call a custom handler. I did this for my latest app, works fine, I can fire the event from anywhere within the app (even from within an onClick event in the view HTML).
// make sure that sound effects do not stop the users itunes music Titanium.Media.defaultAudioSessionMode = Titanium.Media.AUDIO_SESSION_MODE_AMBIENT; // method for loading sounds var soundArray = []; function loadSound(soundName) { soundArray[soundName] = Titanium.Media.createSound({ url:'sounds/'+soundName+'.mp3', preload:true }); } // now load the sounds loadSound('chime'); loadSound('bell'); // event listener for playing any sound Ti.App.addEventListener('playSound', function(data) { if (soundArray[data.sound] != null) { soundArray[data.sound].play(); } });
And then from anywhere else:
Ti.App.fireEvent("playSound", { sound: "chime"} );
-
you can just do this, the documentation states this is just for basic sounds and recommends Titanium.Media.createAudioPlayer for streaming or longer media files.
sound = Titanium.Media.createSound({url:mySound}); sound.play(); sound.release();
-
sound.play(); works fine as stated above. But what I need is for the sound to play from within the view. The reason being that the view contains an event listener that when clicked will refresh the image and the sound.
Do you know how to play the sound from the view and not from the window?
-
from within your event listener you could fire a custom event that plays the sound
-
Hal,
perhaps you are right about using a window instead of a view. To better explain this I drew a picture.
If you know a better way of achieving the same thing, please let me know. I appreciate all your help.
Regards,
Dave
-
Hi David
Assuming that you wanna play the sound when the View pops up…., hope the code will help you…
function playSound(url){ var file = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,url); var sound = Titanium.Media.createSound({ sound:file, volume:1.0 }); sound.addEventListener('complete',function(e){ Ti.API.info('sound played'); }); sound.play(); } var imageView = Titanium.UI.createImageView({ image:myImage, top:20, width:300, height:300 }); playSound(soundURL); win.add(imageView); win.open(); });
NOTE
First time playing the sound takes few seconds to play the sound… -
Double Post…