Demonstrates how to play a song from a user’s media libary.
The Complete Sample
The code in this tutorial illustrates the technique described in the text. A complete code sample for this tutorial is available for you to download, including full source code and any additional supporting files required by the sample.
The following example plays the first song from a randomly picked album.
The Albums property provides access to the media library, and the Play method will play a song. Consider any current audio playback when using the Play method. If the user has a different song playing currently, the user can use theStop method to stop the current song.
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Net; using Microsoft.Xna.Framework.Storage; namespace PlaySong { public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; MediaLibrary sampleMediaLibrary; Random rand; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; // Frame rate is 30 fps by default for Zune. TargetElapsedTime = TimeSpan.FromSeconds(1 / 30.0); sampleMediaLibrary = new MediaLibrary(); rand = new Random(); } protected override void Initialize() { MediaPlayer.Stop(); // stop current audio playback // generate a random valid index into Albums int i = rand.Next(0, sampleMediaLibrary.Albums.Count - 1); // play the first track from the album MediaPlayer.Play(sampleMediaLibrary.Albums[i].Songs[0]); base.Initialize(); } protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // TODO: use this.Content to load your game content here } protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); // TODO: Add your update logic here base.Update(gameTime); } protected override void Draw(GameTime gameTime) { graphics.GraphicsDevice.Clear(Color.CornflowerBlue); // TODO: Add your drawing code here base.Draw(gameTime); } } }
- 本文固定链接: http://www.wy182000.com/2009/02/22/how-to-play-a-song/
- 转载请注明: wy182000 于 Studio 发表