Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

iNando

Como reproduzir audio no C# via WEB

Recommended Posts

olá gostaria de saber se é possivel reproduzir

audio na web com c#

 

o que quero fazer é quando clico em um button ele reproduza o audio

 

seria possivel ou tenho que recorrer ao flash

 

é que nao gostaria de usar outros componentes,

quero fazer como se fosse nativo do sistema.

 

sem o cliente ter que baixar o flash ou outro plugin para rodar.

 

valeu pela atenção

http://forum.imasters.com.br/public/style_emoticons/default/thumbsup.gif

Compartilhar este post


Link para o post
Compartilhar em outros sites

Acho q enconteri realmente concreto para te ajudar..testa ai...

 

using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;

namespace SDL2
{
	/// <summary>
	/// Summary description for TestPlayer.
	/// </summary>
	public class TestPlayer
	{
		private CallBackFunction FMT_CALLBACK;
		private inputFile input;		


		unsafe public TestPlayer()
		{
			FMT_CALLBACK = new CallBackFunction(FillBuffer);
			input = new inputFile();
			//string filename = "C:\\test.wav";
			string filename = "C:\\origin_cbr128kbps.wav";

			FileStream fs = new FileStream(filename,FileMode.Open,FileAccess.Read);
			int headersize = 44;
			input.header = new byte[headersize];
			Console.WriteLine("Header copied");
			fs.Read(input.header,0,headersize);
			int length = Convert.ToInt32(fs.Length-headersize);
			input.data = new byte[length];
			fs.Read(input.data,0,length);
			Console.WriteLine("Data copied");
			input.pointer = 0;
			input.length = (uint) length;
		}

		unsafe public void TestRun()
		{
			try
			{
				if ( Win32API.SDL_Init((int)(SDL_INIT.AUDIO)) < 0 ) 
				{
					Console.WriteLine("Unable to init SDL: {0}", Win32API.SDL_GetError());
				}
				else
				{
					Console.WriteLine("SDL_Init succeeded !!!");
				}

				SDL_AudioSpec fmt;
				SDL_AudioSpec fmt2;
				
				#region Init Audio specs
								
				/* Set 16-bit stereo audio at 22Khz */
				fmt.freq = input.Frequency;							// eg: 22050
				fmt.format = (ushort) AUDIO_FORMAT.AUDIO_S16LSB;
				fmt.channels = input.Channels;						// eg: 2;
				fmt.silence = 255;
				fmt.samples = Convert.ToUInt16(Math.Pow(2,15)-1);		
				fmt.size = 0;
				fmt.callback = FMT_CALLBACK;
				fmt.userdata = 0;//new IntPtr();
				fmt.Print();

				fmt2.freq = input.Frequency;						// eg: 22050
				fmt2.format = (ushort) AUDIO_FORMAT.AUDIO_S16MSB;
				fmt2.channels = input.Channels;						// eg: 2;
				fmt2.silence = 255;
				fmt2.samples = Convert.ToUInt16(Math.Pow(2,10)-1);		
				fmt2.size = 0;
				fmt2.callback = FMT_CALLBACK;
				fmt2.userdata = 0;//new IntPtr();
				#endregion

				/* Open the audio device and start playing sound! */
				if ( Win32API.SDL_OpenAudio(ref fmt, ref fmt2) < 0 ) 
				{
					Console.WriteLine("Unable to open audio: {0}",Win32API.SDL_GetError());
					goto _finally;
				}
				fmt2.Print();

				bool quit = false;
				while (!quit)
				{
					int c;
					string str;
					Console.WriteLine("Options:");
					Console.WriteLine("Press ... to ...");
					Console.WriteLine("... \'p\' ... \"Start Playing\"");
					Console.WriteLine("... \'s\' ... \"Stop Playing:");
					Console.WriteLine("... \'x\' ... \"Exit Program\"");
					Console.WriteLine("... \'e\' ... \"Error code\"");
					str = Console.ReadLine();
					if (str.Length > 0)
						c = str[0];	// c := first character entered
					else
						c = '@';	// c := undefined symbol

					switch(c)
					{
						case 'p':
							Console.WriteLine("Start Playing");
							try
							{
								Win32API.SDL_PauseAudio(0);				// still generates error message
							}
							catch (Exception e)
							{
								Console.WriteLine(Win32API.SDL_GetError());
								int err = Marshal.GetLastWin32Error();
								Console.WriteLine("Win32ErrorNumber = " + err);
								Win32Exception w32e = new Win32Exception(err);
								Console.WriteLine(w32e.ToString());
							}
							finally
							{
								Console.WriteLine("finally");
							}
							Console.Write(c);
							break;
						case 's':
							Console.WriteLine("Stop Playing");
							Win32API.SDL_PauseAudio(1);				// still generates error message
							break;
						case 'x':
							Console.WriteLine("Exit Program");
							quit = true;
							break;
						case 'e':
							Console.WriteLine("Error code = " + new Win32Exception(Marshal.GetLastWin32Error()).ToString());
							Console.WriteLine(Win32API.SDL_GetError());
							break;
						default:
							Console.WriteLine("Invalid option. Try again");
							break;
					}
				}

				Win32API.SDL_CloseAudio();				
				Console.WriteLine("SDL_CloseAudio succeeded !!!");

				Win32API.SDL_Quit();
				Console.WriteLine("SDL_Quit succeeded !!!");
			
			_finally:	//goto label
			;//skip
			}
			catch(Exception e)
			{
				Console.WriteLine(e.ToString());
			}
			finally
			{
				Console.WriteLine("End TestPlayer");
			}
		}

