/// <summary>
        /// Play the specified intro/loop (in order).
        /// </summary>
        /// <param name="intro">The path to the intro-part to play.</param>
        /// <param name="loop">The path to the loop-part to play.</param>
        public void Play(string intro, string loop)
        {
            bool play_intro = !string.IsNullOrWhiteSpace(intro);
            bool play_loop  = !string.IsNullOrWhiteSpace(loop);

            //Stop all playbacks.
            Stop();

            //Play intro?
            #region Intro
            if (play_intro)
            {
                string randomizer = "";

                //Check if the shuffle list contains values.
                if (Shuffle_OneShot != null && Shuffles_OneShot.Count > 0)
                {
                    //Check if the specified one-shot path is a directory.
                    FileAttributes attr = File.GetAttributes(intro);
                    if (attr.HasFlag(FileAttributes.Directory))
                    {
                        //Get all files from the specified one-shot directory.
                        string[] files = GetFiles(intro, "*.wav|*.mp3|*.ogg", SearchOption.TopDirectoryOnly);

                        //Take a number from the shuffle list.
                        int random = Shuffle_OneShot[0];
                        //Remove the number we took.
                        Shuffle_OneShot.RemoveAt(0);

                        //Get the matching file path.
                        randomizer = files[random];
                        //Only use the file name of the path.
                        randomizer = $"\\{Path.GetFileName(randomizer)}";
                    }
                }

                //Go through all one-shot devices.
                for (int i = 0; i < Audio_File_Reader_OneShot.Length; ++i)
                {
                    string file = $"{intro}{randomizer}";
                    if (File.Exists(file) == false)
                    {
                        break;
                    }

                    //Get the audio file to play. If intro is a directory, we add a "random" audio file to the end of it.
                    Audio_File_Reader_OneShot[i] = new AudioFileReader(file);

                    //Set the volume of the playback.
                    Audio_File_Reader_OneShot[i].Volume = (float)(Playback_Volumes[i] / 100.0);

                    //Create a new playback device.
                    Playback_Devices_OneShot[i] = new WaveOut(WaveCallbackInfo.FunctionCallback());

                    //Set the playback device's output device.
                    Playback_Devices_OneShot[i].DeviceNumber = Playback_Devices[i].ID;

                    //Initialize the playback device's audio.
                    Playback_Devices_OneShot[i].Init(Audio_File_Reader_OneShot[i]);
                }
            }
            #endregion

            //Is there a loop required?
            #region Loop
            if (play_loop)
            {
                string randomizer = "";

                //Check if the shuffle list contains values.
                if (Shuffles_Loop != null && Shuffles_Loop.Count > 0)
                {
                    //Check if the specified one-shot path is a directory.
                    FileAttributes attr = File.GetAttributes(loop);
                    if (attr.HasFlag(FileAttributes.Directory))
                    {
                        //Get all files from the specified loop directory.
                        string[] files = GetFiles(loop, "*.wav|*.mp3|*.ogg", SearchOption.TopDirectoryOnly);

                        //Take a number from the shuffle list.
                        int random = Shuffle_Loop[0];
                        //Remove the number we took.
                        Shuffle_Loop.RemoveAt(0);

                        //Get the matching file path.
                        randomizer = files[random];
                        //Only use the file name of the path.
                        randomizer = $"\\{Path.GetFileName(randomizer)}";
                    }
                }

                //Go through all loop devices.
                for (int i = 0; i < Playback_Devices_Loop.Length; ++i)
                {
                    string file = $"{intro}{randomizer}";
                    if (File.Exists(file) == false)
                    {
                        break;
                    }

                    //Get the audio file to play. If loop is a directory, we add a "random" audio file to the end of it.
                    Audio_File_Reader_Loop[i] = new AudioFileReader(file);

                    //Set the volume of the playback.
                    Audio_File_Reader_Loop[i].Volume = (float)(Playback_Volumes[i] / 100.0);

                    //Create a new loop stream (for looping).
                    LoopStreams[i] = new LoopStream(Audio_File_Reader_Loop[i]);

                    //Create a new playback device.
                    Playback_Devices_Loop[i] = new WaveOut();

                    //Set the playback device's output device.
                    Playback_Devices_Loop[i].DeviceNumber = Playback_Devices[i].ID;

                    //Initialize the playback device's audio.
                    Playback_Devices_Loop[i].Init(LoopStreams[i]);
                }
            }
            #endregion

            if (play_intro) //Only play the intro...
            {
                if (Playback_Devices_OneShot[0] != null)
                {
                    Playback_Devices_OneShot[0].Play();
                }
                if (Playback_Devices_OneShot[1] != null)
                {
                    Playback_Devices_OneShot[1].Play();
                }

                //Wait for intro to finish then play the loop.
                if (play_loop)
                {
                    Playback_Devices_OneShot[0].PlaybackStopped += (pbss, pbse) =>
                    {
                        if (Playback_Devices_Loop[0] != null)
                        {
                            Playback_Devices_Loop[0].Play();
                        }
                        if (Playback_Devices_Loop[1] != null)
                        {
                            Playback_Devices_Loop[1].Play();
                        }
                    };
                }
            }
            else if (play_loop) //No intro to play, only play the loop...
            {
                if (Playback_Devices_Loop[0] != null)
                {
                    Playback_Devices_Loop[0].Play();
                }
                if (Playback_Devices_Loop[1] != null)
                {
                    Playback_Devices_Loop[1].Play();
                }
            }
        }
Beispiel #2
0
        static async Task TestWavFile(string path)
        {
            if (!File.Exists(path))
            {
                return;
            }

            float[] buffer = null;
            using (AudioFileReader reader = new AudioFileReader(path))
            {
                buffer = new float[reader.Length];
                reader.Read(buffer, 0, buffer.Length);
            }

            int index = 0;

            do
            {
                if (index > buffer.Length)
                {
                    break;
                }
                Logger.Log("Parsing Index " + index.ToString() + " - " + (index + 10000).ToString());
                float[] partOfBuffer = new float[10000];
                for (int i = 0; i < partOfBuffer.Length; i++)
                {
                    if (index + i >= buffer.Length)
                    {
                        break;
                    }
                    partOfBuffer[i] = buffer[index + i];
                }
                index += 10000;
                //Logger.Log(BufferToDataString(partOfBuffer, 0, 1000));
                try
                {
                    var payload = new Temp()
                    {
                        audioData = partOfBuffer, chordData = string.Empty
                    };
                    string json = JsonConvert.SerializeObject(payload);

                    var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
                    var response    = await httpClient.PostAsync("api/Essentia", httpContent);

                    if (response.Content != null)
                    {
                        var responseContent = await response.Content.ReadAsStringAsync();

                        var truckload = JsonConvert.DeserializeObject <Temp>(responseContent);
                        if (truckload is Temp)
                        {
                            Temp t = truckload as Temp;
                            Logger.Log("Chord: " + t.chordData);
                        }
                    }
                }
                catch (Exception e)
                {
                    Logger.Log(e.Message);
                    ;
                }
            }while (true);
            return;
        }
