Search code examples
xamarin.android

Audio file problem in for loop xamarin android


Use an iterative loop to extract numbers and work well. The problem I have is I want to add a sound when completing the process and every time the process is done there will be a sound I used the following code, but the sound appears sometimes and not.

OnCreate
  _player = MediaPlayer.Create(this, Resource.Raw.beep);

  string[] words = str.Split("\n");
foreach (var word in words)
                    {
                     if (!word.Any(c => c < '0' || c > '9'))
                            {
                                txtView.Text = word;
                                _player.Start();
                                buttn.Visibility = ViewStates.Invisible;
                              _player.Stop();

                              }
                        }

Solution

  • I hope this could helps.

    OnCreate += async (sender, e) => {
    
        string s = await getNumber(anyStringArg, true, ", ");
    
        if (s != "")
        {
            txtView.Text = s;
            buttn.Visibility = ViewStates.Invisible;
    
            if (_player != null) _player.reset();
    
            try
            {
                _player = await prepareMediaPlayer(Resource.Raw.beep);
    
               _player.start();
            }
            catch (Exception ex)
            {
                // your exception handler
            }
        }
    }
    
    async Task<string> getNumber(string str, bool isAll = false, string separator = "")
    {
        if (str != "")
        {
            string[] words = str.Split("\n");
    
            // only first number match 
            if (!isAll)
            {
                int i = 0, n = words.Length();
                while (i < n && !isNumber(words[i])) i++;
                if (i < n) return words[i];
            }
    
            // all numbers
            else
            {
                List<string> nums = new List<string>();
    
                foreach (string word in words)
                {
                    if (isNumber(word))
                    {
                        nums.Add(word);
                    }
                }
    
               return String.Join(separator, nums);
            }
        }
    
        return "";
    }
    
    bool isNumber(string str)
    {
        int i = 0, n = str.Length();
        while (i < n && !(str[i] < '0' || str[i] > '9')) i++;
        return n > 0 && i == n;
    }
    
    /*  If you are not use custom Task,
         you can avoid problem on unasync Prepare()
         by invoke MediaPlayer.PrepareAsync()
         after the MediaPlayer.Create(). */
    
    async Task<MediaPlayer> prepareMediaPlayer(url)
    {
        MediaPlayer mediaPlayer;
    
        await Task.Run(() => {
             mediaPlayer = MediaPlayer.Create(this, url);
        });
    
       return mediaPlayer;
    }