		unsafe public delegate void CallBackFunction(int userdata, byte* stream, int len);
		
		private struct inputFile
		{
			public byte[] header;
			public byte[] data;
			public uint pointer;
			public uint length;

			public int Frequency
			{
				get 
				{
					int res = (header[24] << 0) + (header[25] << 8) + (header[26] << 16) + (header[27] << 24);
					return res;
				}
			}

			public byte Channels
			{
				get 
				{
					byte res = Convert.ToByte((header[22] << 0) + (header[23] << 8));
					return res;
				}
			}

			public uint dataLeft
			{
				get 
				{
					return length-pointer;
				}
			}
		}

		unsafe public void FillBuffer(int usrdata, byte *stream, int len)
		{
			int i = 0;
			try
			{
				for(i = 0; i < len; i++)
				{
					stream[i] = input.data[input.pointer];
					input.pointer++;
				}
//				Console.WriteLine(input.pointer);
				Console.WriteLine("Error = " + Win32API.SDL_GetError());
			}
			catch(Exception e)
			{
				Console.WriteLine("i = " + i);
				Console.WriteLine("Error Callback: "+ e.ToString());
			}
			finally
			{
				Console.WriteLine("End CallBack");
			}
		}
	}

	class Win32API
	{
		[DllImport("SDL.dll")]
		public static extern int SDL_Init(
			int flags
			);

		[DllImport("SDL.dll")]
		[return : MarshalAs(UnmanagedType.LPStr)]
		public static extern string SDL_GetError();

		[DllImport("SDL.dll")]
		public static extern void SDL_Quit();

		[DllImport("SDL.dll" , SetLastError=true)]
		public static extern void SDL_PauseAudio(
			int pause_on
			);

		[DllImport("SDL.dll")]
		unsafe public static extern int SDL_OpenAudio(
			ref SDL_AudioSpec desired,
			ref SDL_AudioSpec obtained
			);

		[DllImport("SDL.dll")]
		public static extern void SDL_CloseAudio();

//		[DllImport("SDL.dll")]
//		unsafe public static extern void SDL_MixAudio(
//			byte* dst,		//uint8*
//			byte* src,		//uint8*
//			uint len,		//uint32
//			int volume		//int
//			);

//		[DllImport("SDL.dll")]
//		public static extern void SDL_Delay(int ms);
	}

	enum SDL_INIT
	{
		TIMER = 0x00000001,
		AUDIO = 0x00000010,
		VIDEO = 0x00000020,
		CDROM = 0x00000100,
		JOYSTICK = 0x00000200,
		NOPARACHUTE = 0x00100000,	/* Don't catch fatal signals */
		EVENTTHREAD = 0x01000000,	/* Not supported on all OS's */
		EVERYTHING = 0x0000FFF
	}

	enum  AUDIO_FORMAT
	{
		AUDIO_U8 = 0x0008,		/* Unsigned 8-bit samples */
		AUDIO_S8 = 0x8008,		/* Signed 8-bit samples */
		AUDIO_U16LSB = 0x0010,		/* Unsigned 16-bit samples */
		AUDIO_S16LSB = 0x8010,		/* Signed 16-bit samples */
		AUDIO_U16MSB = 0x1010,		/* As above, but big-endian byte order */
		AUDIO_S16MSB = 0x9010,		/* As above, but big-endian byte order */
		AUDIO_U16 = AUDIO_U16LSB,
		AUDIO_S16 = AUDIO_S16LSB,
	}

	[StructLayout(LayoutKind.Sequential)]
	public unsafe struct SDL_AudioSpec 
	{
		/* Set 16-bit stereo audio at 22Khz */
		public int freq;				//int
		public ushort format;			//uint16
		public byte channels;			//uint8
		public byte silence;			//uint8
		public ushort samples;			//uint16
		public uint size;				//uint32
		public TestPlayer.CallBackFunction callback;
		public int userdata;			//void*

		public void Print()
		{
			Console.WriteLine("AudioSpec:");
			Console.WriteLine("\tfrequency = \t" +  freq);
			Console.WriteLine("\tformat =\t" + format);
			Console.WriteLine("\tchannels =\t" + channels);
			Console.WriteLine("\tsilence =\t" + silence);
			Console.WriteLine("\tsamples =\t" + samples);
			Console.WriteLine("\tsize =\t" +size);
			Console.WriteLine("etc...");
		}
	}

	public struct sample 
	{
		public byte[] data;	//Uint8 *data;
		public uint dpos;	//Uint32 dpos;
		public uint dlen;	//Uint32 dlen;
	}
}


using System;

namespace SDL2
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	public class Class1
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
	
		[STAThread]
		static void Main(string[] args)
		{
			TestPlayer tp = new TestPlayer();
			tp.TestRun();
			Console.Write("Press any key to quit ...");
			Console.Read();
		}
	}
}

 

Acho q a tentativa eh valida...

 

Boa sorte..!!!

 

Abraços...

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.