Beispiel #3
0
        private static void AnalyzeWaveFile(string path)
        {
            using (var log = new Log("waveFile.log"))
            {
                PureTones.ClearTones();
                //PureTones.AddLowTone(0);
                //PureTones.AddHighTone(645);

                //PureTones.AddTonePair(794, 524); // Station 2
                //PureTones.AddTonePair(1084, 794); // Station 3
                //PureTones.AddTonePair(716, 645); // Station 6

                PureTones.TryAddHighTone(794);
                PureTones.TryAddHighTone(881);
                PureTones.TryAddHighTone(524);
                PureTones.TryAddHighTone(1084);
                //PureTones.AddHighTone(881);
                PureTones.TryAddHighTone(645);
                PureTones.TryAddHighTone(716);
                PureTones.TryAddHighTone(384);
                PureTones.TryAddHighTone(547);
                PureTones.TryAddHighTone(802);
                PureTones.TryAddHighTone(346);
                PureTones.TryAddHighTone(426);
                PureTones.TryAddHighTone(582);
                PureTones.TryAddHighTone(757);
                PureTones.TryAddHighTone(592);
                PureTones.TryAddHighTone(473);

                DtmfClassification.ClearAllTones();


                DtmfTone custom1 = new DtmfTone(794, 0, PhoneKey.Custom1);
                DtmfTone custom2 = new DtmfTone(881, 0, PhoneKey.Custom2);
                DtmfTone custom3 = new DtmfTone(524, 0, PhoneKey.Custom3);
                DtmfTone custom4 = new DtmfTone(1084, 0, PhoneKey.Custom4);
                //DtmfTone custom5 = new DtmfTone(881, 0, PhoneKey.Custom5);
                DtmfTone custom6  = new DtmfTone(645, 0, PhoneKey.Custom6);
                DtmfTone custom7  = new DtmfTone(716, 0, PhoneKey.Custom7);
                DtmfTone custom8  = new DtmfTone(384, 0, PhoneKey.Custom8);
                DtmfTone custom9  = new DtmfTone(547, 0, PhoneKey.Custom9);
                DtmfTone custom10 = new DtmfTone(802, 0, PhoneKey.Custom10);
                DtmfTone custom11 = new DtmfTone(346, 0, PhoneKey.Custom11);
                DtmfTone custom12 = new DtmfTone(426, 0, PhoneKey.Custom12);
                DtmfTone custom13 = new DtmfTone(582, 0, PhoneKey.Custom13);
                DtmfTone custom14 = new DtmfTone(757, 0, PhoneKey.Custom14);
                DtmfTone custom15 = new DtmfTone(592, 0, PhoneKey.Custom15);
                DtmfTone custom16 = new DtmfTone(473, 0, PhoneKey.Custom16);

                DtmfClassification.AddCustomTone(custom1);
                DtmfClassification.AddCustomTone(custom2);
                DtmfClassification.AddCustomTone(custom3);
                DtmfClassification.AddCustomTone(custom4);
                //DtmfClassification.AddCustomTone(custom5);
                DtmfClassification.AddCustomTone(custom6);
                DtmfClassification.AddCustomTone(custom7);
                DtmfClassification.AddCustomTone(custom8);
                DtmfClassification.AddCustomTone(custom9);
                DtmfClassification.AddCustomTone(custom10);
                DtmfClassification.AddCustomTone(custom11);
                DtmfClassification.AddCustomTone(custom12);
                DtmfClassification.AddCustomTone(custom13);
                DtmfClassification.AddCustomTone(custom14);
                DtmfClassification.AddCustomTone(custom15);
                DtmfClassification.AddCustomTone(custom16);


                using (var audioFile = new AudioFileReader(path))
                {
                    foreach (var occurence in audioFile.DtmfTones())
                    {
                        if (occurence.Duration.TotalSeconds >= .5)
                        {
                            log.Add(
                                $"{occurence.Position.TotalSeconds:00.000} s "
                                + $"({occurence.Channel}): "
                                + $"{occurence.DtmfTone.Key} key "
                                + $"(duration: {occurence.Duration.TotalSeconds:00.000} s)");
                        }
                    }
                }
            }
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            Console.WriteLine(Double(2));

            HelloWorld();

            Console.WriteLine(Double(10));

            string Path = "chordtest_128_1.wav";

            if (File.Exists(Path))
            {
                int     outsideRead   = 0;
                float[] outsideBuffer = null;
                using (AudioFileReader reader = new AudioFileReader(Path))
                {
                    float[] buffer = new float[reader.Length];
                    outsideRead   = reader.Read(buffer, 0, buffer.Length);
                    outsideBuffer = buffer;
                }

                StringBuilder sb = new StringBuilder(outsideBuffer.Length * 6);
                foreach (float f in outsideBuffer)
                {
                    if (f == 0)
                    {
                        continue;
                    }
                    sb.Append(f.ToString() + ";");
                }
                System.IO.File.WriteAllText(@"WavAsString.txt", sb.ToString());
                Console.WriteLine("Success");


                /*for(int i = 0; i < buffer.Length; i = i + 256)
                 * {
                 *   string s = string.Empty;
                 *   for(int j = 0; j < 256; j++)
                 *   {
                 *       s += Convert.ToString(buffer[j + i]);
                 *   }
                 *   Console.WriteLine(s);
                 * }*/

                //int counter = 0;
                //do
                //{
                //    Console.WriteLine("---- Attempt: " + counter + " ----");
                //    float sum = 0.0f;
                //    for (int i = 0; i < outsideBuffer.Length; i++)
                //    {
                //        sum += outsideBuffer[i];
                //    }
                //    float externSum = TestFloatArray(outsideBuffer, outsideBuffer.Length);
                //    Console.WriteLine("Intern: " + sum + " -- " + "Extern: " + externSum);

                //    int[] array = new int[101];
                //    int intSume = 0;
                //    for (int i = 0; i < array.Length; i++)
                //    {
                //        array[i] = i;
                //        intSume += i;
                //    }
                //    int externIntSum = TestIntArray(array, array.Length);
                //    Console.WriteLine("Intern: " + intSume + " -- " + "Extern: " + externIntSum);

                //    counter++;
                //}
                //while (counter < 1);

                string s = TestFloatArrayAndString(outsideBuffer, outsideBuffer.Length);
                Console.WriteLine(s);

                string chords = CalculateChords(outsideBuffer, outsideBuffer.Length /*, 1, 44100, 2048, 1024*/);

                Console.WriteLine(chords);
            }
        }
