当前位置: 首页 > news >正文

从零开发游戏需要学习的c#模块,第二十二章(音效与背景音乐)

本节课学习目标加载并播放背景音乐循环收集金币时播放音效碰到敌人时播放音效用 MonoGame 内置音频系统实现第一步准备音频文件去这些网站下载免费音效freesound.orgopengameart.orgmixkit.co需要三个文件文件用途coin.wav吃金币音效hit.wav碰敌人音效bgm.wav或bgm.mp3背景音乐MonoGame 支持的格式.wav、.mp3、.ogg下载后放到Content文件夹属性设为“如果较新则复制”。第二步完整代码把Game1.cs完整替换为using Microsoft.Xna.Framework;using Microsoft.Xna.Framework.Graphics;using Microsoft.Xna.Framework.Input;using Microsoft.Xna.Framework.Audio;using Microsoft.Xna.Framework.Media;using System;using System.Collections.Generic;using System.IO;using FontStashSharp;namespace MY_FIRST_GAME{public enum GameState { Exploring, Battling }public class Game1 : Game{private GraphicsDeviceManager _graphics;private SpriteBatch _spriteBatch;private Player player default!;private Texture2D playerSpriteSheet;private Texture2D coinTexture;private ListVector2 coins;private Random rng;private int score;private Texture2D enemyTexture;private ListVector2 enemies;private SpriteFontBase font;private GameState state GameState.Exploring;// ★ 音频private SoundEffect coinSound default!;private SoundEffect hitSound default!;private Song bgm default!;public Game1(){_graphics new GraphicsDeviceManager(this);Content.RootDirectory Content;IsMouseVisible true;// ★ 背景音乐必须通过 MGCB Editor 加载// 如果 MGCB 不能用这里会跳过音乐加载}protected override void Initialize(){_graphics.PreferredBackBufferWidth 800;_graphics.PreferredBackBufferHeight 600;_graphics.ApplyChanges();rng new Random();coins new ListVector2();enemies new ListVector2();score 0;SpawnCoins(5);SpawnEnemies(3);base.Initialize();}protected override void LoadContent(){_spriteBatch new SpriteBatch(GraphicsDevice);// 玩家图集using var stream File.OpenRead(Content/player_spritesheet.png);playerSpriteSheet Texture2D.FromStream(GraphicsDevice, stream);player new Player(playerSpriteSheet, new Vector2(400, 300));// 金币coinTexture new Texture2D(GraphicsDevice, 24, 24);Color[] coinData new Color[24 * 24];for (int i 0; i coinData.Length; i) coinData[i] Color.Gold;coinTexture.SetData(coinData);// 敌人enemyTexture new Texture2D(GraphicsDevice, 40, 40);Color[] enemyData new Color[40 * 40];for (int i 0; i enemyData.Length; i) enemyData[i] Color.Red;enemyTexture.SetData(enemyData);// 字体var fontSystem new FontSystem();fontSystem.AddFont(File.ReadAllBytes(Content/consola.ttf));font fontSystem.GetFont(18);// ★ 加载音效SoundEffect 可以用 FileStream 直接读try{using var coinStream File.OpenRead(Content/coin.wav);coinSound SoundEffect.FromStream(coinStream);using var hitStream File.OpenRead(Content/hit.wav);hitSound SoundEffect.FromStream(hitStream);// 背景音乐MediaPlayer 需要 MGCB 编译直接读文件不支持// 暂时用音效替代把 bgm 循环播放}catch (Exception ex){System.Diagnostics.Debug.WriteLine(音效加载失败 ex.Message);}}// ★ 开始播放背景音乐在 Initialize 之后调用protected override void BeginRun(){base.BeginRun();// 尝试播放背景音乐音效作为临时方案try{// 如果你的 bgm 是 mp3/wav可以用 SoundEffect 播放using var bgmStream File.OpenRead(Content/bgm.wav);var bgmSound SoundEffect.FromStream(bgmStream);SoundEffectInstance bgmInstance bgmSound.CreateInstance();bgmInstance.IsLooped true;bgmInstance.Volume 0.3f; // 音量 30%bgmInstance.Play();}catch{// 没有音乐文件就跳过}}private void SpawnCoins(int count){for (int i 0; i count; i)coins.Add(new Vector2(rng.Next(50, 750), rng.Next(50, 550)));}private void SpawnEnemies(int count){for (int i 0; i count; i)enemies.Add(new Vector2(rng.Next(80, 720), rng.Next(80, 520)));}protected override void Update(GameTime gameTime){float deltaTime (float)gameTime.ElapsedGameTime.TotalSeconds;KeyboardState keyboard Keyboard.GetState();if (state GameState.Exploring){player.Update(deltaTime);CheckCoinCollision();CheckEnemyCollision();if (coins.Count 0) SpawnCoins(5);if (enemies.Count 0) SpawnEnemies(3);}if (keyboard.IsKeyDown(Keys.M)){// ★ 按 M 静音/取消静音MediaPlayer.IsMuted !MediaPlayer.IsMuted;SoundEffect.MasterVolume SoundEffect.MasterVolume 0 ? 0f : 1f;}if (keyboard.IsKeyDown(Keys.Escape)) Exit();base.Update(gameTime);}private void CheckCoinCollision(){Rectangle playerRect player.GetBounds();for (int i coins.Count - 1; i 0; i--){Rectangle coinRect new Rectangle((int)coins[i].X, (int)coins[i].Y, 24, 24);if (playerRect.Intersects(coinRect)){coins.RemoveAt(i);score 10;// ★ 播放吃金币音效try { coinSound?.Play(); }catch { }}}}private void CheckEnemyCollision(){Rectangle playerRect player.GetBounds();for (int i enemies.Count - 1; i 0; i--){Rectangle enemyRect new Rectangle((int)enemies[i].X - 20, (int)enemies[i].Y - 20, 40, 40);if (playerRect.Intersects(enemyRect)){enemies.RemoveAt(i);score 50;// ★ 播放碰敌人音效try { hitSound?.Play(); }catch { }}}}protected override void Draw(GameTime gameTime){GraphicsDevice.Clear(Color.CornflowerBlue);_spriteBatch.Begin();foreach (Vector2 coinPos in coins)_spriteBatch.Draw(coinTexture, coinPos, Color.White);foreach (Vector2 enemyPos in enemies)_spriteBatch.Draw(enemyTexture, enemyPos, null, Color.White,0f, new Vector2(20, 20), 1f, SpriteEffects.None, 0f);player.Draw(_spriteBatch);_spriteBatch.DrawString(font, $分数{score}, new Vector2(10, 10), Color.White);_spriteBatch.DrawString(font, $金币{coins.Count}, new Vector2(10, 35), Color.Gold);_spriteBatch.DrawString(font, $敌人{enemies.Count}, new Vector2(10, 60), Color.Red);_spriteBatch.DrawString(font, $HP{player.Hp}/{player.MaxHp}, new Vector2(10, 85), Color.LimeGreen);_spriteBatch.DrawString(font, WASD移动 | M静音 | ESC退出, new Vector2(10, 570), Color.LightGray);_spriteBatch.End();base.Draw(gameTime);}}}本节课新内容using var stream File.OpenRead(Content/coin.wav); coinSound SoundEffect.FromStream(stream); coinSound.Play(); // 播放一次SoundEffectInstance bgmInstance bgmSound.CreateInstance(); bgmInstance.IsLooped true; // 循环播放 bgmInstance.Volume 0.3f; // 音量 bgmInstance.Play();SoundEffect.MasterVolume 0f; // 所有音效静音 SoundEffect.MasterVolume 1f; // 恢复本节课到此结束我叫魔法阵维护师关注我下期更精彩
http://www.rkmt.cn/news/1365456.html

相关文章:

  • 终极Zotero中文文献管理指南:茉莉花插件三招解决90%难题
  • 基于开源大模型的自动化定性分析:GATOS工作流实践指南
  • Windows控制台程序逆向入门:从破解到理解的实战指南
  • 2026 海南财税公司排名对比:代理记账・注册公司・营业执照代办优选 - 品牌优企推荐
  • 2026年GEO优化源码出售服务商横向评测与避坑选型实战指南 - 品牌报告
  • arXiv开始拒收综述,CS新人发论文得找人背书
  • 软件工程中机器学习实践:学术论文与专家访谈的“说做差距”分析
  • SQLite到MySQL数据库迁移工具:解决异构数据库转换的智能方案
  • 魔兽争霸3现代化优化指南:WarcraftHelper让经典游戏焕发新生
  • 基于FPGA的量子比特实时神经网络读出:96%保真度与32纳秒延迟实现
  • TPFanCtrl2终极教程:5分钟掌握ThinkPad风扇智能控制与静音散热优化
  • VMware Workstation Pro 17免费许可证密钥完整指南:快速激活专业虚拟化工具
  • HAR模型调优实战:为何精心调优的线性模型能击败复杂机器学习?
  • DP-QEq恒电位框架:原子尺度揭示锂枝晶成核机理与SEI调控
  • 第七史诗自动化助手E7Helper:轻松实现游戏自动化,告别重复操作
  • Vectorizer:3分钟免费将普通图片转换为无限放大矢量图
  • 量子几何机器学习:从理论到代码的灰盒模型实战
  • 魔兽争霸3终极优化指南:5分钟解决画面拉伸、帧率限制与中文兼容问题
  • 实战揭秘:3步解锁你的微信聊天记忆宝库
  • RAG:终结AI“一本正经胡说八道”,让AI回答问题不再答非所问!
  • Anthropic为何如此反华
  • EasyExcel 核心实战:合并单元格、在线编辑与导出全攻略
  • BabelDOC终极指南:如何完美保留PDF格式的专业文档翻译工具
  • HCI数据集驱动机器学习PBL课程:从EEG脑电实战到全栈能力培养
  • 登录页面渗透测试实战:从零基础到发现高危漏洞链
  • 【AI Agent零售落地实战指南】:2024年已验证的7大高ROI场景与避坑清单
  • Web安全十大漏洞原理与实战:从SQL注入到XXE的运行时脆弱性解析
  • Sunshine虚拟手柄配置终极指南:打造完美游戏串流体验
  • 机器学习赋能心电图分析:探索神经认知障碍的早期筛查新路径
  • ICA与NMF算法详解:从盲源分离到矩阵分解的数学原理与工程实践