Beispiel #5
0
        private void NewBroadcast()
        {
            AudioFileReader reader;
            var             file = GetFilename();

            if (file == null)
            {
                return;
            }
            else
            {
                reader = new AudioFileReader(file);
            }

            var duration = (rbLiveBroadcast.Checked) ? dtpDuration.Value.TimeOfDay : reader.TotalTime;

            var broadcast    = new BroadcastInfo(currentUser.Username, StartTime, duration, BroadcastType, MediaType, txtDescription.Text);
            var planRequest  = new PlanBroadcastRequest(currentUser, broadcast);
            var planResponse = client.SendAndRecieve <PlanBroadcastResponse>(planRequest);

            if (planRequest != null)
            {
                switch (planResponse.Result)
                {
                case PlanBroadcastResult.CanUpload:
                    break;

                case PlanBroadcastResult.CannotUpload:
                    MessageBox.Show("Hlášení koliduje s jiným(i) hlášením(i), zvolte, prosím, jiný čas.");
                    return;

                case PlanBroadcastResult.CanUploadIfAdmin:
                    var result = MessageBox.Show("Hlášení koliduje s jiným(i) hlášením(i), chcete tato hlášení odstranit?", "Otázka", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == DialogResult.Yes)
                    {
                        break;
                    }
                    else
                    {
                        return;
                    }
                }
            }
            else
            {
                return;
            }

            if (!rbLiveBroadcast.Checked)
            {
                var settings       = Settings.Default;
                var uploadRequest  = new UploadBroadcastRequest(currentUser, broadcast, MediaType.MP3, settings.BROADCAST_PORT, settings.TRANSFER_BUFFER_SIZE); //TODO: Media file detection
                var uploadResponse = client.SendAndRecieve <UploadBroadcastResponse>(uploadRequest);
                if (uploadResponse != null)
                {
                    switch (uploadResponse.Result)
                    {
                    case UploadBroadcastResult.Success:
                        FileStreamer streamer = new FileStreamer(file, settings.TRANSFER_BUFFER_SIZE, settings.SERVER_IP, settings.BROADCAST_PORT);     //TODO: From settings...
                        streamer.Start();
                        MessageBox.Show("Vaše hlášení bylo úspěšně naplánováno.", "Oznámení", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.Close();
                        break;

                    case UploadBroadcastResult.CollissionBlocked:
                        MessageBox.Show("Hlášení koliduje s jiným(i) hlášením(i), zvolte, prosím, jiný čas.", "Upozornění", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        break;
                    }
                }
                else
                {
                    return;
                }
            }
        }
Beispiel #6
0
        private static IEnumerable <PitchUnit> LoadAudioFile(string fileName, bool play)
        {
            using (var playerReader = new AudioFileReader(fileName))
                using (var player = new WaveOutEvent())
                {
                    if (play)
                    {
                        player.Init(playerReader);
                        player.Play();
                    }

                    var startTime = Environment.TickCount;

                    const int analysisUnit    = 4096;
                    const int pitchWindowSize = 1024;

                    using (var reader = new AudioFileReader(fileName))
                    {
                        var provider   = reader.ToSampleProvider().ToMono();
                        var sampleRate = provider.WaveFormat.SampleRate;
                        var samples    = new float[analysisUnit];

                        for (var unitIndex = 0; ; unitIndex++)
                        {
                            if (play)
                            {
                                var waitTime = (int)(startTime + unitIndex * analysisUnit * 1000.0 / sampleRate) - Environment.TickCount;
                                if (waitTime > 0)
                                {
                                    Thread.Sleep(waitTime);
                                }
                            }

                            for (var readSamples = 0; readSamples < samples.Length;)
                            {
                                var count = provider.Read(samples, readSamples, samples.Length - readSamples);
                                if (count == 0)
                                {
                                    yield break;
                                }
                                readSamples += count;
                            }

                            // 実効値を求める
                            var squared = 0.0;
                            for (var i = 0; i < samples.Length; i++)
                            {
                                squared += samples[i] * samples[i];
                            }
                            var rms = Math.Sqrt(squared / samples.Length);

                            // 512 ずつずらしながらピッチ検出
                            const int pitchOffsetDelta = 512;
                            var       f0s = new List <double>((analysisUnit - pitchOffsetDelta) / pitchOffsetDelta);
                            for (var offset = 0; offset <= analysisUnit - pitchWindowSize; offset += pitchOffsetDelta)
                            {
                                var f = McLeodPitchMethod.EstimateFundamentalFrequency(
                                    sampleRate,
                                    new ReadOnlySpan <float>(samples, offset, pitchWindowSize)
                                    );

                                if (f.HasValue)
                                {
                                    f0s.Add(f.Value);
                                }
                            }

                            if (f0s.Count == 0)
                            {
                                continue;
                            }

                            f0s.Sort();
                            var f0 = f0s[f0s.Count / 2]; // 中央値

                            var normalizedPitch = NormalizePitch(f0);
                            if (normalizedPitch.HasValue)
                            {
                                yield return(new PitchUnit(unitIndex, rms, normalizedPitch.Value));
                            }
                        }
                    }
                }
        }
Beispiel #7
0
 public LoopingFileReader(AudioFileReader reader)
 {
     _reader = reader;
 }
        public static async Task <string> Download(string content)
        {
            var errorCount = 0;

Retry:
            try
            {
                var fileName = Path.Combine(Vars.CacheDir, Conf.GetRandomFileName() + "USER.mp3");
                Bridge.ALog($"(E5) 正在下载 TTS, 文件名: {fileName}, 方法: {Vars.CurrentConf.ReqType}");
                if (Vars.CurrentConf.ReqType == RequestType.ApplicationXWwwFormUrlencoded || Vars.CurrentConf.ReqType == RequestType.TextPlain)
                {
                    Bridge.ALog("POST 模式: text/plain / application/x-www-form-urlencoded");
                    // 配置 Headers
                    var uploader = WebRequest.CreateHttp(Vars.CurrentConf.CustomEngineURL);
                    uploader.Method = "POST";
                    if (Vars.CurrentConf.HttpAuth)
                    {
                        uploader.Credentials     = new NetworkCredential(Vars.CurrentConf.HttpAuthUsername, Vars.CurrentConf.HttpAuthPassword);
                        uploader.PreAuthenticate = true;
                    }
                    foreach (var header in Vars.CurrentConf.Headers)
                    {
                        Bridge.ALog($"添加 Header: {header.Name}, 值 {header.Value}");
                        uploader.Headers.Add(header.Name, header.Value);
                    }
                    uploader.ContentType = Vars.CurrentConf.ReqType == RequestType.ApplicationXWwwFormUrlencoded ? "application/x-www-form-urlencoded" : "text/plain";

                    // 准备数据
                    var data       = Encoding.UTF8.GetBytes(Vars.CurrentConf.PostData);
                    var dataStream = uploader.GetRequestStream();
                    dataStream.Write(data, 0, data.Length);
                    dataStream.Close();
                    uploader.ContentLength = data.Length;

                    // 等响应
                    using (var res = uploader.GetResponse())
                    {
                        // 写数据
                        using (var writer = new StreamWriter(File.OpenWrite(fileName))
                        {
                            AutoFlush = true
                        })
                        {
                            byte[] responseData = new byte[res.ContentLength];
                            res.GetResponseStream().Read(responseData, 0, responseData.Length);
                            writer.Write(responseData);
                        }
                    }
                }
                else if (Vars.CurrentConf.ReqType == RequestType.MultipartFormData)
                {
                    using (var httpClient = new HttpClient())
                    {
                        var form = new MultipartFormDataContent();
                        // 配置 Headers
                        if (Vars.CurrentConf.HttpAuth)
                        {
                            var authArray = Encoding.UTF8.GetBytes($"{Vars.CurrentConf.HttpAuthUsername}:{Vars.CurrentConf.HttpAuthPassword}");
                            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authArray));
                        }
                        foreach (var header in Vars.CurrentConf.Headers)
                        {
                            Bridge.ALog($"添加 Header: {header.Name}, 值 {header.Value}");
                            httpClient.DefaultRequestHeaders.Add(header.Name, header.Value);
                        }
                        // 转换数据
                        var postItems = JsonConvert.DeserializeObject <List <Header> >(Vars.CurrentConf.PostData);
                        foreach (var item in postItems)
                        {
                            var data = Convert.FromBase64String(item.Value);
                            form.Add(new ByteArrayContent(data, 0, data.Length), item.Name);
                        }
                        // 抓结果
                        using (var res = await httpClient.PostAsync(Vars.CurrentConf.CustomEngineURL, form))
                        {
                            res.EnsureSuccessStatusCode();
                            // 写数据
                            using (var writer = new StreamWriter(File.OpenWrite(fileName))
                            {
                                AutoFlush = true
                            })
                            {
                                var responseData = await res.Content.ReadAsByteArrayAsync();

                                writer.Write(responseData);
                            }
                        }
                    }
                }
                else
                {
                    Bridge.ALog("GET 模式");
                    using (var downloader = new WebClient())
                    {
                        downloader.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36");
                        foreach (var header in Vars.CurrentConf.Headers)
                        {
                            Bridge.ALog($"添加 Header: {header.Name}, 值 {header.Value}");
                            downloader.Headers.Add(header.Name, header.Value);
                        }
                        if (Vars.CurrentConf.HttpAuth)
                        {
                            downloader.Credentials = new NetworkCredential(Vars.CurrentConf.HttpAuthUsername, Vars.CurrentConf.HttpAuthPassword);
                        }
                        await downloader.DownloadFileTaskAsync(Vars.CurrentConf.CustomEngineURL.Replace("$TTSTEXT", content), fileName);
                    }
                }
                // validate if file is playable
                using (var reader = new AudioFileReader(fileName)) { }
                return(fileName);
            }
            catch (Exception ex)
            {
                Bridge.ALog($"(E5) TTS 下载失败: {ex.Message}");
                errorCount += 1;
                Vars.TotalFails++;
                if (errorCount <= Vars.CurrentConf.DownloadFailRetryCount)
                {
                    goto Retry;
                }
                return(null);
            }
        }
        private void dataGridViewParticipants_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // Initialize audioreader so we can verify if the files found are playable
            AudioFileReader audioFileReaderTest = null;
            var             senderGrid          = (DataGridView)sender;

            if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
                e.RowIndex >= 0 && e.RowIndex < senderGrid.Rows.Count - 1)
            {
                //Button Clicked - Execute Code Here
                openFileDialog1.Title    = "Select musicfile for:" + senderGrid[1, e.RowIndex].Value.ToString() + " " + senderGrid[2, e.RowIndex].Value.ToString();
                openFileDialog1.FileName = string.Empty;
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        // Make the path relative if possible.
                        if (openFileDialog1.FileName.Substring(0, Application.StartupPath.Length) == Application.StartupPath)
                        {                                                                                                      // Remove startpath
                            openFileDialog1.FileName = openFileDialog1.FileName.Substring(Application.StartupPath.Length + 1); //Also remove the backslash from path
                        }

                        // Calculate MD5 for musicfile to verify that no other participant already has this file
                        string MD5 = FormMusicPlayer.getMD5HashFromFile(openFileDialog1.FileName);

                        // First check so no other participant already has this file
                        for (int i = 0; i < senderGrid.Rows.Count - 1; i++)
                        {
                            if ((i != e.RowIndex && senderGrid[9, i].Value.ToString() == openFileDialog1.FileName) || (senderGrid[12, i].Value.ToString() == openFileDialog1.FileName))
                            {
                                MessageBox.Show("File already connected to participant " + senderGrid[1, i].Value + " " + senderGrid[2, i].Value + "\n\nFile not connected to this participant!", Properties.Resources.CAPTION_DUPLICATE_USE, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                MD5 = string.Empty;  //Remove MD5 to indicate that the file isn't connected
                            }
                        }

                        // Check MD5 for musicfile so no other participant already has this file
                        for (int i = 0; i < senderGrid.Rows.Count - 1; i++)
                        {
                            if (!string.IsNullOrEmpty(MD5))
                            {
                                if ((i != e.RowIndex && senderGrid[10, i].Value.ToString() == MD5) || (senderGrid[13, i].Value.ToString() == MD5))
                                {
                                    MessageBox.Show("Identical file content already connected to participant " + senderGrid[1, i].Value + " " + senderGrid[2, i].Value + "\n\nFile not connected to this participant!", Properties.Resources.CAPTION_DUPLICATE_USE, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                    MD5 = string.Empty;  //Remove MD5 to indicate that the file isn't connected
                                }
                            }
                        }

                        //Try to load the file to see if NAudio can read it. Gives an exception if we can't read it
                        audioFileReaderTest = new AudioFileReader(openFileDialog1.FileName);

                        // Do we have a MD5? If so connect file to participant
                        if (!string.IsNullOrEmpty(MD5))
                        {
                            senderGrid[8, e.RowIndex].Value  = string.Format("{0:00}:{1:00}", (int)audioFileReaderTest.TotalTime.TotalMinutes, audioFileReaderTest.TotalTime.Seconds);
                            senderGrid[9, e.RowIndex].Value  = openFileDialog1.FileName;
                            senderGrid[10, e.RowIndex].Value = FormMusicPlayer.getMD5HashFromFile(openFileDialog1.FileName);
                            senderGrid.Rows[e.RowIndex].DefaultCellStyle.ForeColor = SystemColors.ControlText;  // Restore color if it wasn't correct
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Can't verify file as a music file\n\n\n" + "Errormessage:" + ex.Message, Properties.Resources.CAPTION_INVALID_FILE, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        if (audioFileReaderTest != null)
                        {
                            // Dispose of the reader
                            audioFileReaderTest.Dispose();
                            audioFileReaderTest = null;
                        }
                    }
                }
            }
        }
Beispiel #10
0
        private void BotonGraficar_Click(object sender, RoutedEventArgs e)
        {
            var reader =
                new AudioFileReader(txtRutaArchivo.Text);



            double tiempoInicial = 0;
            double tiempoFinal   =
                reader.TotalTime.TotalSeconds;
            double frecuenciaMuestreo = reader.WaveFormat.SampleRate;

            txt_FrecuenciaDeMuestreo.Text = frecuenciaMuestreo.ToString();
            txt_TiempoInicial.Text        = "0";
            txt_TiempoFinal.Text          = tiempoFinal.ToString();

            señal = new SeñalPersonalizada();

            // Primer Señal
            señal.TiempoInicial      = tiempoInicial;
            señal.TiempoFinal        = tiempoFinal;
            señal.FrecuenciaMuestreo = frecuenciaMuestreo;

            //Construir nuestra señal a traves del archivo de audio

            var    bufferLectura    = new float[reader.WaveFormat.Channels];
            int    muestrasLeidas   = 1;
            double instanteActual   = 0;
            double intervaloMuestra = 1.0 / frecuenciaMuestreo;

            do
            {
                muestrasLeidas = reader.Read(bufferLectura, 0, reader.WaveFormat.Channels);

                if (muestrasLeidas > 0)
                {
                    double max =
                        bufferLectura.Take(muestrasLeidas).Max();
                    señal.Muestras.Add(new Muestra(0, max));
                }

                instanteActual += intervaloMuestra;
            } while (muestrasLeidas > 0);



            // Actualizar
            señal.actualizarAmplitudMaxima();

            // Definición de la amplitud máxima en función de la señal de mayor amplitud
            amplitudMaxima = señal.AmplitudMaxima;

            // Limpieza de polylines
            plnGrafica.Points.Clear();

            // Impresión de la amplitud máxima en los labels de la ventana.
            lbl_AmplitudMaxima.Text = amplitudMaxima.ToString("F");
            lbl_AmplitudMinima.Text = "-" + amplitudMaxima.ToString("F");


            if (señal != null)
            {
                // Sirve para recorrer una coleccion o arreglo
                foreach (Muestra muestra in señal.Muestras)
                {
                    plnGrafica.Points.Add(new Point((muestra.X - tiempoInicial) * scrContenedor.Width, (muestra.Y / amplitudMaxima * ((scrContenedor.Height / 2) - 30) * -1 + (scrContenedor.Height / 2))));
                }
            }

            // Línea del Eje X
            plnEjeX.Points.Clear();
            plnEjeX.Points.Add(new Point(0, scrContenedor.Height / 2));
            plnEjeX.Points.Add(new Point((tiempoFinal - tiempoInicial) * scrContenedor.Width, scrContenedor.Height / 2));

            // Línea del Eje Y
            plnEjeY.Points.Clear();
            plnEjeY.Points.Add(new Point((-tiempoInicial) * scrContenedor.Width, 0));
            plnEjeY.Points.Add(new Point((-tiempoInicial) * scrContenedor.Width, scrContenedor.Height));
        }
Beispiel #11
0
        public void Play(string _file)
        {
            try
            {
                if (state == State.Paused)
                {
                    if (audioFile.FileName != _file && !string.IsNullOrEmpty(_file))
                    {
                        audioFile = new AudioFileReader(_file);
                        if (state == State.Playing || state == State.Paused)
                        {
                            Stop();
                        }
                        jukebox.Init(audioFile);
                        jukebox.Play();
                        state = State.Playing;
                    }
                    else
                    {
                        if (state == State.Playing || state == State.Paused)
                        {
                            Stop();
                        }
                        audioFile.Position = position;
                        jukebox.Init(audioFile);
                        jukebox.Play();
                        state = State.Playing;
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(_file))
                    {
                        audioFile = new AudioFileReader(_file);
                        if (state == State.Playing || state == State.Paused)
                        {
                            Stop();
                        }
                        jukebox.Init(audioFile);
                        jukebox.Play();
                        state = State.Playing;
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(audioFile.FileName))
                        {
                            if (state == State.Playing || state == State.Paused)
                            {
                                jukebox.Stop();
                            }
                            audioFile.Position = 0;
                            jukebox.Init(audioFile);
                            jukebox.Play();
                            state = State.Playing;
                        }
                    }
                }
            }

            #region DE3UG

            catch (Exception exception)
            {
                tools.Exception(exception);
            }

            #endregion DE3UG
        }
Beispiel #12
0
        /// <summary>
        /// 我问沙勿略模式
        /// </summary>
        public static void P2MMode(NAudioRecorder n)
        {
            canDistinguish = false;
            if (FlowManage.waveOutDevice != null)
            {
                FlowManage.waveOutDevice.Dispose();
                FlowManage.waveOutDevice = null;
            }
            if (FlowManage.audioFileReader != null)
            {
                FlowManage.audioFileReader.Close();
                FlowManage.audioFileReader = null;
            }
            if (VoiceManage.ask_rec_result == string.Empty || VoiceManage.ask_rec_result == null)
            {
                u.P2M_Ask_Panel.transform.GetChild(0).gameObject.transform.GetChild(1).gameObject.SetActive(true);
                u.P2M_Ask_Panel.transform.GetChild(0).gameObject.transform.GetChild(1).gameObject.GetComponent <UILabel>().text = "对不起,我没有听清您说的话!可以再说一次吗?";
                content           = "对不起,我没有听清您说的话!可以再说一次吗?";
                voicename         = "answer";
                mt.FinishedAnswer = true;
                //mt.isFinished = true;
            }
            else
            {
                u.P2M_Ask_Panel.transform.GetChild(0).gameObject.transform.GetChild(1).gameObject.SetActive(true);
                u.P2M_Ask_Panel.transform.GetChild(0).gameObject.transform.GetChild(1).gameObject.GetComponent <UILabel>().text = VoiceManage.ask_rec_result;
                Debug.Log("小沙正在思考中...");
                string answer_result = KeywordMatch.GetAnswerByKeywordMatch(VoiceManage.ask_rec_result, mt.BeforeAskList);//AIUI.HttpPost(AIUI.TEXT_SEMANTIC_API, "{\"userid\":\"test001\",\"scene\":\"main\"}", "text=" + Utils.Encode(VoiceManage.ask_rec_result));
                if (answer_result.Equals("抱歉,这个问题我还不知道,问答结束!"))
                {
                    answer_result = KeywordMatch.GetAnswerByKeywordMatch(VoiceManage.ask_rec_result, mt.AfterAskList);
                }
                u.P2M_Ask_Panel.transform.GetChild(0).gameObject.transform.GetChild(2).gameObject.SetActive(true);
                u.P2M_Ask_Panel.transform.GetChild(0).gameObject.transform.GetChild(2).gameObject.GetComponent <UILabel>().text = answer_result;
                content           = answer_result;
                voicename         = "answer";
                mt.FinishedAnswer = true;
                if (answer_result.Equals("抱歉,这个问题我还不知道,问答结束!"))
                {
                    XmlDocument    xml  = new XmlDocument();
                    XmlDeclaration decl = xml.CreateXmlDeclaration("1.0", "utf-8", null);
                    xml.AppendChild(decl);
                    XmlElement rootEle = xml.CreateElement("root");
                    xml.AppendChild(rootEle);
                    xml.Save(mt.record_path + "/record.xml");
                    DateTime dateTime = new DateTime();
                    dateTime = DateTime.Now;
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(Application.dataPath + "/Resources/Question/record.xml");
                    XmlNode    root = xmlDoc.SelectSingleNode("root");
                    XmlElement xe1  = xmlDoc.CreateElement("问题");
                    xe1.SetAttribute("内容", VoiceManage.ask_rec_result);
                    xe1.SetAttribute("时间", dateTime.ToString());
                    root.AppendChild(xe1);
                    xmlDoc.Save(Application.dataPath + "/Resources/Question/record.xml");
                    mt.FinishedAnswer = false;
                    VoiceManage.StopSpeech();
                }
            }
            Thread thread_answer = new Thread(new ThreadStart(playVoice));

            thread_answer.IsBackground = true;
            thread_answer.Start();
            //结束界面
            //进入唤醒状态
        }
        public void CreateCurrentSongImage(AudioFile audioFile)
        {
            try
            {
                int        bytesPerSample = 0;
                WaveStream reader;
                switch (audioFile.Format.ToLower())
                {
                case ".mp3":
                    reader = new Mp3FileReader(audioFile.Path);
                    break;

                case ".wav":
                    reader = new WaveFileReader(audioFile.Path);
                    break;

                case ".aiff":
                    reader = new AiffFileReader(audioFile.Path);
                    break;

                default:
                    reader = new AudioFileReader(audioFile.Path);
                    break;
                }

                using (NAudio.Wave.WaveChannel32 channelStream = new NAudio.Wave.WaveChannel32(reader))
                {
                    //initialize the progress bar, once the audio stream has been created
                    _progBar.Maximum = (int)reader.TotalTime.TotalMilliseconds / _visEventTimer.Interval;

                    bytesPerSample = (reader.WaveFormat.BitsPerSample / 8) * channelStream.WaveFormat.Channels;

                    //Give a size to the bitmap; either a fixed size, or something based on the length of the audio
                    using (Bitmap bitmap = new Bitmap((int)Math.Round(reader.TotalTime.TotalSeconds * 80), 300))
                    {
                        int width  = bitmap.Width;
                        int height = bitmap.Height;

                        using (Graphics graphics = Graphics.FromImage(bitmap))
                        {
                            graphics.Clear(Color.White);
                            Pen bluePen = new Pen(Color.Blue);

                            int    samplesPerPixel = (int)(reader.Length / (double)(width * bytesPerSample));
                            int    bytesPerPixel   = bytesPerSample * samplesPerPixel;
                            int    bytesRead;
                            byte[] waveData = new byte[bytesPerPixel];

                            for (float x = 0; x < width; x++)
                            {
                                bytesRead = reader.Read(waveData, 0, bytesPerPixel);
                                if (bytesRead == 0)
                                {
                                    break;
                                }

                                short low  = 0;
                                short high = 0;
                                for (int n = 0; n < bytesRead; n += 2)
                                {
                                    short sample = BitConverter.ToInt16(waveData, n);
                                    if (sample < low)
                                    {
                                        low = sample;
                                    }
                                    if (sample > high)
                                    {
                                        high = sample;
                                    }
                                }
                                float lowPercent  = ((((float)low) - short.MinValue) / ushort.MaxValue);
                                float highPercent = ((((float)high) - short.MinValue) / ushort.MaxValue);
                                float lowValue    = height * lowPercent;
                                float highValue   = height * highPercent;
                                graphics.DrawLine(bluePen, x, lowValue, x, highValue);
                            }
                        }

                        _currentSongImage = new System.Drawing.Bitmap(bitmap);
                        bitmap.Dispose();
                    }
                }

                reader.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Beispiel #14
0
            public void Play(
                string file,
                float volume = 1.0f,
                bool sync    = false)
            {
                if (!File.Exists(file))
                {
                    return;
                }

                var buffer = default(BufferedWaveProvider);

                if (!sync)
                {
                    lock (this)
                    {
                        buffer = this.Buffers[this.CurrentPlayerIndex];
                        this.CurrentPlayerIndex++;

                        if (this.CurrentPlayerIndex >= MultiplePlaybackCount)
                        {
                            this.CurrentPlayerIndex = 0;
                        }
                    }
                }
                else
                {
                    buffer = this.Buffers[MultiplePlaybackCount];
                }

                if (buffer == null)
                {
                    return;
                }

                var samples = default(byte[]);

                lock (WaveBuffer)
                {
                    if (this.prevVolume != volume)
                    {
                        WaveBuffer.Clear();
                    }

                    this.prevVolume = volume;

                    if (WaveBuffer.ContainsKey(file))
                    {
                        samples = WaveBuffer[file];
                    }
                    else
                    {
                        using (var audio = new AudioFileReader(file)
                        {
                            Volume = volume
                        })
                            using (var resampler = new MediaFoundationResampler(audio, BufferedWavePlayer.OutputFormat))
                                using (var output = new MemoryStream(51200))
                                {
                                    WaveFileWriter.WriteWavFileToStream(output, resampler);
                                    output.Flush();
                                    output.Position = 0;

                                    // ヘッダをカットする
                                    var raw          = output.ToArray();
                                    var headerLength = 0;
                                    using (var wave = new WaveFileReader(output))
                                    {
                                        headerLength = (int)(raw.Length - wave.Length);
                                    }

                                    // ヘッダをスキップした波形データを取得する
                                    samples = raw.Skip(headerLength).ToArray();
                                }

                        WaveBuffer[file] = samples;
                    }
                }

                buffer.AddSamples(
                    samples,
                    0,
                    samples.Length);

#if DEBUG
                System.Diagnostics.Debug.WriteLine($"WASAPI(Buffered) Play: {file}");
#endif
            }
Beispiel #15
0
        public void PlaySound(string fileName)
        {
            var input = new AudioFileReader(fileName);

            AddMixerInput(new AutoDisposeFileReader(input));
        }
Beispiel #16
0
        private void btnReproducir_Click(object sender, RoutedEventArgs e)
        {
            if (output != null &&
                output.PlaybackState == PlaybackState.Paused)
            {
                output.Play();
                btnReproducir.IsEnabled = false;
                btnPausa.IsEnabled      = true;
                btnDetener.IsEnabled    = true;
            }
            else
            {
                reader =
                    new AudioFileReader(txtRutaArchivo.Text);

                delay =
                    new Delay(reader);
                delay.Activo = (bool)cbDelayActivo.IsChecked;

                delay.DelayInversa = (bool)cbAmplitudInvertida.IsChecked;

                delay.OffsetMilisegundos = (int)sldDelayOffset.Value;
                fades = new FadeInOutSampleProvider(
                    delay, true);
                double milisegundosFadeIn =
                    Double.Parse(txtDuracionFadeIn.Text)
                    * 1000.0;
                fades.BeginFadeIn(milisegundosFadeIn);
                fadingOut = false;
                output    = new WaveOutEvent();

                output.DeviceNumber =
                    cbSalida.SelectedIndex;

                output.PlaybackStopped += Output_PlaybackStopped;

                volume =
                    new EfectoVolumen(fades);

                volume.Volume =
                    (float)sldVolumen.Value;

                output.Init(volume);
                output.Play();

                btnDetener.IsEnabled    = true;
                btnPausa.IsEnabled      = true;
                btnReproducir.IsEnabled = false;

                lblTiempoTotal.Text =
                    reader.TotalTime.ToString().Substring(0, 8);
                lblTiempoActual.Text =
                    reader.CurrentTime.ToString().Substring(0, 8);
                sldReproduccion.Maximum =
                    reader.TotalTime.TotalSeconds;
                sldReproduccion.Value =
                    reader.CurrentTime.TotalSeconds;

                timer.Start();
            }
        }
Beispiel #17
0
        private void Yggdrasil_Load(object sender, EventArgs e) //initializes often used variables and generates GUI elements
        {
            #region Init
            int btnEdge = 60;
            int btnGap  = 20;
            changeBackground(Resources.bckgrnd_wood);
            lr            = 247;
            lg            = 241;
            lb            = 227;
            light         = Color.FromArgb(lr, lg, lb);
            dr            = 214; //214,138,105
            dg            = 138;
            db            = 105;
            decisionColor = Color.FromArgb(dr, dg, db);
            outline       = decisionColor;

            Size btnSize = new Size(btnEdge, btnEdge);

            exitBtn.Size = btnSize;
            exitBtn.BringToFront();
            exitBtn.Location = new Point(Width - btnGap - btnEdge, btnGap);

            muteBtn.Size = btnSize;
            muteBtn.BringToFront();
            muteBtn.Location = new Point(Width - btnGap * 2 - btnEdge * 2, btnGap);

            achBtn.Size     = btnSize;
            achBtn.Location = new Point(Width - btnGap * 3 - btnEdge * 3, btnGap);
            achBtn.BringToFront();

            #endregion

            #region Save File
            mySave = new SaveFile();
            if (File.Exists("save.sf"))
            {
                mySave = loadGame <SaveFile>();
            }
            else
            {
                mySave.myChars      = new int[] { 0, 1, 2, 4 };
                mySave.inStory      = 0;
                mySave.verification = getSHA1(mySave.inStory.ToString() + 42 + unlockedChars.ToString());
                mySave.achievements = new int[0];
            }
            if (mySave.verification != getSHA1(mySave.inStory.ToString() + 42 + unlockedChars.ToString()))
            {
                mySave.myChars      = new int[] { 0, 1, 2 };
                mySave.inStory      = 0;
                mySave.verification = getSHA1(mySave.inStory.ToString() + 42 + unlockedChars.ToString());
                mySave.achievements = new int[0];
            }
            myChar = JsonConvert.DeserializeObject <Character>(File.ReadAllText("files/char/" + mySave.selectedChar + ".json"));
            #endregion

            #region Tabs

            myTabs.Size     = new Size(Width + 8, Height + 26);
            myTabs.Location = new Point(-4, -22);

            #region StoryTab
            sceneLbl.MaximumSize = new Size(Width * 60 / 100, 0);
            sceneLbl.Location    = new Point((Width / 2) - sceneLbl.Width / 2, Height * 15 / 100);
            sceneLbl.Parent      = myTabs.TabPages[1];

            situationLbl.MaximumSize = new Size(Width * 60 / 100, 0);
            situationLbl.Location    = new Point((Width / 2) - situationLbl.Width / 2, Height * 20 / 100 + sceneLbl.Height);

            if (Width < 1500)
            {
                sceneLbl.Font = situationLbl.Font = main = new Font("Book Antiqua", 13.5f);
            }

            saveBtn.Size     = new Size(btnEdge, btnEdge);
            saveBtn.Location = new Point(Width - btnGap * 3 - btnEdge * 3, btnGap);

            #endregion

            unlockedChars.AddRange(mySave.myChars);
            achievements.AddRange(mySave.achievements);
            drawCharTab();

            #endregion

            #region Audio
            /* -- Audio -- */

            audioPath = "files/sound/125.mp3";

            if (outputDevice == null)
            {
                outputDevice = new WaveOutEvent();
                outputDevice.PlaybackStopped += OnPlaybackStopped;
                outputDevice.Volume           = volume / 100f;
            }
            if (audioFile == null)
            {
                audioFile = new AudioFileReader(audioPath);
                outputDevice.Init(audioFile);
            }

            outputDevice.Play();

            /* -- Audio End -- */
            #endregion

            #region Open Action
            if (mySave.inStory == 1)
            {
                storyIds.AddRange(mySave.stories);
                curStory             = JsonConvert.DeserializeObject <Story>(File.ReadAllText("files/story/" + storyIds[storyIds.Count - 1] + ".json"));
                myTabs.SelectedIndex = 1;
                loadStory(1);
                fadeInTimer.Enabled = true;
            }

            #endregion
        }
Beispiel #18
0
        /// <summary>Add ringtones to phone via file drop.</summary>
        /// <param name="files">Local file paths.</param>
        /// <returns>True if refresh is needed.</returns>
        private bool AddRemoteFiles(IEnumerable <string> files)
        {
            try
            {
                var refresh = false;
                // connect
                var device = CurrentDevice;
                if (device == null)
                {
                    return(false);
                }
                // start service
                LibiMobileDevice.Instance.Afc.afc_client_start_service(device, out AfcClientHandle client, PROGRAMNAME).ThrowOnError();
                // download Ringtones.plist
                var data      = DownloadFile(client, RINGTONESPLIST);
                var plist     = PropertyListParser.Parse(data);
                var ringtones = new Dictionary <string, string>();
                var guids     = new Dictionary <string, string>();
                foreach (var entry in (NSDictionary)((NSDictionary)plist)["Ringtones"])
                {
                    var values = (NSDictionary)entry.Value;
                    ringtones[values["Name"].ToString()] = entry.Key; // "Song name" -> "XXXX.m4r"
                    guids[entry.Key] = values["GUID"].ToString();     // "XXXX.m4r" -> "2C3003DD9E10A27B"
                }
                foreach (var file in files)
                {
                    if (!File.Exists(file))
                    {
                        continue;                     // throw exception?
                    }
                    if (!Path.GetExtension(file).Equals(RINGTONEEXTENSION))
                    {
                        continue;
                    }
                    var name = Path.GetFileNameWithoutExtension(file);
                    // get length of ringtone
                    var reader    = new AudioFileReader(file);
                    var totaltime = reader.TotalTime.TotalMilliseconds;
                    reader.Close();
                    if (ringtones.ContainsValue(name))
                    {
                        var result = MessageBox.Show(name, "Overwrite ringtone?", MessageBoxButtons.YesNoCancel);
                        if (result == DialogResult.Cancel)
                        {
                            break;
                        }
                        if (result != DialogResult.Yes)
                        {
                            continue;
                        }

                        var key = ringtones[name];
                        // modify ringtone entry
                        var value = (NSDictionary)((NSDictionary)((NSDictionary)plist)["Ringtones"])[key];
                        value["Total Time"] = new NSNumber(totaltime);
                    }
                    else
                    {
                        // generate unique filename
                        var key = RandomString("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4) + RINGTONEEXTENSION;
                        while (guids.ContainsKey(key))
                        {
                            key = RandomString("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4) + RINGTONEEXTENSION;
                        }
                        ringtones[name] = key;
                        // generate unique GUID
                        var guid = RandomString("0123456789ABCDEF", 16);
                        while (guids.ContainsValue(guid))
                        {
                            guid = RandomString("0123456789ABCDEF", 16);
                        }
                        guids[key] = guid;
                        // new ringtone entry
                        var value = new NSDictionary();
                        value["Name"]       = new NSString(name);
                        value["GUID"]       = new NSString(guid);
                        value["Total Time"] = new NSNumber(totaltime);
                        ((NSDictionary)((NSDictionary)plist)["Ringtones"])[key] = value;
                    }
                    // upload ringtone
                    UploadFile(client, Combine(RINGTONESPATH, ringtones[name]), File.ReadAllBytes(file));
                    refresh = true;
                }
                if (refresh)
                {
                    // upload new Ringtones.plist
                    var stream = new MemoryStream();
                    PropertyListParser.SaveAsBinary(plist, stream);
                    UploadFile(client, RINGTONESPLIST, stream.ToArray());
                }
                // disconnect
                client.Close();
                client.Dispose();
                device.Close();
                device.Dispose();
                return(refresh);
            }
            catch (Exception ex) { HandleException(ex); return(false); }
        }
Beispiel #19
0
 public void playSong(string Filename)
 {
     audioFileReader = new AudioFileReader(Filename);
     player.Init(audioFileReader);
     Play();
 }
Beispiel #20
0
 // Convert WAV to MP3 using libmp3lame library
 public static void WaveToMP3(string waveFileName, string mp3FileName, int bitRate = 128)
 {
     using (var reader = new AudioFileReader(waveFileName))
         using (var writer = new LameMP3FileWriter(mp3FileName, reader.WaveFormat, bitRate))
             reader.CopyTo(writer);
 }
Beispiel #21
0
        public Bitmap DrawWaveform(int height, Color color, double yScale, string name)
        {
            if (!IsEnabled)
            {
                return(null);
            }
            var reader = new AudioFileReader(Path);

            Channels       = reader.WaveFormat.Channels;
            ChannelsString = GetChannelsString(Channels);
            BitRate        = reader.WaveFormat.BitsPerSample * 2 / reader.BlockAlign;
            SampleRate     = reader.WaveFormat.SampleRate;

            // calculate number of samples
            long nSamples = reader.Length / ((BitRate * Channels) / 8);

            if (nSamples < 2)
            {
                return(null);
            }

            int    yBase        = height / 2;
            double yScaleBase   = -((double)height - 3) / 2;
            double sampleWidth  = GetSampleWidth();
            double currPosition = 0;
            // Data for current column
            int currColumn = 0;

            float minVal = float.PositiveInfinity, maxVal = float.NegativeInfinity;

            // Data for previous column
            int prevColumn = 0;
            int prevMinY = 0, prevMaxY = 0;

            // Buffer for reading samples
            float[] buffer = new float[8192];
            int     readCount;

            var points = new List <Point[]>();

            while ((readCount = reader.Read(buffer, 0, 8192)) > 0)
            {
                // process samples
                foreach (float sample in buffer.Take(readCount))
                {
                    minVal        = Math.Min(minVal, sample);
                    maxVal        = Math.Max(maxVal, sample);
                    currPosition += sampleWidth;

                    // on column change, draw to bitmap
                    if ((int)currPosition >= currColumn)
                    {
                        if (!float.IsInfinity(minVal) && !float.IsInfinity(maxVal))
                        {
                            // calculate Y coordinates for min & max
                            int minY = ClampHeight((int)(yScaleBase * yScale * minVal), (int)height / 2);
                            int maxY = ClampHeight((int)(yScaleBase * yScale * maxVal), (int)height / 2);

                            points.Add(new Point[] {
                                new Point(prevColumn, yBase + prevMinY), new Point(prevColumn, yBase + prevMaxY),
                                new Point(currColumn, yBase + maxY), new Point(currColumn, yBase + minY)
                            });

                            // save current data to previous
                            prevColumn = currColumn;
                            prevMinY   = minY;
                            prevMaxY   = maxY;
                        }

                        // update column number and reset accumulators
                        currColumn++;
                        minVal = float.PositiveInfinity;
                        maxVal = float.NegativeInfinity;
                    }
                }
            }

            VisualWidth = (int)currPosition;
            Width       = Settings.ViewToRealX(VisualWidth);
            reader.Close();
            reader.Dispose();

            return(GetWaveformImageSource(height, color, points, name));
        }
 public AutoDisposeFileReader(AudioFileReader reader, Action <int> finishCallback = null)
 {
     this.reader     = reader;
     this.WaveFormat = reader.WaveFormat;
     FinishCallback  = finishCallback;
 }
Beispiel #23
0
    public static void AskUserToRestartLevelTwo(IWavePlayer waveOutDevice, AudioFileReader audioFileReader)
    {
        waveOutDevice.Stop();

        Console.Clear();

        Console.SetCursorPosition(5, 15);
        Console.Write("Do you want to RESTART");
        Console.SetCursorPosition(13, 16);
        Console.WriteLine("Y/N");

        var check = Console.ReadKey();

        Console.Clear();

        if (check.Key.ToString().ToLower() == "y")
        {
            Console.Clear();

            PackManHydra.monsterOneCounter   = 0;
            PackManHydra.monsterTwoCounter   = 0;
            PackManHydra.monsterThreeCounter = 0;
            PackManHydra.monsterFourCounter  = 0;

            PackManHydra.points       = 0;
            PackManHydra.lives        = 3;
            PackManHydra.currentLevel = 2;

            Console.ForegroundColor = ConsoleColor.White;

            Mariyan.DrawGameBoardLevelTwo();
            Dimitar.StartCounter();

            PackManHydra.InitDotsArray(1);

            waveOutDevice.Init(audioFileReader);
            waveOutDevice.Play();

            PackManHydra.endGame = true;

            Georgi.RefreshScreen(PackManHydra.badGuysCoordinates, Mariyan.wallsLevelTwo);
        }
        else if (check.Key.ToString().ToLower() == "n")
        {
            Console.Clear();

            PackManHydra.monsterOneCounter   = 0;
            PackManHydra.monsterTwoCounter   = 0;
            PackManHydra.monsterThreeCounter = 0;
            PackManHydra.monsterFourCounter  = 0;

            PackManHydra.points       = 0;
            PackManHydra.lives        = 3;
            PackManHydra.currentLevel = 1;

            PackManHydra.endGame = true;

            PackManHydra.endLevelOne = false;

            PackManHydra.returnFromLevelTwo = false;
            Console.Clear();

            PackManHydra.Main();
        }
    }
Beispiel #24
0
        public void ApplyEffects(string InputFile, string OutputFile, Delegates.DownloadProgressChangedCallback progressCallback = null, CancellationToken cancellationToken = default)
        {
            int step = 0;

            if (Effects.Count != 0)
            {
                bool            RequiresRencoding = false;
                int             Succeeded         = 0;
                AudioFileReader Reader            = new AudioFileReader(InputFile);
                foreach (AudioEffect Effect in Effects)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }
                    step++;
                    progressCallback?.Invoke(step, -1, $"Applying effect {Effect.GetType().Name}", null);



                    if (string.IsNullOrEmpty(Effect.AudioCachePath))
                    {
                        Effect.AudioCachePath = AudioCachePath;
                    }

                    Reader.Position = 0;
                    System.Console.WriteLine($"Applying effect of type {Effect.GetType().Name}");
                    AudioEffectResult Result = Effect.ApplyEffect(ref Reader);
                    if (Result == AudioEffectResult.Completed)
                    {
                        System.Console.WriteLine("Returned S");
                        RequiresRencoding = true;
                        Succeeded        += 1;
                    }
                    else if (Result == AudioEffectResult.Failed)
                    {
                        System.Console.WriteLine("Effect Failed.");
                    }
                    else if (Result == (AudioEffectResult.Completed | AudioEffectResult.PreEncoded))
                    {
                        System.Console.WriteLine("Effect Completed + Encoded.");
                        RequiresRencoding = false;
                        Succeeded        += 1;
                    }
                }
                bool ReEncode;
                if (Succeeded == 0)
                {
                    System.Console.WriteLine("Re encoding; No effects passed");
                    ReEncode = false;
                }
                else if (RequiresRencoding)
                {
                    System.Console.WriteLine("Re encoding; Re-encoding declared as required");
                    ReEncode = true;
                }
                else
                {
                    System.Console.WriteLine("Copying Stream; Stream declared as pre-encoded");

                    ReEncode = false;
                }
                if (ReEncode)
                {
                    step++;
                    progressCallback?.Invoke(step, -1, $"Re-encoding mp3", null);

                    System.Console.WriteLine("Re-Encoding...");
                    using (var writer = new LameMP3FileWriter(OutputFile, Reader.WaveFormat, 128))
                    {
                        Reader.CopyTo(writer);
                    }
                    Reader.Dispose();
                }
                else
                {
                    step++;
                    progressCallback?.Invoke(step, -1, $"Finalizing effects", null);

                    System.Console.WriteLine("Copy Out");
                    File.Copy(Reader.FileName, OutputFile);
                }
            }
            else
            {
                File.Copy(InputFile, OutputFile);
            }
        }
Beispiel #25
0
        private Task PlaySoundOnPress(string fileName)
        {
            return(Task.Run(() =>
            {
                if (!settings.PlaySoundOnPress)
                {
                    return;
                }

                if (String.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(settings.PlaybackDevice))
                {
                    Logger.Instance.LogMessage(TracingLevel.WARN, $"PlaySoundOnPress called but File or Playback device are empty. File: {fileName} Device: {settings.PlaybackDevice}");
                    return;
                }

                if (!File.Exists(fileName))
                {
                    Logger.Instance.LogMessage(TracingLevel.WARN, $"PlaySoundOnPress called but file does not exist: {fileName}");
                    return;
                }

                Logger.Instance.LogMessage(TracingLevel.INFO, $"PlaySoundOnPress called. Playing {fileName} on device: {settings.PlaybackDevice}");
                var deviceNumber = GetPlaybackDeviceFromDeviceName(settings.PlaybackDevice); using (var audioFile = new AudioFileReader(fileName))
                {
                    using (var outputDevice = new WaveOutEvent())
                    {
                        outputDevice.DeviceNumber = deviceNumber;
                        outputDevice.Init(audioFile);
                        outputDevice.Play();
                        while (outputDevice.PlaybackState == PlaybackState.Playing)
                        {
                            System.Threading.Thread.Sleep(1000);
                        }
                    }
                }
            }));
        }
        public void Button_Click(object o, RoutedEventArgs e)
        {
            Button b = (Button)o;

            switch (b.Name)
            {
            case "GoButton":
                string text = TextBoxHandle.Text;


                TextBoxHandle.Text = "";
                Console.WriteLine(text);
                if ((automeme.IsChecked == true))
                {
                    text = memetext(text);
                }
                //save as a sound file
                const string fileName = "abusedFile.wav";

                /*using (var reader = new SpeechSynthesizer())
                 * {
                 *  foreach (var x in reader.GetInstalledVoices())
                 *      Console.WriteLine(x.VoiceInfo.Name);
                 *  reader.Rate = (int)-2;
                 *  reader.SetOutputToWaveFile(fileName);
                 *  //https://stackoverflow.com/questions/16021302/c-sharp-save-text-to-speech-to-mp3-file
                 *  reader.Speak(text);
                 * }*/

                using (var tts = new FonixTalkEngine())
                {
                    tts.Voice = (TtsVoice)Enum.Parse(typeof(TtsVoice), VoiceSelector.Text);


                    tts.SpeakToWavFile(fileName, text);
                }



                //////////
                //now output from the sound file
                using (var audioFile = new AudioFileReader(fileName))
                {
                    int selDevice = -1;
                    for (int n = -1; n < WaveOut.DeviceCount; n++)
                    {
                        var caps = WaveOut.GetCapabilities(n);
                        if (caps.ProductName.Contains("CABLE Input"))
                        {
                            selDevice = n;
                            break;
                        }
                    }
                    using (var outputDevice = new WaveOutEvent()
                    {
                        DeviceNumber = selDevice
                    })
                    {
                        outputDevice.Init(audioFile);
                        outputDevice.Volume = (float)percentagevolume;
                        outputDevice.Play();
                        while (outputDevice.PlaybackState == PlaybackState.Playing)
                        {
                            Thread.Sleep(1000);
                        }
                    }
                }



                break;

            case "CloseButton":
                Environment.Exit(0);
                break;
            }
        }
 public MusicPlayHandler(string src) : this()
 {
     PlaySrc   = src;
     SongName  = new List <string>(Directory.EnumerateFiles(src));
     audioFile = new AudioFileReader(SongName[0]);
 }
Beispiel #28
0
 public AutoDisposeFileReader(AudioFileReader reader)
 {
     this.reader     = reader;
     this.WaveFormat = reader.WaveFormat;
 }
Beispiel #29
0
        static void Main(string[] args)
        {
            Console.WriteLine("Animação ASCII : Bad Apple");

            List <String> frames      = new List <String>();
            int           quantFrames = Directory.GetFiles(@"BadApple\frames").Length;
            int           frameIndex  = 1;

            int width  = Console.WindowWidth - 1;
            int height = Console.WindowHeight - 1;

            Console.Write("Loading the animation frames, please wait : ");
            while (true)
            {
                string frame = @"BadApple\frames\" + frameIndex.ToString() + ".png";

                if (!File.Exists(frame))
                {
                    break;
                }

                using (Bitmap image = new Bitmap(frame))
                {
                    Bitmap   bmp = new Bitmap(width, height);
                    Graphics g   = Graphics.FromImage(bmp);
                    g.DrawImage(image, 0, 0, width, height);

                    StringBuilder sb    = new StringBuilder();
                    String        chars = " .*#%@";

                    for (int y = 0; y < bmp.Height; y++)
                    {
                        for (int x = 0; x < bmp.Width; x++)
                        {
                            int index = (int)(bmp.GetPixel(x, y).GetBrightness() * chars.Length);

                            if (index < 0)
                            {
                                index = 0;
                            }
                            else if (index >= chars.Length)
                            {
                                index = chars.Length - 1;
                            }
                            sb.Append(chars[index]);
                        }
                        sb.Append("\n");
                    }

                    frames.Add(sb.ToString());
                    frameIndex++;

                    int percentage = (int)((frames.Count / (float)(quantFrames)) * 100);

                    Console.SetCursorPosition(43, Console.CursorTop);
                    Console.Write("|" + percentage.ToString() + "%" + " | processed frames : " + frames.Count.ToString() + " ");
                }
            }

            AudioFileReader reader = new AudioFileReader(@"BadApple\audio.wav");
            WaveOutEvent    woe    = new WaveOutEvent();

            woe.Init(reader);
            Console.WriteLine("\n\n press ENTER to start!");
            Console.ReadLine();
            woe.Play();

            while (true)
            {
                float percentage = woe.GetPosition() / (float)reader.Length;
                int   frame      = (int)(frames.Count * percentage);
                if (frame >= frames.Count)
                {
                    break;
                }
                Console.SetCursorPosition(0, 0);
                Console.WriteLine(frames[frame].ToString());
            }
            Console.WriteLine("The END, bye:)");
            Console.ReadLine();
        }
Beispiel #30
0
 public PAudio(string AudioPath)
 {
     audioFile = new AudioFileReader(AudioPath);
     Path      = AudioPath;
 }